s3db.js 7.3.9 → 7.3.10

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.
@@ -1 +1 @@
1
- import{customAlphabet as t,urlAlphabet as e}from"nanoid";import r from"node:zlib";import{PromisePool as i}from"@supercharge/promise-pool";import{ReadableStream as s}from"node:stream/web";import{mkdir as n,writeFile as a,readFile as o,stat as c,unlink as l,readdir as u,rm as h}from"fs/promises";import{createHash as f}from"crypto";import{chunk as d,merge as p,isString as g,isEmpty as m,invert as y,uniq as b,cloneDeep as w,get as v,set as S,isObject as _,isFunction as k}from"lodash-es";import O from"json-stable-stringify";import{S3Client as R,PutObjectCommand as j,GetObjectCommand as x,HeadObjectCommand as E,CopyObjectCommand as D,DeleteObjectCommand as A,DeleteObjectsCommand as N,ListObjectsV2Command as I}from"@aws-sdk/client-s3";import{flatten as $,unflatten as P}from"flat";import C from"fastest-validator";const T="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",M=Object.fromEntries([...T].map((t,e)=>[t,e])),L=t=>{if("number"!=typeof t||isNaN(t))return"undefined";if(!isFinite(t))return"undefined";if(0===t)return T[0];if(t<0)return"-"+L(-Math.floor(t));t=Math.floor(t);let e="";for(;t;)e=T[t%62]+e,t=Math.floor(t/62);return e},U=t=>{if("string"!=typeof t)return NaN;if(""===t)return 0;let e=!1;"-"===t[0]&&(e=!0,t=t.slice(1));let r=0;for(let e=0;e<t.length;e++){const i=M[t[e]];if(void 0===i)return NaN;r=62*r+i}return e?-r:r},F=t=>{if("number"!=typeof t||isNaN(t))return"undefined";if(!isFinite(t))return"undefined";const e=t<0;t=Math.abs(t);const[r,i]=t.toString().split("."),s=L(Number(r));return i?(e?"-":"")+s+"."+i:(e?"-":"")+s},q=t=>{if("string"!=typeof t)return NaN;let e=!1;"-"===t[0]&&(e=!0,t=t.slice(1));const[r,i]=t.split("."),s=U(r);if(isNaN(s))return NaN;const n=i?Number(s+"."+i):s;return e?-n:n};function B(t){"string"!=typeof t&&(t=String(t));let e=0;for(let r=0;r<t.length;r++){const i=t.codePointAt(r);i<=127?e+=1:i<=2047?e+=2:i<=65535?e+=3:i<=1114111&&(e+=4,i>65535&&r++)}return e}function z(t){let e=0;for(const r of Object.keys(t))e+=B(r);return e}function V(t){return null==t?"":"boolean"==typeof t?t?"1":"0":"number"==typeof t?String(t):"string"==typeof t?t:Array.isArray(t)?0===t.length?"[]":t.map(t=>String(t)).join("|"):"object"==typeof t?JSON.stringify(t):String(t)}function K(t){const e={};for(const[r,i]of Object.entries(t)){const t=B(V(i));e[r]=t}return e}function W(t){const e=K(t);return Object.values(e).reduce((t,e)=>t+e,0)+z(t)}function J(t){const e=K(t),r=z(t),i=Object.values(e).reduce((t,e)=>t+e,0),s=i+r,n=Object.entries(e).sort(([,t],[,e])=>e-t).map(([t,e])=>({attribute:t,size:e,percentage:(e/s*100).toFixed(2)+"%"}));return{total:s,valueSizes:e,namesSize:r,valueTotal:i,breakdown:n,detailedBreakdown:{values:i,names:r,total:s}}}function H(t={}){const{version:e="1",timestamps:r=!1,id:i=""}=t,s={_v:String(e)};r&&(s.createdAt="2024-01-01T00:00:00.000Z",s.updatedAt="2024-01-01T00:00:00.000Z"),i&&(s.id=i);const n={};for(const[t,e]of Object.entries(s))n[t]=e;return W(n)}function Y(t={}){const{s3Limit:e=2048,systemConfig:r={}}=t;return e-H(r)}class G extends Error{constructor({verbose:t,bucket:e,key:r,message:i,code:s,statusCode:n,requestId:a,awsMessage:o,original:c,commandName:l,commandInput:u,metadata:h,suggestion:f,...d}){t&&(i+=`\n\nVerbose:\n\n${JSON.stringify(d,null,2)}`),super(i),"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error(i).stack,super.name=this.constructor.name,this.name=this.constructor.name,this.bucket=e,this.key=r,this.thrownAt=new Date,this.code=s,this.statusCode=n,this.requestId=a,this.awsMessage=o,this.original=c,this.commandName=l,this.commandInput=u,this.metadata=h,this.suggestion=f,this.data={bucket:e,key:r,...d,verbose:t,message:i}}toJson(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,awsMessage:this.awsMessage,bucket:this.bucket,key:this.key,thrownAt:this.thrownAt,commandName:this.commandName,commandInput:this.commandInput,metadata:this.metadata,suggestion:this.suggestion,data:this.data,original:this.original,stack:this.stack}}toString(){return`${this.name} | ${this.message}`}}class Q extends G{constructor(t,e={}){let r,i,s,n,a,o;e.original&&(a=e.original,r=a.code||a.Code||a.name,i=a.statusCode||a.$metadata&&a.$metadata.httpStatusCode,s=a.requestId||a.$metadata&&a.$metadata.requestId,n=a.message,o=a.$metadata?{...a.$metadata}:void 0),super({message:t,...e,code:r,statusCode:i,requestId:s,awsMessage:n,original:a,metadata:o})}}class X extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class Z extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class tt extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class et extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class rt extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class it extends Q{constructor({bucket:t,resourceName:e,id:r,original:i,...s}){if("string"!=typeof r)throw new Error("id must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");if("string"!=typeof e)throw new Error("resourceName must be a string");super(`Resource not found: ${e}/${r} [bucket:${t}]`,{bucket:t,resourceName:e,id:r,original:i,...s})}}class st extends Q{constructor({bucket:t,original:e,...r}){if("string"!=typeof t)throw new Error("bucket must be a string");super(`Bucket does not exists [bucket:${t}]`,{bucket:t,original:e,...r})}}class nt extends Q{constructor({bucket:t,key:e,resourceName:r,id:i,original:s,...n}){if("string"!=typeof e)throw new Error("key must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");if(void 0!==i&&"string"!=typeof i)throw new Error("id must be a string");super(`No such key: ${e} [bucket:${t}]`,{bucket:t,key:e,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class at extends Q{constructor({bucket:t,key:e,resourceName:r,id:i,original:s,...n}){if("string"!=typeof e)throw new Error("key must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");super(`Not found: ${e} [bucket:${t}]`,{bucket:t,key:e,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class ot extends Q{constructor({bucket:t,original:e,...r}){if("string"!=typeof t)throw new Error("bucket must be a string");super(`Missing metadata for bucket [bucket:${t}]`,{bucket:t,original:e,...r})}}class ct extends Q{constructor({bucket:t,resourceName:e,attributes:r,validation:i,message:s,original:n,...a}){if("string"!=typeof t)throw new Error("bucket must be a string");if("string"!=typeof e)throw new Error("resourceName must be a string");super(s||`Validation error: This item is not valid. Resource=${e} [bucket:${t}].\n${JSON.stringify(i,null,2)}`,{bucket:t,resourceName:e,attributes:r,validation:i,original:n,...a})}}class lt extends Q{}const ut={NotFound:at,NoSuchKey:nt,UnknownError:lt,NoSuchBucket:st,MissingMetadata:ot,InvalidResourceItem:ct};function ht(t,e={}){const r=t.code||t.Code||t.name,i=t.$metadata?{...t.$metadata}:void 0,s=e.commandName,n=e.commandInput;let a;return"NoSuchKey"===r||"NotFound"===r?(a="Check if the key exists in the specified bucket and if your credentials have permission.",new nt({...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"NoSuchBucket"===r?(a="Check if the bucket exists and if your credentials have permission.",new st({...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"AccessDenied"===r||403===t.statusCode||"Forbidden"===r?(a="Check your credentials and bucket policy.",new et("Access denied",{...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"ValidationError"===r||400===t.statusCode?(a="Check the request parameters and payload.",new Z("Validation error",{...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"MissingMetadata"===r?(a="Check if the object metadata is present and valid.",new ot({...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):(a="Check the error details and AWS documentation.",new lt("Unknown error",{...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a}))}class ft extends Q{constructor(t,e={}){super(t,{...e,suggestion:"Check the connection string format and credentials."})}}class dt extends Q{constructor(t,e={}){super(t,{...e,suggestion:"Check if the crypto library is available and input is valid."})}}class pt extends Q{constructor(t,e={}){super(t,{...e,suggestion:"Check schema definition and input data."})}}class gt extends Q{constructor(t,e={}){super(t,{...e,suggestion:e.suggestion||"Check resource configuration, attributes, and operation context."}),Object.assign(this,e)}}class mt extends Q{constructor(t,e={}){super(t,{...e,suggestion:e.suggestion||"Check partition definition, fields, and input values."})}}function yt(t){if(null==t){const t=new Error("fnOrPromise cannot be null or undefined");return t.stack=(new Error).stack,[!1,t,void 0]}if("function"==typeof t)try{const e=t();return null==e?[!0,null,e]:"function"==typeof e.then?e.then(t=>[!0,null,t]).catch(t=>{if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}):[!0,null,e]}catch(t){if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}return"function"==typeof t.then?Promise.resolve(t).then(t=>[!0,null,t]).catch(t=>{if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}):[!0,null,t]}function bt(t){try{return[!0,null,t()]}catch(t){return[!1,t,null]}}var wt=yt;async function vt(){let t;if("undefined"!=typeof process){const[e,r,i]=await wt(async()=>{const{webcrypto:t}=await import("crypto");return t});if(!e)throw new dt("Crypto API not available",{original:r,context:"dynamicCrypto"});t=i}else"undefined"!=typeof window&&(t=window.crypto);if(!t)throw new dt("Could not load any crypto library",{context:"dynamicCrypto"});return t}async function St(t){const[e,r,i]=await wt(vt);if(!e)throw new dt("Crypto API not available",{original:r});const s=(new TextEncoder).encode(t),[n,a,o]=await wt(()=>i.subtle.digest("SHA-256",s));if(!n)throw new dt("SHA-256 digest failed",{original:a,input:t});return Array.from(new Uint8Array(o)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function _t(t,e){const[r,i,s]=await wt(vt);if(!r)throw new dt("Crypto API not available",{original:i});const n=s.getRandomValues(new Uint8Array(16)),[a,o,c]=await wt(()=>Rt(e,n));if(!a)throw new dt("Key derivation failed",{original:o,passphrase:e,salt:n});const l=s.getRandomValues(new Uint8Array(12)),u=(new TextEncoder).encode(t),[h,f,d]=await wt(()=>s.subtle.encrypt({name:"AES-GCM",iv:l},c,u));if(!h)throw new dt("Encryption failed",{original:f,content:t});const p=new Uint8Array(n.length+l.length+d.byteLength);return p.set(n),p.set(l,n.length),p.set(new Uint8Array(d),n.length+l.length),function(t){if("undefined"!=typeof process)return Buffer.from(t).toString("base64");{const[e,r,i]=bt(()=>String.fromCharCode.apply(null,new Uint8Array(t)));if(!e)throw new dt("Failed to convert ArrayBuffer to base64 (browser)",{original:r});return window.btoa(i)}}(p)}async function kt(t,e){const[r,i,s]=await wt(vt);if(!r)throw new dt("Crypto API not available",{original:i});const n=function(t){if("undefined"!=typeof process)return new Uint8Array(Buffer.from(t,"base64"));{const[e,r,i]=bt(()=>window.atob(t));if(!e)throw new dt("Failed to decode base64 (browser)",{original:r});const s=i.length,n=new Uint8Array(s);for(let t=0;t<s;t++)n[t]=i.charCodeAt(t);return n}}(t),a=n.slice(0,16),o=n.slice(16,28),c=n.slice(28),[l,u,h]=await wt(()=>Rt(e,a));if(!l)throw new dt("Key derivation failed (decrypt)",{original:u,passphrase:e,salt:a});const[f,d,p]=await wt(()=>s.subtle.decrypt({name:"AES-GCM",iv:o},h,c));if(!f)throw new dt("Decryption failed",{original:d,encryptedBase64:t});return(new TextDecoder).decode(p)}async function Ot(t){if("undefined"==typeof process)throw new dt("MD5 hashing is only available in Node.js environment",{context:"md5"});const[e,r,i]=await wt(async()=>{const{createHash:e}=await import("crypto");return e("md5").update(t).digest("base64")});if(!e)throw new dt("MD5 hashing failed",{original:r,data:t});return i}async function Rt(t,e){const[r,i,s]=await wt(vt);if(!r)throw new dt("Crypto API not available",{original:i});const n=(new TextEncoder).encode(t),[a,o,c]=await wt(()=>s.subtle.importKey("raw",n,{name:"PBKDF2"},!1,["deriveKey"]));if(!a)throw new dt("importKey failed",{original:o,passphrase:t});const[l,u,h]=await wt(()=>s.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:1e5,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]));if(!l)throw new dt("deriveKey failed",{original:u,passphrase:t,salt:e});return h}const jt=t(e,22),xt=t("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",16);var Et;function Dt(){}function At(){At.init.call(this)}function Nt(t){return void 0===t._maxListeners?At.defaultMaxListeners:t._maxListeners}function It(t,e,r,i){var s,n,a,o;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=t._events)?(n.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),n=t._events),a=n[e]):(n=t._events=new Dt,t._eventsCount=0),a){if("function"==typeof a?a=n[e]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),!a.warned&&(s=Nt(t))&&s>0&&a.length>s){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,o=c,"function"==typeof console.warn?console.warn(o):console.log(o)}}else a=n[e]=r,++t._eventsCount;return t}function $t(t,e,r){var i=!1;function s(){t.removeListener(e,s),i||(i=!0,r.apply(t,arguments))}return s.listener=r,s}function Pt(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Ct(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}Dt.prototype=Object.create(null),At.EventEmitter=At,At.usingDomains=!1,At.prototype.domain=void 0,At.prototype._events=void 0,At.prototype._maxListeners=void 0,At.defaultMaxListeners=10,At.init=function(){this.domain=null,At.usingDomains&&(!Et.active||this instanceof Et.Domain||(this.domain=Et.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Dt,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},At.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},At.prototype.getMaxListeners=function(){return Nt(this)},At.prototype.emit=function(t){var e,r,i,s,n,a,o,c="error"===t;if(a=this._events)c=c&&null==a.error;else if(!c)return!1;if(o=this.domain,c){if(e=arguments[1],!o){if(e instanceof Error)throw e;var l=new Error('Uncaught, unspecified "error" event. ('+e+")");throw l.context=e,l}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=o,e.domainThrown=!1,o.emit("error",e),!1}if(!(r=a[t]))return!1;var u="function"==typeof r;switch(i=arguments.length){case 1:!function(t,e,r){if(e)t.call(r);else for(var i=t.length,s=Ct(t,i),n=0;n<i;++n)s[n].call(r)}(r,u,this);break;case 2:!function(t,e,r,i){if(e)t.call(r,i);else for(var s=t.length,n=Ct(t,s),a=0;a<s;++a)n[a].call(r,i)}(r,u,this,arguments[1]);break;case 3:!function(t,e,r,i,s){if(e)t.call(r,i,s);else for(var n=t.length,a=Ct(t,n),o=0;o<n;++o)a[o].call(r,i,s)}(r,u,this,arguments[1],arguments[2]);break;case 4:!function(t,e,r,i,s,n){if(e)t.call(r,i,s,n);else for(var a=t.length,o=Ct(t,a),c=0;c<a;++c)o[c].call(r,i,s,n)}(r,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),n=1;n<i;n++)s[n-1]=arguments[n];!function(t,e,r,i){if(e)t.apply(r,i);else for(var s=t.length,n=Ct(t,s),a=0;a<s;++a)n[a].apply(r,i)}(r,u,this,s)}return!0},At.prototype.addListener=function(t,e){return It(this,t,e,!1)},At.prototype.on=At.prototype.addListener,At.prototype.prependListener=function(t,e){return It(this,t,e,!0)},At.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,$t(this,t,e)),this},At.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,$t(this,t,e)),this},At.prototype.removeListener=function(t,e){var r,i,s,n,a;if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[t]))return this;if(r===e||r.listener&&r.listener===e)0===--this._eventsCount?this._events=new Dt:(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===e||r[n].listener&&r[n].listener===e){a=r[n].listener,s=n;break}if(s<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new Dt,this;delete i[t]}else!function(t,e){for(var r=e,i=r+1,s=t.length;i<s;r+=1,i+=1)t[r]=t[i];t.pop()}(r,s);i.removeListener&&this.emit("removeListener",t,a||e)}return this},At.prototype.off=function(t,e){return this.removeListener(t,e)},At.prototype.removeAllListeners=function(t){var e,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Dt,this._eventsCount=0):r[t]&&(0===--this._eventsCount?this._events=new Dt:delete r[t]),this;if(0===arguments.length){for(var i,s=Object.keys(r),n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new Dt,this._eventsCount=0,this}if("function"==typeof(e=r[t]))this.removeListener(t,e);else if(e)do{this.removeListener(t,e[e.length-1])}while(e[0]);return this},At.prototype.listeners=function(t){var e,r=this._events;return r&&(e=r[t])?"function"==typeof e?[e.listener||e]:function(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}(e):[]},At.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):Pt.call(t,e)},At.prototype.listenerCount=Pt,At.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var Tt=class extends At{constructor(t={}){super(),this.name=this.constructor.name,this.options=t,this.hooks=new Map}async setup(t){this.database=t,this.beforeSetup(),await this.onSetup(),this.afterSetup()}async start(){this.beforeStart(),await this.onStart(),this.afterStart()}async stop(){this.beforeStop(),await this.onStop(),this.afterStop()}async onSetup(){}async onStart(){}async onStop(){}addHook(t,e,r){this.hooks.has(t)||this.hooks.set(t,new Map);const i=this.hooks.get(t);i.has(e)||i.set(e,[]),i.get(e).push(r)}removeHook(t,e,r){const i=this.hooks.get(t);if(i&&i.has(e)){const t=i.get(e),s=t.indexOf(r);s>-1&&t.splice(s,1)}}wrapResourceMethod(t,e,r){const i=t[e];if(t._pluginWrappers||(t._pluginWrappers=new Map),t._pluginWrappers.has(e)||t._pluginWrappers.set(e,[]),t._pluginWrappers.get(e).push(r),!t[`_wrapped_${e}`]){t[`_wrapped_${e}`]=i;const r=i&&i._isMockFunction;t[e]=async function(...r){let i=await t[`_wrapped_${e}`](...r);for(const s of t._pluginWrappers.get(e))i=await s.call(this,i,r,e);return i},r&&(Object.setPrototypeOf(t[e],Object.getPrototypeOf(i)),Object.assign(t[e],i))}}addMiddleware(t,e,r){if(t._pluginMiddlewares||(t._pluginMiddlewares={}),!t._pluginMiddlewares[e]){t._pluginMiddlewares[e]=[];const r=t[e].bind(t);t[e]=async function(...i){let s=-1;const n=async(...i)=>(s++,s<t._pluginMiddlewares[e].length?await t._pluginMiddlewares[e][s].call(this,n,...i):await r(...i));return await n(...i)}}t._pluginMiddlewares[e].push(r)}getPartitionValues(t,e){if(!e.config?.partitions)return{};const r={};for(const[i,s]of Object.entries(e.config.partitions))if(s.fields){r[i]={};for(const[n,a]of Object.entries(s.fields)){const s=this.getNestedFieldValue(t,n);null!=s&&(r[i][n]=e.applyPartitionRule(s,a))}}else r[i]={};return r}getNestedFieldValue(t,e){if(!e.includes("."))return t[e]??null;const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return null;i=i[t]}return i??null}beforeSetup(){this.emit("plugin.beforeSetup",new Date)}afterSetup(){this.emit("plugin.afterSetup",new Date)}beforeStart(){this.emit("plugin.beforeStart",new Date)}afterStart(){this.emit("plugin.afterStart",new Date)}beforeStop(){this.emit("plugin.beforeStop",new Date)}afterStop(){this.emit("plugin.afterStop",new Date)}};const Mt={setup(t){},start(){},stop(){}};class Lt extends Tt{constructor(t={}){super(t),this.auditResource=null,this.config={includeData:!1!==t.includeData,includePartitions:!1!==t.includePartitions,maxDataSize:t.maxDataSize||1e4,...t}}async onSetup(){const[t,e,r]=await wt(()=>this.database.createResource({name:"audits",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",recordId:"string|required",userId:"string|optional",timestamp:"string|required",oldData:"string|optional",newData:"string|optional",partition:"string|optional",partitionValues:"string|optional",metadata:"string|optional"},behavior:"body-overflow"}));this.auditResource=t?r:this.database.resources.audits||null,(t||this.auditResource)&&(this.installDatabaseProxy(),this.installEventListeners())}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._auditProxyInstalled)return;const t=this.installEventListenersForResource.bind(this);this.database._originalCreateResource=this.database.createResource,this.database.createResource=async function(...e){const r=await this._originalCreateResource(...e);return"audits"!==r.name&&t(r),r},this.database._auditProxyInstalled=!0}installEventListeners(){for(const t of Object.values(this.database.resources))"audits"!==t.name&&this.installEventListenersForResource(t)}installEventListenersForResource(t){t.on("insert",async e=>{const r=e.id||"auto-generated",i=this.config.includePartitions?this.getPartitionValues(e,t):null,s={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"insert",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(e)),partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(s).catch(()=>{})}),t.on("update",async e=>{const r=e.id;let i=e.$before;if(this.config.includeData&&!i){const[e,s,n]=await wt(()=>t.get(r));e&&(i=n)}const s=this.config.includePartitions?this.getPartitionValues(e,t):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"update",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(e)),partition:this.config.includePartitions?this.getPrimaryPartition(s):null,partitionValues:this.config.includePartitions&&s&&Object.keys(s).length>0?JSON.stringify(s):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(n).catch(()=>{})}),t.on("delete",async e=>{const r=e.id;let i=e;if(this.config.includeData&&!i){const[e,s,n]=await wt(()=>t.get(r));e&&(i=n)}const s=i&&this.config.includePartitions?this.getPartitionValues(i,t):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"delete",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(s):null,partitionValues:this.config.includePartitions&&s&&Object.keys(s).length>0?JSON.stringify(s):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(n).catch(()=>{})}),t.useMiddleware("deleteMany",async(e,r)=>{const i=e.args[0],s={};if(this.config.includeData)for(const e of i){const[r,i,n]=await wt(()=>t.get(e));s[e]=r?n:null}const n=await r();if(n&&n.length>0&&this.config.includeData)for(const e of i){const r=s[e],i=r&&this.config.includePartitions?this.getPartitionValues(r,t):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"delete",recordId:e,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(r)),newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0",batchOperation:!0})};this.logAudit(n).catch(()=>{})}return n})}getPartitionValues(t,e){if(!t)return null;const r=e.config?.partitions||{},i={};for(const[e,s]of Object.entries(r))if(s.fields){const r={};for(const[e,i]of Object.entries(s.fields)){const i=this.getNestedFieldValue(t,e);null!=i&&(r[e]=i)}Object.keys(r).length>0&&(i[e]=r)}return i}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return;i=i[t]}return i}getPrimaryPartition(t){if(!t)return null;const e=Object.keys(t);return e.length>0?e[0]:null}async logAudit(t){t.id||(t.id=`audit-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return await this.auditResource.insert(t)}truncateData(t){if(!t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||"$overflow"===r||(e[r]=i);const r=JSON.stringify(e);if(r.length<=this.config.maxDataSize)return e;let i={...e},s=JSON.stringify(i).length;const n=JSON.stringify({_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}).length,a=this.config.maxDataSize-n;for(const[t,e]of Object.entries(i))if("string"==typeof e&&s>a){const r=s-a,n=Math.max(0,e.length-r-3);n<e.length&&(i[t]=e.substring(0,n)+"...",s=JSON.stringify(i).length)}return{...i,_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}}async getAuditLogs(t={}){if(!this.auditResource)return[];const[e,r,i]=await wt(async()=>{const{resourceName:e,operation:r,recordId:i,userId:s,partition:n,startDate:a,endDate:o,limit:c=100,offset:l=0}=t;let u=(await this.auditResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&((!i||t.recordId===i)&&((!s||t.userId===s)&&((!n||t.partition===n)&&(!(a&&new Date(t.timestamp)<new Date(a))&&!(o&&new Date(t.timestamp)>new Date(o))))))));u.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp));return u.slice(l,l+c).map(t=>{const[e,,r]="string"==typeof t.oldData?bt(()=>JSON.parse(t.oldData)):[!0,null,t.oldData],[i,,s]="string"==typeof t.newData?bt(()=>JSON.parse(t.newData)):[!0,null,t.newData],[n,,a]=t.partitionValues&&"string"==typeof t.partitionValues?bt(()=>JSON.parse(t.partitionValues)):[!0,null,t.partitionValues],[o,,c]=t.metadata&&"string"==typeof t.metadata?bt(()=>JSON.parse(t.metadata)):[!0,null,t.metadata];return{...t,oldData:null===t.oldData||void 0===t.oldData||"null"===t.oldData?null:e?r:null,newData:null===t.newData||void 0===t.newData||"null"===t.newData?null:i?s:null,partitionValues:n?a:t.partitionValues,metadata:o?c:t.metadata}})});return e?i:[]}async getRecordHistory(t,e){return this.getAuditLogs({resourceName:t,recordId:e,limit:1e3})}async getPartitionHistory(t,e,r){return this.getAuditLogs({resourceName:t,partition:e,limit:1e3})}async getAuditStats(t={}){const{resourceName:e,startDate:r,endDate:i}=t,s=await this.getAuditLogs({resourceName:e,startDate:r,endDate:i,limit:1e4}),n={total:s.length,byOperation:{},byResource:{},byPartition:{},byUser:{},timeline:{}};for(const t of s)if(n.byOperation[t.operation]=(n.byOperation[t.operation]||0)+1,n.byResource[t.resourceName]=(n.byResource[t.resourceName]||0)+1,t.partition&&(n.byPartition[t.partition]=(n.byPartition[t.partition]||0)+1),n.byUser[t.userId]=(n.byUser[t.userId]||0)+1,t.timestamp){const e=t.timestamp.split("T")[0];n.timeline[e]=(n.timeline[e]||0)+1}return n}}function Ut(t,e){for(var r=0,i=t.length-1;i>=0;i--){var s=t[i];"."===s?t.splice(i,1):".."===s?(t.splice(i,1),r++):r&&(t.splice(i,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}var Ft=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,qt=function(t){return Ft.exec(t).slice(1)};function Bt(){for(var t="",e=!1,r=arguments.length-1;r>=-1&&!e;r--){var i=r>=0?arguments[r]:"/";if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");i&&(t=i+"/"+t,e="/"===i.charAt(0))}return(e?"/":"")+(t=Ut(Jt(t.split("/"),function(t){return!!t}),!e).join("/"))||"."}function zt(t){var e=Vt(t),r="/"===Ht(t,-1);return(t=Ut(Jt(t.split("/"),function(t){return!!t}),!e).join("/"))||e||(t="."),t&&r&&(t+="/"),(e?"/":"")+t}function Vt(t){return"/"===t.charAt(0)}function Kt(){return zt(Jt(Array.prototype.slice.call(arguments,0),function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))}var Wt={extname:function(t){return qt(t)[3]},basename:function(t,e){var r=qt(t)[2];return e&&r.substr(-1*e.length)===e&&(r=r.substr(0,r.length-e.length)),r},dirname:function(t){var e=qt(t),r=e[0],i=e[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},sep:"/",delimiter:":",relative:function(t,e){function r(t){for(var e=0;e<t.length&&""===t[e];e++);for(var r=t.length-1;r>=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=Bt(t).substr(1),e=Bt(e).substr(1);for(var i=r(t.split("/")),s=r(e.split("/")),n=Math.min(i.length,s.length),a=n,o=0;o<n;o++)if(i[o]!==s[o]){a=o;break}var c=[];for(o=a;o<i.length;o++)c.push("..");return(c=c.concat(s.slice(a))).join("/")},join:Kt,isAbsolute:Vt,normalize:zt,resolve:Bt};function Jt(t,e){if(t.filter)return t.filter(e);for(var r=[],i=0;i<t.length;i++)e(t[i],i,t)&&r.push(t[i]);return r}var Ht="b"==="ab".substr(-1)?function(t,e,r){return t.substr(e,r)}:function(t,e,r){return e<0&&(e=t.length+e),t.substr(e,r)};class Yt extends At{constructor(t={}){super(),this.config=t}async _set(t,e){}async _get(t){}async _del(t){}async _clear(t){}validateKey(t){if(null==t||"string"!=typeof t||!t)throw new Error("Invalid key")}async set(t,e){return this.validateKey(t),await this._set(t,e),this.emit("set",e),e}async get(t){this.validateKey(t);const e=await this._get(t);return this.emit("get",e),e}async del(t){this.validateKey(t);const e=await this._del(t);return this.emit("delete",e),e}async delete(t){return this.del(t)}async clear(t){const e=await this._clear(t);return this.emit("clear",e),e}}function Gt(){throw new Error("setTimeout has not been defined")}function Qt(){throw new Error("clearTimeout has not been defined")}var Xt=Gt,Zt=Qt;function te(t){if(Xt===setTimeout)return setTimeout(t,0);if((Xt===Gt||!Xt)&&setTimeout)return Xt=setTimeout,setTimeout(t,0);try{return Xt(t,0)}catch(e){try{return Xt.call(null,t,0)}catch(e){return Xt.call(this,t,0)}}}"function"==typeof global.setTimeout&&(Xt=setTimeout),"function"==typeof global.clearTimeout&&(Zt=clearTimeout);var ee,re=[],ie=!1,se=-1;function ne(){ie&&ee&&(ie=!1,ee.length?re=ee.concat(re):se=-1,re.length&&ae())}function ae(){if(!ie){var t=te(ne);ie=!0;for(var e=re.length;e;){for(ee=re,re=[];++se<e;)ee&&ee[se].run();se=-1,e=re.length}ee=null,ie=!1,function(t){if(Zt===clearTimeout)return clearTimeout(t);if((Zt===Qt||!Zt)&&clearTimeout)return Zt=clearTimeout,clearTimeout(t);try{return Zt(t)}catch(e){try{return Zt.call(null,t)}catch(e){return Zt.call(this,t)}}}(t)}}function oe(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];re.push(new ce(t,e)),1!==re.length||ie||te(ae)}function ce(t,e){this.fun=t,this.array=e}ce.prototype.run=function(){this.fun.apply(null,this.array)};var le,ue={env:{}};le="function"==typeof Object.create?function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t};var he=/%[sdj%]/g;function fe(t){if(!Oe(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(me(arguments[r]));return e.join(" ")}r=1;for(var i=arguments,s=i.length,n=String(t).replace(he,function(t){if("%%"===t)return"%";if(r>=s)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}}),a=i[r];r<s;a=i[++r])ke(a)||!xe(a)?n+=" "+a:n+=" "+me(a);return n}function de(t,e){if(Re(global.process))return function(){return de(t,e).apply(this,arguments)};if(!0===ue.noDeprecation)return t;var r=!1;return function(){if(!r){if(ue.throwDeprecation)throw new Error(e);ue.traceDeprecation?console.trace(e):console.error(e),r=!0}return t.apply(this,arguments)}}var pe,ge={};function me(t,e){var r={seen:[],stylize:be};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),_e(e)?r.showHidden=e:e&&function(t,e){if(!e||!xe(e))return t;var r=Object.keys(e),i=r.length;for(;i--;)t[r[i]]=e[r[i]]}(r,e),Re(r.showHidden)&&(r.showHidden=!1),Re(r.depth)&&(r.depth=2),Re(r.colors)&&(r.colors=!1),Re(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=ye),we(r,t,r.depth)}function ye(t,e){var r=me.styles[e];return r?"["+me.colors[r][0]+"m"+t+"["+me.colors[r][1]+"m":t}function be(t,e){return t}function we(t,e,r){if(t.customInspect&&e&&Ae(e.inspect)&&e.inspect!==me&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(r,t);return Oe(i)||(i=we(t,i,r)),i}var s=function(t,e){if(Re(e))return t.stylize("undefined","undefined");if(Oe(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(i=e,"number"==typeof i)return t.stylize(""+e,"number");var i;if(_e(e))return t.stylize(""+e,"boolean");if(ke(e))return t.stylize("null","null")}(t,e);if(s)return s;var n=Object.keys(e),a=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(n);if(t.showHidden&&(n=Object.getOwnPropertyNames(e)),De(e)&&(n.indexOf("message")>=0||n.indexOf("description")>=0))return ve(e);if(0===n.length){if(Ae(e)){var o=e.name?": "+e.name:"";return t.stylize("[Function"+o+"]","special")}if(je(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Ee(e))return t.stylize(Date.prototype.toString.call(e),"date");if(De(e))return ve(e)}var c,l,u="",h=!1,f=["{","}"];(c=e,Array.isArray(c)&&(h=!0,f=["[","]"]),Ae(e))&&(u=" [Function"+(e.name?": "+e.name:"")+"]");return je(e)&&(u=" "+RegExp.prototype.toString.call(e)),Ee(e)&&(u=" "+Date.prototype.toUTCString.call(e)),De(e)&&(u=" "+ve(e)),0!==n.length||h&&0!=e.length?r<0?je(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),l=h?function(t,e,r,i,s){for(var n=[],a=0,o=e.length;a<o;++a)Ie(e,String(a))?n.push(Se(t,e,r,i,String(a),!0)):n.push("");return s.forEach(function(s){s.match(/^\d+$/)||n.push(Se(t,e,r,i,s,!0))}),n}(t,e,r,a,n):n.map(function(i){return Se(t,e,r,a,i,h)}),t.seen.pop(),function(t,e,r){var i=t.reduce(function(t,e){return e.indexOf("\n"),t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(i>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(l,u,f)):f[0]+u+f[1]}function ve(t){return"["+Error.prototype.toString.call(t)+"]"}function Se(t,e,r,i,s,n){var a,o,c;if((c=Object.getOwnPropertyDescriptor(e,s)||{value:e[s]}).get?o=c.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):c.set&&(o=t.stylize("[Setter]","special")),Ie(i,s)||(a="["+s+"]"),o||(t.seen.indexOf(c.value)<0?(o=ke(r)?we(t,c.value,null):we(t,c.value,r-1)).indexOf("\n")>-1&&(o=n?o.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+o.split("\n").map(function(t){return" "+t}).join("\n")):o=t.stylize("[Circular]","special")),Re(a)){if(n&&s.match(/^\d+$/))return o;(a=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+o}function _e(t){return"boolean"==typeof t}function ke(t){return null===t}function Oe(t){return"string"==typeof t}function Re(t){return void 0===t}function je(t){return xe(t)&&"[object RegExp]"===Ne(t)}function xe(t){return"object"==typeof t&&null!==t}function Ee(t){return xe(t)&&"[object Date]"===Ne(t)}function De(t){return xe(t)&&("[object Error]"===Ne(t)||t instanceof Error)}function Ae(t){return"function"==typeof t}function Ne(t){return Object.prototype.toString.call(t)}function Ie(t,e){return Object.prototype.hasOwnProperty.call(t,e)}me.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},me.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var $e=[],Pe=[],Ce="undefined"!=typeof Uint8Array?Uint8Array:Array,Te=!1;function Me(){Te=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0;e<64;++e)$e[e]=t[e],Pe[t.charCodeAt(e)]=e;Pe["-".charCodeAt(0)]=62,Pe["_".charCodeAt(0)]=63}function Le(t){return $e[t>>18&63]+$e[t>>12&63]+$e[t>>6&63]+$e[63&t]}function Ue(t,e,r){for(var i,s=[],n=e;n<r;n+=3)i=(t[n]<<16)+(t[n+1]<<8)+t[n+2],s.push(Le(i));return s.join("")}function Fe(t){var e;Te||Me();for(var r=t.length,i=r%3,s="",n=[],a=16383,o=0,c=r-i;o<c;o+=a)n.push(Ue(t,o,o+a>c?c:o+a));return 1===i?(e=t[r-1],s+=$e[e>>2],s+=$e[e<<4&63],s+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],s+=$e[e>>10],s+=$e[e>>4&63],s+=$e[e<<2&63],s+="="),n.push(s),n.join("")}function qe(t,e,r,i,s){var n,a,o=8*s-i-1,c=(1<<o)-1,l=c>>1,u=-7,h=r?s-1:0,f=r?-1:1,d=t[e+h];for(h+=f,n=d&(1<<-u)-1,d>>=-u,u+=o;u>0;n=256*n+t[e+h],h+=f,u-=8);for(a=n&(1<<-u)-1,n>>=-u,u+=i;u>0;a=256*a+t[e+h],h+=f,u-=8);if(0===n)n=1-l;else{if(n===c)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,i),n-=l}return(d?-1:1)*a*Math.pow(2,n-i)}function Be(t,e,r,i,s,n){var a,o,c,l=8*n-s-1,u=(1<<l)-1,h=u>>1,f=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,p=i?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=u):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),(e+=a+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(a++,c/=2),a+h>=u?(o=0,a=u):a+h>=1?(o=(e*c-1)*Math.pow(2,s),a+=h):(o=e*Math.pow(2,h-1)*Math.pow(2,s),a=0));s>=8;t[r+d]=255&o,d+=p,o/=256,s-=8);for(a=a<<s|o,l+=s;l>0;t[r+d]=255&a,d+=p,a/=256,l-=8);t[r+d-p]|=128*g}var ze={}.toString,Ve=Array.isArray||function(t){return"[object Array]"==ze.call(t)};function Ke(){return Je.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function We(t,e){if(Ke()<e)throw new RangeError("Invalid typed array length");return Je.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=Je.prototype:(null===t&&(t=new Je(e)),t.length=e),t}function Je(t,e,r){if(!(Je.TYPED_ARRAY_SUPPORT||this instanceof Je))return new Je(t,e,r);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return Ge(this,t)}return He(this,t,e,r)}function He(t,e,r,i){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,r,i){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(i||0))throw new RangeError("'length' is out of bounds");e=void 0===r&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,r):new Uint8Array(e,r,i);Je.TYPED_ARRAY_SUPPORT?(t=e).__proto__=Je.prototype:t=Qe(t,e);return t}(t,e,r,i):"string"==typeof e?function(t,e,r){"string"==typeof r&&""!==r||(r="utf8");if(!Je.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|tr(e,r);t=We(t,i);var s=t.write(e,r);s!==i&&(t=t.slice(0,s));return t}(t,e,r):function(t,e){if(Ze(e)){var r=0|Xe(e.length);return 0===(t=We(t,r)).length||e.copy(t,0,0,r),t}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(i=e.length)!=i?We(t,0):Qe(t,e);if("Buffer"===e.type&&Ve(e.data))return Qe(t,e.data)}var i;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function Ye(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function Ge(t,e){if(Ye(e),t=We(t,e<0?0:0|Xe(e)),!Je.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function Qe(t,e){var r=e.length<0?0:0|Xe(e.length);t=We(t,r);for(var i=0;i<r;i+=1)t[i]=255&e[i];return t}function Xe(t){if(t>=Ke())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ke().toString(16)+" bytes");return 0|t}function Ze(t){return!(null==t||!t._isBuffer)}function tr(t,e){if(Ze(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return xr(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Er(t).length;default:if(i)return xr(t).length;e=(""+e).toLowerCase(),i=!0}}function er(t,e,r){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return mr(this,e,r);case"utf8":case"utf-8":return fr(this,e,r);case"ascii":return pr(this,e,r);case"latin1":case"binary":return gr(this,e,r);case"base64":return hr(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return yr(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function rr(t,e,r){var i=t[e];t[e]=t[r],t[r]=i}function ir(t,e,r,i,s){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=s?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(s)return-1;r=t.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof e&&(e=Je.from(e,i)),Ze(e))return 0===e.length?-1:sr(t,e,r,i,s);if("number"==typeof e)return e&=255,Je.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):sr(t,[e],r,i,s);throw new TypeError("val must be string, number or Buffer")}function sr(t,e,r,i,s){var n,a=1,o=t.length,c=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;a=2,o/=2,c/=2,r/=2}function l(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}if(s){var u=-1;for(n=r;n<o;n++)if(l(t,n)===l(e,-1===u?0:n-u)){if(-1===u&&(u=n),n-u+1===c)return u*a}else-1!==u&&(n-=n-u),u=-1}else for(r+c>o&&(r=o-c),n=r;n>=0;n--){for(var h=!0,f=0;f<c;f++)if(l(t,n+f)!==l(e,f)){h=!1;break}if(h)return n}return-1}function nr(t,e,r,i){r=Number(r)||0;var s=t.length-r;i?(i=Number(i))>s&&(i=s):i=s;var n=e.length;if(n%2!=0)throw new TypeError("Invalid hex string");i>n/2&&(i=n/2);for(var a=0;a<i;++a){var o=parseInt(e.substr(2*a,2),16);if(isNaN(o))return a;t[r+a]=o}return a}function ar(t,e,r,i){return Dr(xr(e,t.length-r),t,r,i)}function or(t,e,r,i){return Dr(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,i)}function cr(t,e,r,i){return or(t,e,r,i)}function lr(t,e,r,i){return Dr(Er(e),t,r,i)}function ur(t,e,r,i){return Dr(function(t,e){for(var r,i,s,n=[],a=0;a<t.length&&!((e-=2)<0);++a)i=(r=t.charCodeAt(a))>>8,s=r%256,n.push(s),n.push(i);return n}(e,t.length-r),t,r,i)}function hr(t,e,r){return 0===e&&r===t.length?Fe(t):Fe(t.slice(e,r))}function fr(t,e,r){r=Math.min(t.length,r);for(var i=[],s=e;s<r;){var n,a,o,c,l=t[s],u=null,h=l>239?4:l>223?3:l>191?2:1;if(s+h<=r)switch(h){case 1:l<128&&(u=l);break;case 2:128==(192&(n=t[s+1]))&&(c=(31&l)<<6|63&n)>127&&(u=c);break;case 3:n=t[s+1],a=t[s+2],128==(192&n)&&128==(192&a)&&(c=(15&l)<<12|(63&n)<<6|63&a)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:n=t[s+1],a=t[s+2],o=t[s+3],128==(192&n)&&128==(192&a)&&128==(192&o)&&(c=(15&l)<<18|(63&n)<<12|(63&a)<<6|63&o)>65535&&c<1114112&&(u=c)}null===u?(u=65533,h=1):u>65535&&(u-=65536,i.push(u>>>10&1023|55296),u=56320|1023&u),i.push(u),s+=h}return function(t){var e=t.length;if(e<=dr)return String.fromCharCode.apply(String,t);var r="",i=0;for(;i<e;)r+=String.fromCharCode.apply(String,t.slice(i,i+=dr));return r}(i)}Je.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT,Ke(),Je.poolSize=8192,Je._augment=function(t){return t.__proto__=Je.prototype,t},Je.from=function(t,e,r){return He(null,t,e,r)},Je.TYPED_ARRAY_SUPPORT&&(Je.prototype.__proto__=Uint8Array.prototype,Je.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Je[Symbol.species]),Je.alloc=function(t,e,r){return function(t,e,r,i){return Ye(e),e<=0?We(t,e):void 0!==r?"string"==typeof i?We(t,e).fill(r,i):We(t,e).fill(r):We(t,e)}(null,t,e,r)},Je.allocUnsafe=function(t){return Ge(null,t)},Je.allocUnsafeSlow=function(t){return Ge(null,t)},Je.isBuffer=function(t){return null!=t&&(!!t._isBuffer||Ar(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&Ar(t.slice(0,0))}(t))},Je.compare=function(t,e){if(!Ze(t)||!Ze(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,i=e.length,s=0,n=Math.min(r,i);s<n;++s)if(t[s]!==e[s]){r=t[s],i=e[s];break}return r<i?-1:i<r?1:0},Je.isEncoding=function(t){switch(String(t).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}},Je.concat=function(t,e){if(!Ve(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return Je.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var i=Je.allocUnsafe(e),s=0;for(r=0;r<t.length;++r){var n=t[r];if(!Ze(n))throw new TypeError('"list" argument must be an Array of Buffers');n.copy(i,s),s+=n.length}return i},Je.byteLength=tr,Je.prototype._isBuffer=!0,Je.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)rr(this,e,e+1);return this},Je.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)rr(this,e,e+3),rr(this,e+1,e+2);return this},Je.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)rr(this,e,e+7),rr(this,e+1,e+6),rr(this,e+2,e+5),rr(this,e+3,e+4);return this},Je.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?fr(this,0,t):er.apply(this,arguments)},Je.prototype.equals=function(t){if(!Ze(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Je.compare(this,t)},Je.prototype.inspect=function(){var t="";return this.length>0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),"<Buffer "+t+">"},Je.prototype.compare=function(t,e,r,i,s){if(!Ze(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),e<0||r>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&e>=r)return 0;if(i>=s)return-1;if(e>=r)return 1;if(this===t)return 0;for(var n=(s>>>=0)-(i>>>=0),a=(r>>>=0)-(e>>>=0),o=Math.min(n,a),c=this.slice(i,s),l=t.slice(e,r),u=0;u<o;++u)if(c[u]!==l[u]){n=c[u],a=l[u];break}return n<a?-1:a<n?1:0},Je.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},Je.prototype.indexOf=function(t,e,r){return ir(this,t,e,r,!0)},Je.prototype.lastIndexOf=function(t,e,r){return ir(this,t,e,r,!1)},Je.prototype.write=function(t,e,r,i){if(void 0===e)i="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)i=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(r)?(r|=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var s=this.length-e;if((void 0===r||r>s)&&(r=s),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var n=!1;;)switch(i){case"hex":return nr(this,t,e,r);case"utf8":case"utf-8":return ar(this,t,e,r);case"ascii":return or(this,t,e,r);case"latin1":case"binary":return cr(this,t,e,r);case"base64":return lr(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ur(this,t,e,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},Je.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var dr=4096;function pr(t,e,r){var i="";r=Math.min(t.length,r);for(var s=e;s<r;++s)i+=String.fromCharCode(127&t[s]);return i}function gr(t,e,r){var i="";r=Math.min(t.length,r);for(var s=e;s<r;++s)i+=String.fromCharCode(t[s]);return i}function mr(t,e,r){var i=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>i)&&(r=i);for(var s="",n=e;n<r;++n)s+=jr(t[n]);return s}function yr(t,e,r){for(var i=t.slice(e,r),s="",n=0;n<i.length;n+=2)s+=String.fromCharCode(i[n]+256*i[n+1]);return s}function br(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function wr(t,e,r,i,s,n){if(!Ze(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>s||e<n)throw new RangeError('"value" argument is out of bounds');if(r+i>t.length)throw new RangeError("Index out of range")}function vr(t,e,r,i){e<0&&(e=65535+e+1);for(var s=0,n=Math.min(t.length-r,2);s<n;++s)t[r+s]=(e&255<<8*(i?s:1-s))>>>8*(i?s:1-s)}function Sr(t,e,r,i){e<0&&(e=4294967295+e+1);for(var s=0,n=Math.min(t.length-r,4);s<n;++s)t[r+s]=e>>>8*(i?s:3-s)&255}function _r(t,e,r,i,s,n){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function kr(t,e,r,i,s){return s||_r(t,0,r,4),Be(t,e,r,i,23,4),r+4}function Or(t,e,r,i,s){return s||_r(t,0,r,8),Be(t,e,r,i,52,8),r+8}Je.prototype.slice=function(t,e){var r,i=this.length;if((t=~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),(e=void 0===e?i:~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t),Je.TYPED_ARRAY_SUPPORT)(r=this.subarray(t,e)).__proto__=Je.prototype;else{var s=e-t;r=new Je(s,void 0);for(var n=0;n<s;++n)r[n]=this[n+t]}return r},Je.prototype.readUIntLE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=this[t],s=1,n=0;++n<e&&(s*=256);)i+=this[t+n]*s;return i},Je.prototype.readUIntBE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=this[t+--e],s=1;e>0&&(s*=256);)i+=this[t+--e]*s;return i},Je.prototype.readUInt8=function(t,e){return e||br(t,1,this.length),this[t]},Je.prototype.readUInt16LE=function(t,e){return e||br(t,2,this.length),this[t]|this[t+1]<<8},Je.prototype.readUInt16BE=function(t,e){return e||br(t,2,this.length),this[t]<<8|this[t+1]},Je.prototype.readUInt32LE=function(t,e){return e||br(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Je.prototype.readUInt32BE=function(t,e){return e||br(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Je.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=this[t],s=1,n=0;++n<e&&(s*=256);)i+=this[t+n]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*e)),i},Je.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=e,s=1,n=this[t+--i];i>0&&(s*=256);)n+=this[t+--i]*s;return n>=(s*=128)&&(n-=Math.pow(2,8*e)),n},Je.prototype.readInt8=function(t,e){return e||br(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Je.prototype.readInt16LE=function(t,e){e||br(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Je.prototype.readInt16BE=function(t,e){e||br(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Je.prototype.readInt32LE=function(t,e){return e||br(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Je.prototype.readInt32BE=function(t,e){return e||br(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Je.prototype.readFloatLE=function(t,e){return e||br(t,4,this.length),qe(this,t,!0,23,4)},Je.prototype.readFloatBE=function(t,e){return e||br(t,4,this.length),qe(this,t,!1,23,4)},Je.prototype.readDoubleLE=function(t,e){return e||br(t,8,this.length),qe(this,t,!0,52,8)},Je.prototype.readDoubleBE=function(t,e){return e||br(t,8,this.length),qe(this,t,!1,52,8)},Je.prototype.writeUIntLE=function(t,e,r,i){(t=+t,e|=0,r|=0,i)||wr(this,t,e,r,Math.pow(2,8*r)-1,0);var s=1,n=0;for(this[e]=255&t;++n<r&&(s*=256);)this[e+n]=t/s&255;return e+r},Je.prototype.writeUIntBE=function(t,e,r,i){(t=+t,e|=0,r|=0,i)||wr(this,t,e,r,Math.pow(2,8*r)-1,0);var s=r-1,n=1;for(this[e+s]=255&t;--s>=0&&(n*=256);)this[e+s]=t/n&255;return e+r},Je.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,1,255,0),Je.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Je.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,65535,0),Je.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):vr(this,t,e,!0),e+2},Je.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,65535,0),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):vr(this,t,e,!1),e+2},Je.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,4294967295,0),Je.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Sr(this,t,e,!0),e+4},Je.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,4294967295,0),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Sr(this,t,e,!1),e+4},Je.prototype.writeIntLE=function(t,e,r,i){if(t=+t,e|=0,!i){var s=Math.pow(2,8*r-1);wr(this,t,e,r,s-1,-s)}var n=0,a=1,o=0;for(this[e]=255&t;++n<r&&(a*=256);)t<0&&0===o&&0!==this[e+n-1]&&(o=1),this[e+n]=(t/a|0)-o&255;return e+r},Je.prototype.writeIntBE=function(t,e,r,i){if(t=+t,e|=0,!i){var s=Math.pow(2,8*r-1);wr(this,t,e,r,s-1,-s)}var n=r-1,a=1,o=0;for(this[e+n]=255&t;--n>=0&&(a*=256);)t<0&&0===o&&0!==this[e+n+1]&&(o=1),this[e+n]=(t/a|0)-o&255;return e+r},Je.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,1,127,-128),Je.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Je.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,32767,-32768),Je.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):vr(this,t,e,!0),e+2},Je.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,32767,-32768),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):vr(this,t,e,!1),e+2},Je.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,2147483647,-2147483648),Je.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Sr(this,t,e,!0),e+4},Je.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Sr(this,t,e,!1),e+4},Je.prototype.writeFloatLE=function(t,e,r){return kr(this,t,e,!0,r)},Je.prototype.writeFloatBE=function(t,e,r){return kr(this,t,e,!1,r)},Je.prototype.writeDoubleLE=function(t,e,r){return Or(this,t,e,!0,r)},Je.prototype.writeDoubleBE=function(t,e,r){return Or(this,t,e,!1,r)},Je.prototype.copy=function(t,e,r,i){if(r||(r=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e<i-r&&(i=t.length-e+r);var s,n=i-r;if(this===t&&r<e&&e<i)for(s=n-1;s>=0;--s)t[s+e]=this[s+r];else if(n<1e3||!Je.TYPED_ARRAY_SUPPORT)for(s=0;s<n;++s)t[s+e]=this[s+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+n),e);return n},Je.prototype.fill=function(t,e,r,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),1===t.length){var s=t.charCodeAt(0);s<256&&(t=s)}if(void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!Je.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;var n;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(n=e;n<r;++n)this[n]=t;else{var a=Ze(t)?t:xr(new Je(t,i).toString()),o=a.length;for(n=0;n<r-e;++n)this[n+e]=a[n%o]}return this};var Rr=/[^+\/0-9A-Za-z-_]/g;function jr(t){return t<16?"0"+t.toString(16):t.toString(16)}function xr(t,e){var r;e=e||1/0;for(var i=t.length,s=null,n=[],a=0;a<i;++a){if((r=t.charCodeAt(a))>55295&&r<57344){if(!s){if(r>56319){(e-=3)>-1&&n.push(239,191,189);continue}if(a+1===i){(e-=3)>-1&&n.push(239,191,189);continue}s=r;continue}if(r<56320){(e-=3)>-1&&n.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(e-=3)>-1&&n.push(239,191,189);if(s=null,r<128){if((e-=1)<0)break;n.push(r)}else if(r<2048){if((e-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function Er(t){return function(t){var e,r,i,s,n,a;Te||Me();var o=t.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");n="="===t[o-2]?2:"="===t[o-1]?1:0,a=new Ce(3*o/4-n),i=n>0?o-4:o;var c=0;for(e=0,r=0;e<i;e+=4,r+=3)s=Pe[t.charCodeAt(e)]<<18|Pe[t.charCodeAt(e+1)]<<12|Pe[t.charCodeAt(e+2)]<<6|Pe[t.charCodeAt(e+3)],a[c++]=s>>16&255,a[c++]=s>>8&255,a[c++]=255&s;return 2===n?(s=Pe[t.charCodeAt(e)]<<2|Pe[t.charCodeAt(e+1)]>>4,a[c++]=255&s):1===n&&(s=Pe[t.charCodeAt(e)]<<10|Pe[t.charCodeAt(e+1)]<<4|Pe[t.charCodeAt(e+2)]>>2,a[c++]=s>>8&255,a[c++]=255&s),a}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(Rr,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Dr(t,e,r,i){for(var s=0;s<i&&!(s+r>=e.length||s>=t.length);++s)e[s+r]=t[s];return s}function Ar(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function Nr(){this.head=null,this.tail=null,this.length=0}Nr.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Nr.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Nr.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Nr.prototype.clear=function(){this.head=this.tail=null,this.length=0},Nr.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Nr.prototype.concat=function(t){if(0===this.length)return Je.alloc(0);if(1===this.length)return this.head.data;for(var e=Je.allocUnsafe(t>>>0),r=this.head,i=0;r;)r.data.copy(e,i),i+=r.data.length,r=r.next;return e};var Ir=Je.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function $r(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Ir(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Cr;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Tr;break;default:return void(this.write=Pr)}this.charBuffer=new Je(6),this.charReceived=0,this.charLength=0}function Pr(t){return t.toString(this.encoding)}function Cr(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function Tr(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}$r.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";if(t=t.slice(r,t.length),!((s=(e=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(e.length-1))>=55296&&s<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var i=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,i),i-=this.charReceived);var s;i=(e+=t.toString(this.encoding,0,i)).length-1;if((s=e.charCodeAt(i))>=55296&&s<=56319){var n=this.surrogateSize;return this.charLength+=n,this.charReceived+=n,this.charBuffer.copy(this.charBuffer,n,0,n),t.copy(this.charBuffer,0,0,n),e.substring(0,i)}return e},$r.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},$r.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,i=this.charBuffer,s=this.encoding;e+=i.slice(0,r).toString(s)}return e},Ur.ReadableState=Lr;var Mr=function(t){if(Re(pe)&&(pe=ue.env.NODE_DEBUG||""),t=t.toUpperCase(),!ge[t])if(new RegExp("\\b"+t+"\\b","i").test(pe)){ge[t]=function(){var e=fe.apply(null,arguments);console.error("%s %d: %s",t,0,e)}}else ge[t]=function(){};return ge[t]}("stream");function Lr(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof di&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=new Nr,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new $r(t.encoding),this.encoding=t.encoding)}function Ur(t){if(!(this instanceof Ur))return new Ur(t);this._readableState=new Lr(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),At.call(this)}function Fr(t,e,r,i,s){var n=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(n)t.emit("error",n);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,zr(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!s){var a=new Error("stream.push() after EOF");t.emit("error",a)}else if(e.endEmitted&&s){var o=new Error("stream.unshift() after end event");t.emit("error",o)}else{var c;!e.decoder||s||i||(r=e.decoder.write(r),c=!e.objectMode&&0===r.length),s||(e.reading=!1),c||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,s?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&zr(t))),function(t,e){e.readingMore||(e.readingMore=!0,oe(Kr,t,e))}(t,e)}else s||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(e)}le(Ur,At),Ur.prototype.push=function(t,e){var r=this._readableState;return r.objectMode||"string"!=typeof t||(e=e||r.defaultEncoding)!==r.encoding&&(t=Buffer.from(t,e),e=""),Fr(this,r,t,e,!1)},Ur.prototype.unshift=function(t){return Fr(this,this._readableState,t,"",!0)},Ur.prototype.isPaused=function(){return!1===this._readableState.flowing},Ur.prototype.setEncoding=function(t){return this._readableState.decoder=new $r(t),this._readableState.encoding=t,this};var qr=8388608;function Br(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=qr?t=qr:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function zr(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Mr("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?oe(Vr,t):Vr(t))}function Vr(t){Mr("emit readable"),t.emit("readable"),Hr(t)}function Kr(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(Mr("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function Wr(t){Mr("readable nexttick read 0"),t.read(0)}function Jr(t,e){e.reading||(Mr("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),Hr(t),e.flowing&&!e.reading&&t.read(0)}function Hr(t){var e=t._readableState;for(Mr("flow",e.flowing);e.flowing&&null!==t.read(););}function Yr(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var i;t<e.head.data.length?(i=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):i=t===e.head.data.length?e.shift():r?function(t,e){var r=e.head,i=1,s=r.data;t-=s.length;for(;r=r.next;){var n=r.data,a=t>n.length?n.length:t;if(a===n.length?s+=n:s+=n.slice(0,t),0===(t-=a)){a===n.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=n.slice(a));break}++i}return e.length-=i,s}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),i=e.head,s=1;i.data.copy(r),t-=i.data.length;for(;i=i.next;){var n=i.data,a=t>n.length?n.length:t;if(n.copy(r,r.length-t,0,a),0===(t-=a)){a===n.length?(++s,i.next?e.head=i.next:e.head=e.tail=null):(e.head=i,i.data=n.slice(a));break}++s}return e.length-=s,r}(t,e);return i}(t,e.buffer,e.decoder),r);var r}function Gr(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,oe(Qr,e,t))}function Qr(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function Xr(t,e){for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}function Zr(){}function ti(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function ei(t,e){Object.defineProperty(this,"buffer",{get:de(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),t=t||{},this.objectMode=!!t.objectMode,e instanceof di&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var s=!1===t.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,i=r.sync,s=r.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,i,s){--e.pendingcb,r?oe(s,i):s(i);t._writableState.errorEmitted=!0,t.emit("error",i)}(t,r,i,e,s);else{var n=ai(r);n||r.corked||r.bufferProcessing||!r.bufferedRequest||ni(t,r),i?oe(si,t,r,n,s):si(t,r,n,s)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new li(this)}function ri(t){if(!(this instanceof ri||this instanceof di))return new ri(t);this._writableState=new ei(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev)),At.call(this)}function ii(t,e,r,i,s,n,a){e.writelen=i,e.writecb=a,e.writing=!0,e.sync=!0,r?t._writev(s,e.onwrite):t._write(s,n,e.onwrite),e.sync=!1}function si(t,e,r,i){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,i(),ci(t,e)}function ni(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var i=e.bufferedRequestCount,s=new Array(i),n=e.corkedRequestsFree;n.entry=r;for(var a=0;r;)s[a]=r,r=r.next,a+=1;ii(t,e,!0,e.length,s,"",n.finish),e.pendingcb++,e.lastBufferedRequest=null,n.next?(e.corkedRequestsFree=n.next,n.next=null):e.corkedRequestsFree=new li(e)}else{for(;r;){var o=r.chunk,c=r.encoding,l=r.callback;if(ii(t,e,!1,e.objectMode?1:o.length,o,c,l),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function ai(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function oi(t,e){e.prefinished||(e.prefinished=!0,t.emit("prefinish"))}function ci(t,e){var r=ai(e);return r&&(0===e.pendingcb?(oi(t,e),e.finished=!0,t.emit("finish")):oi(t,e)),r}function li(t){var e=this;this.next=null,this.entry=null,this.finish=function(r){var i=e.entry;for(e.entry=null;i;){var s=i.callback;t.pendingcb--,s(r),i=i.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}}Ur.prototype.read=function(t){Mr("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return Mr("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Gr(this):zr(this),null;if(0===(t=Br(t,e))&&e.ended)return 0===e.length&&Gr(this),null;var i,s=e.needReadable;return Mr("need readable",s),(0===e.length||e.length-t<e.highWaterMark)&&Mr("length less than watermark",s=!0),e.ended||e.reading?Mr("reading or ended",s=!1):s&&(Mr("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=Br(r,e))),null===(i=t>0?Yr(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Gr(this)),null!==i&&this.emit("data",i),i},Ur.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Ur.prototype.pipe=function(t,e){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=t;break;case 1:i.pipes=[i.pipes,t];break;default:i.pipes.push(t)}i.pipesCount+=1,Mr("pipe count=%d opts=%j",i.pipesCount,e);var s=!e||!1!==e.end?a:l;function n(t){Mr("onunpipe"),t===r&&l()}function a(){Mr("onend"),t.end()}i.endEmitted?oe(s):r.once("end",s),t.on("unpipe",n);var o=function(t){return function(){var e=t._readableState;Mr("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Hr(t))}}(r);t.on("drain",o);var c=!1;function l(){Mr("cleanup"),t.removeListener("close",d),t.removeListener("finish",p),t.removeListener("drain",o),t.removeListener("error",f),t.removeListener("unpipe",n),r.removeListener("end",a),r.removeListener("end",l),r.removeListener("data",h),c=!0,!i.awaitDrain||t._writableState&&!t._writableState.needDrain||o()}var u=!1;function h(e){Mr("ondata"),u=!1,!1!==t.write(e)||u||((1===i.pipesCount&&i.pipes===t||i.pipesCount>1&&-1!==Xr(i.pipes,t))&&!c&&(Mr("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,u=!0),r.pause())}function f(e){var r;Mr("onerror",e),g(),t.removeListener("error",f),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function d(){t.removeListener("finish",p),g()}function p(){Mr("onfinish"),t.removeListener("close",d),g()}function g(){Mr("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",d),t.once("finish",p),t.emit("pipe",r),i.flowing||(Mr("pipe resume"),r.resume()),t},Ur.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this);return this}var n=Xr(e.pipes,t);return-1===n||(e.pipes.splice(n,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this)),this},Ur.prototype.on=function(t,e){var r=At.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&zr(this):oe(Wr,this))}return r},Ur.prototype.addListener=Ur.prototype.on,Ur.prototype.resume=function(){var t=this._readableState;return t.flowing||(Mr("resume"),t.flowing=!0,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,oe(Jr,t,e))}(this,t)),this},Ur.prototype.pause=function(){return Mr("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Mr("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Ur.prototype.wrap=function(t){var e=this._readableState,r=!1,i=this;for(var s in t.on("end",function(){if(Mr("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&i.push(t)}i.push(null)}),t.on("data",function(s){(Mr("wrapped data"),e.decoder&&(s=e.decoder.write(s)),e.objectMode&&null==s)||(e.objectMode||s&&s.length)&&(i.push(s)||(r=!0,t.pause()))}),t)void 0===this[s]&&"function"==typeof t[s]&&(this[s]=function(e){return function(){return t[e].apply(t,arguments)}}(s));return function(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}(["error","close","destroy","pause","resume"],function(e){t.on(e,i.emit.bind(i,e))}),i._read=function(e){Mr("wrapped _read",e),r&&(r=!1,t.resume())},i},Ur._fromList=Yr,ri.WritableState=ei,le(ri,At),ei.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},ri.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},ri.prototype.write=function(t,e,r){var i=this._writableState,s=!1;return"function"==typeof e&&(r=e,e=null),Je.isBuffer(t)?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=Zr),i.ended?function(t,e){var r=new Error("write after end");t.emit("error",r),oe(e,r)}(this,r):function(t,e,r,i){var s=!0,n=!1;return null===r?n=new TypeError("May not write null values to stream"):Je.isBuffer(r)||"string"==typeof r||void 0===r||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n&&(t.emit("error",n),oe(i,n),s=!1),s}(this,i,t,r)&&(i.pendingcb++,s=function(t,e,r,i,s){r=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Je.from(e,r));return e}(e,r,i),Je.isBuffer(r)&&(i="buffer");var n=e.objectMode?1:r.length;e.length+=n;var a=e.length<e.highWaterMark;a||(e.needDrain=!0);if(e.writing||e.corked){var o=e.lastBufferedRequest;e.lastBufferedRequest=new ti(r,i,s),o?o.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else ii(t,e,!1,n,r,i,s);return a}(this,i,t,e,r)),s},ri.prototype.cork=function(){this._writableState.corked++},ri.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||ni(this,t))},ri.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},ri.prototype._write=function(t,e,r){r(new Error("not implemented"))},ri.prototype._writev=null,ri.prototype.end=function(t,e,r){var i=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||function(t,e,r){e.ending=!0,ci(t,e),r&&(e.finished?oe(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,i,r)},le(di,Ur);for(var ui=Object.keys(ri.prototype),hi=0;hi<ui.length;hi++){var fi=ui[hi];di.prototype[fi]||(di.prototype[fi]=ri.prototype[fi])}function di(t){if(!(this instanceof di))return new di(t);Ur.call(this,t),ri.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",pi)}function pi(){this.allowHalfOpen||this._writableState.ended||oe(gi,this)}function gi(t){t.end()}function mi(t){this.afterTransform=function(e,r){return function(t,e,r){var i=t._transformState;i.transforming=!1;var s=i.writecb;if(!s)return t.emit("error",new Error("no writecb in Transform class"));i.writechunk=null,i.writecb=null,null!=r&&t.push(r);s(e);var n=t._readableState;n.reading=!1,(n.needReadable||n.length<n.highWaterMark)&&t._read(n.highWaterMark)}(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function yi(t){if(!(this instanceof yi))return new yi(t);di.call(this,t),this._transformState=new mi(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(t){bi(e,t)}):bi(e)})}function bi(t,e){if(e)return t.emit("error",e);var r=t._writableState,i=t._transformState;if(r.length)throw new Error("Calling transform done when ws.length != 0");if(i.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}function wi(t){if(!(this instanceof wi))return new wi(t);yi.call(this,t)}function vi(){At.call(this)}le(yi,di),yi.prototype.push=function(t,e){return this._transformState.needTransform=!1,di.prototype.push.call(this,t,e)},yi.prototype._transform=function(t,e,r){throw new Error("Not implemented")},yi.prototype._write=function(t,e,r){var i=this._transformState;if(i.writecb=r,i.writechunk=t,i.writeencoding=e,!i.transforming){var s=this._readableState;(i.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},yi.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},le(wi,yi),wi.prototype._transform=function(t,e,r){r(null,t)},le(vi,At),vi.Readable=Ur,vi.Writable=ri,vi.Duplex=di,vi.Transform=yi,vi.PassThrough=wi,vi.Stream=vi,vi.prototype.pipe=function(t,e){var r=this;function i(e){t.writable&&!1===t.write(e)&&r.pause&&r.pause()}function s(){r.readable&&r.resume&&r.resume()}r.on("data",i),t.on("drain",s),t._isStdio||e&&!1===e.end||(r.on("end",a),r.on("close",o));var n=!1;function a(){n||(n=!0,t.end())}function o(){n||(n=!0,"function"==typeof t.destroy&&t.destroy())}function c(t){if(l(),0===At.listenerCount(this,"error"))throw t}function l(){r.removeListener("data",i),t.removeListener("drain",s),r.removeListener("end",a),r.removeListener("close",o),r.removeListener("error",c),t.removeListener("error",c),r.removeListener("end",l),r.removeListener("close",l),t.removeListener("close",l)}return r.on("error",c),t.on("error",c),r.on("end",l),r.on("close",l),t.on("close",l),t.emit("pipe",r),t};class Si extends At{constructor({resource:t}){super(),this.resource=t,this.client=t.client,this.stream=new s({highWaterMark:3*this.client.parallelism,start:this._start.bind(this),pull:this._pull.bind(this),cancel:this._cancel.bind(this)})}build(){return this.stream.getReader()}async _start(t){this.controller=t,this.continuationToken=null,this.closeNextIteration=!1}async _pull(t){if(this.closeNextIteration)return void t.close();const e=await this.client.listObjects({prefix:`resource=${this.resource.name}`,continuationToken:this.continuationToken}),r=e?.Contents.map(t=>t.Key).map(t=>t.replace(this.client.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t).map(t=>t.replace(`resource=${this.resource.name}/id=`,""));this.continuationToken=e.NextContinuationToken,this.enqueue(r),e.IsTruncated||(this.closeNextIteration=!0)}enqueue(t){t.forEach(t=>{this.controller.enqueue(t),this.emit("id",t)})}_cancel(t){}}var _i=Si;class ki extends _i{enqueue(t){this.controller.enqueue(t),this.emit("page",t)}}class Oi extends At{constructor({resource:t,batchSize:e=10,concurrency:r=5}){if(super(),!t)throw new Error("Resource is required for ResourceReader");this.resource=t,this.client=t.client,this.batchSize=e,this.concurrency=r,this.input=new ki({resource:this.resource}),this.transform=new yi({objectMode:!0,transform:this._transform.bind(this)}),this.input.on("data",t=>{this.transform.write(t)}),this.input.on("end",()=>{this.transform.end()}),this.input.on("error",t=>{this.emit("error",t)}),this.transform.on("data",t=>{this.emit("data",t)}),this.transform.on("end",()=>{this.emit("end")}),this.transform.on("error",t=>{this.emit("error",t)})}build(){return this}async _transform(t,e,r){const[s,n]=await wt(async()=>{await i.for(t).withConcurrency(this.concurrency).handleError(async(t,e)=>{this.emit("error",t,e)}).process(async t=>{const e=await this.resource.get(t);return this.push(e),e})});r(n)}resume(){this.input.resume()}}class Ri extends At{constructor({resource:t,batchSize:e=10,concurrency:r=5}){super(),this.resource=t,this.client=t.client,this.batchSize=e,this.concurrency=r,this.buffer=[],this.writing=!1,this.writable=new ri({objectMode:!0,write:this._write.bind(this)}),this.writable.on("finish",()=>{this.emit("finish")}),this.writable.on("error",t=>{this.emit("error",t)})}build(){return this}write(t){return this.buffer.push(t),this._maybeWrite().catch(t=>{this.emit("error",t)}),!0}end(){this.ended=!0,this._maybeWrite().catch(t=>{this.emit("error",t)})}async _maybeWrite(){if(!this.writing&&(0!==this.buffer.length||this.ended)){for(this.writing=!0;this.buffer.length>0;){const t=this.buffer.splice(0,this.batchSize),[e,r]=await wt(async()=>{await i.for(t).withConcurrency(this.concurrency).handleError(async(t,e)=>{this.emit("error",t,e)}).process(async t=>{const[e,r,i]=await wt(async()=>await this.resource.insert(t));return e?i:(this.emit("error",r,t),null)})});e||this.emit("error",r)}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(t,e,r){r()}}function ji(t){return new Promise((e,r)=>{if(!t)return r(new Error("streamToString: stream is undefined"));const i=[];t.on("data",t=>i.push(t)),t.on("error",r),t.on("end",()=>e(Buffer.concat(i).toString("utf-8")))})}var xi=class extends Yt{constructor({client:t,keyPrefix:e="cache",ttl:r=0,prefix:i}){super({client:t,keyPrefix:e,ttl:r,prefix:i}),this.client=t,this.keyPrefix=e,this.config.ttl=r,this.config.client=t,this.config.prefix=void 0!==i?i:e+(e.endsWith("/")?"":"/")}async _set(t,e){let i=JSON.stringify(e);const s=i.length;return i=r.gzipSync(i).toString("base64"),this.client.putObject({key:Kt(this.keyPrefix,t),body:i,contentEncoding:"gzip",contentType:"application/gzip",metadata:{compressor:"zlib",compressed:"true","client-id":this.client.id,"length-serialized":String(s),"length-compressed":String(i.length),"compression-gain":(i.length/s).toFixed(2)}})}async _get(t){const[e,i,s]=await wt(async()=>{const{Body:e}=await this.client.getObject(Kt(this.keyPrefix,t));let i=await ji(e);return i=Buffer.from(i,"base64"),i=r.unzipSync(i).toString(),JSON.parse(i)});if(e)return s;if("NoSuchKey"===i.name||"NotFound"===i.name)return null;throw i}async _del(t){return await this.client.deleteObject(Kt(this.keyPrefix,t)),!0}async _clear(){const t=await this.client.getAllKeys({prefix:this.keyPrefix});await this.client.deleteObjects(t)}async size(){return(await this.keys()).length}async keys(){const t=await this.client.getAllKeys({prefix:this.keyPrefix}),e=this.keyPrefix.endsWith("/")?this.keyPrefix:this.keyPrefix+"/";return t.map(t=>t.startsWith(e)?t.slice(e.length):t)}};var Ei=class extends Yt{constructor(t={}){super(t),this.cache={},this.meta={},this.maxSize=t.maxSize||0,this.ttl=t.ttl||0}async _set(t,e){if(this.maxSize>0&&Object.keys(this.cache).length>=this.maxSize){const t=Object.entries(this.meta).sort((t,e)=>t[1].ts-e[1].ts)[0]?.[0];t&&(delete this.cache[t],delete this.meta[t])}return this.cache[t]=e,this.meta[t]={ts:Date.now()},e}async _get(t){if(!Object.prototype.hasOwnProperty.call(this.cache,t))return null;if(this.ttl>0){const e=Date.now(),r=this.meta[t];if(r&&e-r.ts>1e3*this.ttl)return delete this.cache[t],delete this.meta[t],null}return this.cache[t]}async _del(t){return delete this.cache[t],delete this.meta[t],!0}async _clear(t){if(!t)return this.cache={},this.meta={},!0;for(const e of Object.keys(this.cache))e.startsWith(t)&&(delete this.cache[e],delete this.meta[e]);return!0}async size(){return Object.keys(this.cache).length}async keys(){return Object.keys(this.cache)}},Di={};class Ai extends Yt{constructor({directory:t,prefix:e="cache",ttl:r=36e5,enableCompression:i=!0,compressionThreshold:s=1024,createDirectory:n=!0,fileExtension:a=".cache",enableMetadata:o=!0,maxFileSize:c=10485760,enableStats:l=!1,enableCleanup:u=!0,cleanupInterval:h=3e5,encoding:f="utf8",fileMode:d=420,enableBackup:p=!1,backupSuffix:g=".bak",enableLocking:m=!1,lockTimeout:y=5e3,enableJournal:b=!1,journalFile:w="cache.journal",...v}){if(super(v),!t)throw new Error("FilesystemCache: directory parameter is required");this.directory=Wt.resolve(t),this.prefix=e,this.ttl=r,this.enableCompression=i,this.compressionThreshold=s,this.createDirectory=n,this.fileExtension=a,this.enableMetadata=o,this.maxFileSize=c,this.enableStats=l,this.enableCleanup=u,this.cleanupInterval=h,this.encoding=f,this.fileMode=d,this.enableBackup=p,this.backupSuffix=g,this.enableLocking=m,this.lockTimeout=y,this.enableJournal=b,this.journalFile=Wt.join(this.directory,w),this.stats={hits:0,misses:0,sets:0,deletes:0,clears:0,errors:0},this.locks=new Map,this.cleanupTimer=null,this._init()}async _init(){this.createDirectory&&await this._ensureDirectory(this.directory),this.enableCleanup&&this.cleanupInterval>0&&(this.cleanupTimer=setInterval(()=>{this._cleanup().catch(t=>{console.warn("FilesystemCache cleanup error:",t.message)})},this.cleanupInterval))}async _ensureDirectory(t){const[e,r]=await wt(async()=>{await n(t,{recursive:!0})});if(!e&&"EEXIST"!==r.code)throw new Error(`Failed to create cache directory: ${r.message}`)}_getFilePath(t){const e=t.replace(/[<>:"/\\|?*]/g,"_"),r=`${this.prefix}_${e}${this.fileExtension}`;return Wt.join(this.directory,r)}_getMetadataPath(t){return t+".meta"}async _set(t,e){const i=this._getFilePath(t);try{let s=JSON.stringify(e);const n=Buffer.byteLength(s,this.encoding);if(n>this.maxFileSize)throw new Error(`Cache data exceeds maximum file size: ${n} > ${this.maxFileSize}`);let o=!1,c=s;if(this.enableCompression&&n>=this.compressionThreshold){c=r.gzipSync(Buffer.from(s,this.encoding)).toString("base64"),o=!0}if(this.enableBackup&&await this._fileExists(i)){const t=i+this.backupSuffix;await this._copyFile(i,t)}this.enableLocking&&await this._acquireLock(i);try{if(await a(i,c,{encoding:o?"utf8":this.encoding,mode:this.fileMode}),this.enableMetadata){const e={key:t,timestamp:Date.now(),ttl:this.ttl,compressed:o,originalSize:n,compressedSize:o?Buffer.byteLength(c,"utf8"):n,compressionRatio:o?(Buffer.byteLength(c,"utf8")/n).toFixed(2):1};await a(this._getMetadataPath(i),JSON.stringify(e),{encoding:this.encoding,mode:this.fileMode})}this.enableStats&&this.stats.sets++,this.enableJournal&&await this._journalOperation("set",t,{size:n,compressed:o})}finally{this.enableLocking&&this._releaseLock(i)}return e}catch(e){throw this.enableStats&&this.stats.errors++,new Error(`Failed to set cache key '${t}': ${e.message}`)}}async _get(t){const e=this._getFilePath(t);try{if(!await this._fileExists(e))return this.enableStats&&this.stats.misses++,null;let i=!1;if(this.enableMetadata){const t=this._getMetadataPath(e);if(await this._fileExists(t)){const[e,r,s]=await wt(async()=>{const e=await o(t,this.encoding);return JSON.parse(e)});if(e&&s.ttl>0){i=Date.now()-s.timestamp>s.ttl}}}else if(this.ttl>0){const t=await c(e);i=Date.now()-t.mtime.getTime()>this.ttl}if(i)return await this._del(t),this.enableStats&&this.stats.misses++,null;this.enableLocking&&await this._acquireLock(e);try{const t=await o(e,this.encoding);let i=!1;if(this.enableMetadata){const t=this._getMetadataPath(e);if(await this._fileExists(t)){const[e,r,s]=await wt(async()=>{const e=await o(t,this.encoding);return JSON.parse(e)});e&&(i=s.compressed)}}let s=t;if(i||this.enableCompression&&t.match(/^[A-Za-z0-9+/=]+$/))try{const e=Buffer.from(t,"base64");s=r.gunzipSync(e).toString(this.encoding)}catch(e){s=t}const n=JSON.parse(s);return this.enableStats&&this.stats.hits++,n}finally{this.enableLocking&&this._releaseLock(e)}}catch(e){return this.enableStats&&this.stats.errors++,await this._del(t),null}}async _del(t){const e=this._getFilePath(t);try{if(await this._fileExists(e)&&await l(e),this.enableMetadata){const t=this._getMetadataPath(e);await this._fileExists(t)&&await l(t)}if(this.enableBackup){const t=e+this.backupSuffix;await this._fileExists(t)&&await l(t)}return this.enableStats&&this.stats.deletes++,this.enableJournal&&await this._journalOperation("delete",t),!0}catch(e){throw this.enableStats&&this.stats.errors++,new Error(`Failed to delete cache key '${t}': ${e.message}`)}}async _clear(t){try{if(!await this._fileExists(this.directory))return this.enableStats&&this.stats.clears++,!0;const e=(await u(this.directory)).filter(e=>{if(!e.startsWith(this.prefix))return!1;if(!e.endsWith(this.fileExtension))return!1;if(t){return e.slice(this.prefix.length+1,-this.fileExtension.length).startsWith(t)}return!0});for(const t of e){const e=Wt.join(this.directory,t);if(await this._fileExists(e)&&await l(e),this.enableMetadata){const t=this._getMetadataPath(e);await this._fileExists(t)&&await l(t)}if(this.enableBackup){const t=e+this.backupSuffix;await this._fileExists(t)&&await l(t)}}return this.enableStats&&this.stats.clears++,this.enableJournal&&await this._journalOperation("clear",t||"all",{count:e.length}),!0}catch(t){throw this.enableStats&&this.stats.errors++,new Error(`Failed to clear cache: ${t.message}`)}}async size(){return(await this.keys()).length}async keys(){try{const t=(await u(this.directory)).filter(t=>t.startsWith(this.prefix)&&t.endsWith(this.fileExtension));return t.map(t=>t.slice(this.prefix.length+1,-this.fileExtension.length))}catch(t){return console.warn("FilesystemCache: Failed to list keys:",t.message),[]}}async _fileExists(t){const[e]=await wt(async()=>{await c(t)});return e}async _copyFile(t,e){const[r,i]=await wt(async()=>{const r=await o(t);await a(e,r)});r||console.warn("FilesystemCache: Failed to create backup:",i.message)}async _cleanup(){if(this.ttl&&!(this.ttl<=0))try{const t=await u(this.directory),e=Date.now();for(const r of t){if(!r.startsWith(this.prefix)||!r.endsWith(this.fileExtension))continue;const t=Wt.join(this.directory,r);let i=!1;if(this.enableMetadata){const r=this._getMetadataPath(t);if(await this._fileExists(r)){const[t,s,n]=await wt(async()=>{const t=await o(r,this.encoding);return JSON.parse(t)});if(t&&n.ttl>0){i=e-n.timestamp>n.ttl}}}else{const[r,s,n]=await wt(async()=>await c(t));if(r){i=e-n.mtime.getTime()>this.ttl}}if(i){const t=r.slice(this.prefix.length+1,-this.fileExtension.length);await this._del(t)}}}catch(t){console.warn("FilesystemCache cleanup error:",t.message)}}async _acquireLock(t){if(!this.enableLocking)return;const e=t,r=Date.now();for(;this.locks.has(e);){if(Date.now()-r>this.lockTimeout)throw new Error(`Lock timeout for file: ${t}`);await new Promise(t=>setTimeout(t,10))}this.locks.set(e,Date.now())}_releaseLock(t){this.enableLocking&&this.locks.delete(t)}async _journalOperation(t,e,r={}){if(!this.enableJournal)return;const i={timestamp:(new Date).toISOString(),operation:t,key:e,metadata:r},[s,n]=await wt(async()=>{const t=JSON.stringify(i)+"\n";await Di.promises.appendFile(this.journalFile,t,this.encoding)});s||console.warn("FilesystemCache journal error:",n.message)}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}getStats(){return{...this.stats,directory:this.directory,ttl:this.ttl,compression:this.enableCompression,metadata:this.enableMetadata,cleanup:this.enableCleanup,locking:this.enableLocking,journal:this.enableJournal}}}class Ni extends Ai{constructor({partitionStrategy:t="hierarchical",trackUsage:e=!0,preloadRelated:r=!1,preloadThreshold:i=10,maxCacheSize:s=null,usageStatsFile:n="partition-usage.json",...a}){super(a),this.partitionStrategy=t,this.trackUsage=e,this.preloadRelated=r,this.preloadThreshold=i,this.maxCacheSize=s,this.usageStatsFile=Wt.join(this.directory,n),this.partitionUsage=new Map,this.loadUsageStats()}_getPartitionCacheKey(t,e,r,i={},s={}){const n=[`resource=${t}`,`action=${e}`];if(r&&Object.keys(i).length>0){n.push(`partition=${r}`);const t=Object.entries(i).sort(([t],[e])=>t.localeCompare(e));for(const[e,r]of t)null!=r&&n.push(`${e}=${r}`)}if(Object.keys(s).length>0){const t=Object.entries(s).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>`${t}=${e}`).join("|");n.push(`params=${Buffer.from(t).toString("base64")}`)}return n.join("/")+this.fileExtension}_getPartitionDirectory(t,e,r={}){const i=Wt.join(this.directory,`resource=${t}`);if(!e)return i;if("flat"===this.partitionStrategy)return Wt.join(i,"partitions");if("temporal"===this.partitionStrategy&&this._isTemporalPartition(e,r))return this._getTemporalDirectory(i,e,r);const s=[i,`partition=${e}`],n=Object.entries(r).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of n)null!=e&&s.push(`${t}=${this._sanitizePathValue(e)}`);return Wt.join(...s)}async _set(t,e,r={}){const{resource:i,action:s,partition:n,partitionValues:a,params:o}=r;if(i&&n){const t=this._getPartitionCacheKey(i,s,n,a,o),r=this._getPartitionDirectory(i,n,a);await this._ensureDirectory(r);const c=Wt.join(r,this._sanitizeFileName(t));this.trackUsage&&await this._trackPartitionUsage(i,n,a);const l={data:e,metadata:{resource:i,partition:n,partitionValues:a,timestamp:Date.now(),ttl:this.ttl}};return this._writeFileWithMetadata(c,l)}return super._set(t,e)}async _get(t,e={}){const{resource:r,action:i,partition:s,partitionValues:n,params:a}=e;if(r&&s){const t=this._getPartitionCacheKey(r,i,s,n,a),e=this._getPartitionDirectory(r,s,n),o=Wt.join(e,this._sanitizeFileName(t));if(!await this._fileExists(o))return this.preloadRelated&&await this._preloadRelatedPartitions(r,s,n),null;const c=await this._readFileWithMetadata(o);return c&&this.trackUsage&&await this._trackPartitionUsage(r,s,n),c?.data||null}return super._get(t)}async clearPartition(t,e,r={}){const i=this._getPartitionDirectory(t,e,r),[s,n]=await wt(async()=>{await this._fileExists(i)&&await h(i,{recursive:!0})});s||console.warn(`Failed to clear partition cache: ${n.message}`);const a=this._getUsageKey(t,e,r);return this.partitionUsage.delete(a),await this._saveUsageStats(),s}async clearResourcePartitions(t){const e=Wt.join(this.directory,`resource=${t}`),[r,i]=await wt(async()=>{await this._fileExists(e)&&await h(e,{recursive:!0})});for(const[e]of this.partitionUsage.entries())e.startsWith(`${t}/`)&&this.partitionUsage.delete(e);return await this._saveUsageStats(),r}async getPartitionStats(t,e=null){const r={totalFiles:0,totalSize:0,partitions:{},usage:{}},i=Wt.join(this.directory,`resource=${t}`);if(!await this._fileExists(i))return r;await this._calculateDirectoryStats(i,r);for(const[i,s]of this.partitionUsage.entries())if(i.startsWith(`${t}/`)){const t=i.split("/")[1];e&&t!==e||(r.usage[t]=s)}return r}async getCacheRecommendations(t){const e=[],r=Date.now();for(const[i,s]of this.partitionUsage.entries())if(i.startsWith(`${t}/`)){const[,t]=i.split("/"),n=(r-s.lastAccess)/864e5,a=s.count/Math.max(1,n);let o="keep",c=s.count;n>30?(o="archive",c=0):a<.1?(o="reduce_ttl",c=1):a>10&&(o="preload",c=100),e.push({partition:t,recommendation:o,priority:c,usage:a,lastAccess:new Date(s.lastAccess).toISOString()})}return e.sort((t,e)=>e.priority-t.priority)}async warmPartitionCache(t,e={}){const{partitions:r=[],maxFiles:i=1e3}=e;let s=0;for(const e of r){const r=`${t}/${e}`,n=this.partitionUsage.get(r);if(n&&n.count>=this.preloadThreshold&&(console.log(`🔥 Warming cache for ${t}/${e} (${n.count} accesses)`),s++),s>=i)break}return s}async _trackPartitionUsage(t,e,r){const i=this._getUsageKey(t,e,r),s=this.partitionUsage.get(i)||{count:0,firstAccess:Date.now(),lastAccess:Date.now()};s.count++,s.lastAccess=Date.now(),this.partitionUsage.set(i,s),s.count%10==0&&await this._saveUsageStats()}_getUsageKey(t,e,r){const i=Object.entries(r).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>`${t}=${e}`).join("|");return`${t}/${e}/${i}`}async _preloadRelatedPartitions(t,e,r){console.log(`🎯 Preloading related partitions for ${t}/${e}`),r.timestamp||r.date}_isTemporalPartition(t,e){const r=["date","timestamp","createdAt","updatedAt"];return Object.keys(e).some(t=>r.some(e=>t.toLowerCase().includes(e)))}_getTemporalDirectory(t,e,r){const i=Object.values(r)[0];if("string"==typeof i&&i.match(/^\d{4}-\d{2}-\d{2}/)){const[e,r,s]=i.split("-");return Wt.join(t,"temporal",e,r,s)}return Wt.join(t,`partition=${e}`)}_sanitizePathValue(t){return String(t).replace(/[<>:"/\\|?*]/g,"_")}_sanitizeFileName(t){return t.replace(/[<>:"/\\|?*]/g,"_")}async _calculateDirectoryStats(t,e){const[r,i,s]=await wt(()=>u(t));if(r)for(const r of s){const i=Wt.join(t,r),[s,n,a]=await wt(()=>c(i));s&&(a.isDirectory()?await this._calculateDirectoryStats(i,e):(e.totalFiles++,e.totalSize+=a.size))}}async loadUsageStats(){const[t,e,r]=await wt(async()=>{const t=await o(this.usageStatsFile,"utf8");return JSON.parse(t)});t&&r&&(this.partitionUsage=new Map(Object.entries(r)))}async _saveUsageStats(){const t=Object.fromEntries(this.partitionUsage);await wt(async()=>{await a(this.usageStatsFile,JSON.stringify(t,null,2),"utf8")})}async _writeFileWithMetadata(t,e){const r=JSON.stringify(e),[i,s]=await wt(async()=>{await a(t,r,{encoding:this.encoding,mode:this.fileMode})});if(!i)throw new Error(`Failed to write cache file: ${s.message}`);return!0}async _readFileWithMetadata(t){const[e,r,i]=await wt(async()=>await o(t,this.encoding));if(!e||!i)return null;try{return JSON.parse(i)}catch(t){return{data:i}}}}class Ii extends Tt{constructor(t={}){super(t),this.driver=t.driver,this.config={includePartitions:!1!==t.includePartitions,partitionStrategy:t.partitionStrategy||"hierarchical",partitionAware:!1!==t.partitionAware,trackUsage:!1!==t.trackUsage,preloadRelated:!1!==t.preloadRelated,...t}}async setup(t){await super.setup(t)}async onSetup(){this.config.driver?this.driver=this.config.driver:"memory"===this.config.driverType?this.driver=new Ei(this.config.memoryOptions||{}):"filesystem"===this.config.driverType?this.config.partitionAware?this.driver=new Ni({partitionStrategy:this.config.partitionStrategy,trackUsage:this.config.trackUsage,preloadRelated:this.config.preloadRelated,...this.config.filesystemOptions}):this.driver=new Ai(this.config.filesystemOptions||{}):this.driver=new xi({client:this.database.client,...this.config.s3Options||{}}),this.installDatabaseProxy(),this.installResourceHooks()}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._cacheProxyInstalled)return;const t=this.installResourceHooks.bind(this);this.database._originalCreateResourceForCache=this.database.createResource,this.database.createResource=async function(...e){const r=await this._originalCreateResourceForCache(...e);return t(r),r},this.database._cacheProxyInstalled=!0}installResourceHooks(){for(const t of Object.values(this.database.resources))this.installResourceHooksForResource(t)}installResourceHooksForResource(t){if(!this.driver)return;Object.defineProperty(t,"cache",{value:this.driver,writable:!0,configurable:!0,enumerable:!1}),t.cacheKeyFor=async(e={})=>{const{action:r,params:i={},partition:s,partitionValues:n}=e;return this.generateCacheKey(t,r,i,s,n)},this.driver instanceof Ni&&(t.clearPartitionCache=async(e,r={})=>await this.driver.clearPartition(t.name,e,r),t.getPartitionCacheStats=async(e=null)=>await this.driver.getPartitionStats(t.name,e),t.getCacheRecommendations=async()=>await this.driver.getCacheRecommendations(t.name),t.warmPartitionCache=async(e=[],r={})=>await this.driver.warmPartitionCache(t.name,{partitions:e,...r}));const e=["count","listIds","getMany","getAll","page","list","get"];for(const r of e)t.useMiddleware(r,async(e,i)=>{let s;if("getMany"===r)s=await t.cacheKeyFor({action:r,params:{ids:e.args[0]}});else if("page"===r){const{offset:i,size:n,partition:a,partitionValues:o}=e.args[0]||{};s=await t.cacheKeyFor({action:r,params:{offset:i,size:n},partition:a,partitionValues:o})}else if("list"===r||"listIds"===r||"count"===r){const{partition:i,partitionValues:n}=e.args[0]||{};s=await t.cacheKeyFor({action:r,partition:i,partitionValues:n})}else"getAll"===r?s=await t.cacheKeyFor({action:r}):"get"===r&&(s=await t.cacheKeyFor({action:r,params:{id:e.args[0]}}));if(this.driver instanceof Ni){let n,a;if("list"===r||"listIds"===r||"count"===r||"page"===r){const t=e.args[0]||{};n=t.partition,a=t.partitionValues}const[o,c,l]=await wt(()=>t.cache._get(s,{resource:t.name,action:r,partition:n,partitionValues:a}));if(o&&null!=l)return l;if(!o&&"NoSuchKey"!==c.name)throw c;const u=await i();return await t.cache._set(s,u,{resource:t.name,action:r,partition:n,partitionValues:a}),u}{const[e,r,n]=await wt(()=>t.cache.get(s));if(e&&null!=n)return n;if(!e&&"NoSuchKey"!==r.name)throw r;const a=await i();return await t.cache.set(s,a),a}});const r=["insert","update","delete","deleteMany"];for(const e of r)t.useMiddleware(e,async(r,i)=>{const s=await i();if("insert"===e)await this.clearCacheForResource(t,r.args[0]);else if("update"===e)await this.clearCacheForResource(t,{id:r.args[0],...r.args[1]});else if("delete"===e){let e={id:r.args[0]};if("function"==typeof t.get){const[i,s,n]=await wt(()=>t.get(r.args[0]));i&&n&&(e=n)}await this.clearCacheForResource(t,e)}else"deleteMany"===e&&await this.clearCacheForResource(t);return s})}async clearCacheForResource(t,e){if(!t.cache)return;const r=`resource=${t.name}`;if(await t.cache.clear(r),!0===this.config.includePartitions&&t.config?.partitions&&Object.keys(t.config.partitions).length>0)if(e){const i=this.getPartitionValues(e,t);for(const[e,s]of Object.entries(i))if(s&&Object.keys(s).length>0&&Object.values(s).some(t=>null!=t)){const i=Kt(r,`partition=${e}`);await t.cache.clear(i)}}else for(const e of Object.keys(t.config.partitions)){const i=Kt(r,`partition=${e}`);await t.cache.clear(i)}}async generateCacheKey(t,e,r={},i=null,s=null){const n=[`resource=${t.name}`,`action=${e}`];if(i&&s&&Object.keys(s).length>0){n.push(`partition:${i}`);for(const[t,e]of Object.entries(s))null!=e&&n.push(`${t}:${e}`)}if(Object.keys(r).length>0){const t=await this.hashParams(r);n.push(t)}return Kt(...n)+".json.gz"}async hashParams(t){const e=Object.keys(t).sort().map(e=>`${e}:${t[e]}`).join("|")||"empty";return await St(e)}async getCacheStats(){return this.driver?{size:await this.driver.size(),keys:await this.driver.keys(),driver:this.driver.constructor.name}:null}async clearAllCache(){if(this.driver)for(const t of Object.values(this.database.resources))if(t.cache){const e=`resource=${t.name}`;await t.cache.clear(e)}}async warmCache(t,e={}){const r=this.database.resources[t];if(!r)throw new Error(`Resource '${t}' not found`);const{includePartitions:i=!0}=e;if(this.driver instanceof Ni&&r.warmPartitionCache){const t=r.config.partitions?Object.keys(r.config.partitions):[];return await r.warmPartitionCache(t,e)}if(await r.getAll(),i&&r.config.partitions)for(const[t,e]of Object.entries(r.config.partitions))if(e.fields){const e=await r.getAll(),i=Array.isArray(e)?e:[],s=new Set;for(const e of i.slice(0,10)){const i=this.getPartitionValues(e,r);i[t]&&s.add(JSON.stringify(i[t]))}for(const e of s){const i=JSON.parse(e);await r.list({partition:t,partitionValues:i})}}}async getPartitionCacheStats(t,e=null){if(!(this.driver instanceof Ni))throw new Error("Partition cache statistics are only available with PartitionAwareFilesystemCache");return await this.driver.getPartitionStats(t,e)}async getCacheRecommendations(t){if(!(this.driver instanceof Ni))throw new Error("Cache recommendations are only available with PartitionAwareFilesystemCache");return await this.driver.getCacheRecommendations(t)}async clearPartitionCache(t,e,r={}){if(!(this.driver instanceof Ni))throw new Error("Partition cache clearing is only available with PartitionAwareFilesystemCache");return await this.driver.clearPartition(t,e,r)}async analyzeCacheUsage(){if(!(this.driver instanceof Ni))return{message:"Cache usage analysis is only available with PartitionAwareFilesystemCache"};const t={totalResources:Object.keys(this.database.resources).length,resourceStats:{},recommendations:{},summary:{mostUsedPartitions:[],leastUsedPartitions:[],suggestedOptimizations:[]}};for(const[e,r]of Object.entries(this.database.resources))try{t.resourceStats[e]=await this.driver.getPartitionStats(e),t.recommendations[e]=await this.driver.getCacheRecommendations(e)}catch(r){t.resourceStats[e]={error:r.message}}const e=Object.values(t.recommendations).flat();return t.summary.mostUsedPartitions=e.filter(t=>"preload"===t.recommendation).sort((t,e)=>e.priority-t.priority).slice(0,5),t.summary.leastUsedPartitions=e.filter(t=>"archive"===t.recommendation).slice(0,5),t.summary.suggestedOptimizations=[`Consider preloading ${t.summary.mostUsedPartitions.length} high-usage partitions`,`Archive ${t.summary.leastUsedPartitions.length} unused partitions`,"Monitor cache hit rates for partition efficiency"],t}}const $i={async setup(t){t&&t.client&&(this.client=t.client,this.map={PutObjectCommand:"put",GetObjectCommand:"get",HeadObjectCommand:"head",DeleteObjectCommand:"delete",DeleteObjectsCommand:"delete",ListObjectsV2Command:"list"},this.costs={total:0,prices:{put:5e-6,copy:5e-6,list:5e-6,post:5e-6,get:4e-4/1e3,select:4e-4/1e3,delete:4e-4/1e3,head:4e-4/1e3},requests:{total:0,put:0,post:0,copy:0,list:0,get:0,select:0,delete:0,head:0},events:{total:0,PutObjectCommand:0,GetObjectCommand:0,HeadObjectCommand:0,DeleteObjectCommand:0,DeleteObjectsCommand:0,ListObjectsV2Command:0}},this.client.costs=JSON.parse(JSON.stringify(this.costs)))},async start(){this.client&&(this.client.on("command.response",t=>this.addRequest(t,this.map[t])),this.client.on("command.error",t=>this.addRequest(t,this.map[t])))},addRequest(t,e){e&&(this.costs.events[t]++,this.costs.events.total++,this.costs.requests.total++,this.costs.requests[e]++,this.costs.total+=this.costs.prices[e],this.client&&this.client.costs&&(this.client.costs.events[t]++,this.client.costs.events.total++,this.client.costs.requests.total++,this.client.costs.requests[e]++,this.client.costs.total+=this.client.costs.prices[e]))}};class Pi extends Tt{constructor(t={}){super(),this.indexResource=null,this.config={minWordLength:t.minWordLength||3,maxResults:t.maxResults||100,...t},this.indexes=new Map}async setup(t){this.database=t;const[e,r,i]=await wt(()=>t.createResource({name:"fulltext_indexes",attributes:{id:"string|required",resourceName:"string|required",fieldName:"string|required",word:"string|required",recordIds:"json|required",count:"number|required",lastUpdated:"string|required"}}));this.indexResource=e?i:t.resources.fulltext_indexes,await this.loadIndexes(),this.installIndexingHooks()}async start(){}async stop(){await this.saveIndexes()}async loadIndexes(){if(!this.indexResource)return;const[t,e,r]=await wt(()=>this.indexResource.getAll());if(t)for(const t of r){const e=`${t.resourceName}:${t.fieldName}:${t.word}`;this.indexes.set(e,{recordIds:t.recordIds||[],count:t.count||0})}}async saveIndexes(){if(!this.indexResource)return;const[t,e]=await wt(async()=>{const t=await this.indexResource.getAll();for(const e of t)await this.indexResource.delete(e.id);for(const[t,e]of this.indexes.entries()){const[r,i,s]=t.split(":");await this.indexResource.insert({id:`index-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:r,fieldName:i,word:s,recordIds:e.recordIds,count:e.count,lastUpdated:(new Date).toISOString()})}})}installIndexingHooks(){this.database.plugins||(this.database.plugins={}),this.database.plugins.fulltext=this;for(const t of Object.values(this.database.resources))"fulltext_indexes"!==t.name&&this.installResourceHooks(t);this.database._fulltextProxyInstalled||(this.database._previousCreateResourceForFullText=this.database.createResource,this.database.createResource=async function(...t){const e=await this._previousCreateResourceForFullText(...t);return this.plugins?.fulltext&&"fulltext_indexes"!==e.name&&this.plugins.fulltext.installResourceHooks(e),e},this.database._fulltextProxyInstalled=!0);for(const t of Object.values(this.database.resources))"fulltext_indexes"!==t.name&&this.installResourceHooks(t)}installResourceHooks(t){t._insert=t.insert,t._update=t.update,t._delete=t.delete,t._deleteMany=t.deleteMany,this.wrapResourceMethod(t,"insert",async(e,r,i)=>{const[s]=r;return this.indexRecord(t.name,e.id,s).catch(()=>{}),e}),this.wrapResourceMethod(t,"update",async(e,r,i)=>{const[s,n]=r;return this.removeRecordFromIndex(t.name,s).catch(()=>{}),this.indexRecord(t.name,s,e).catch(()=>{}),e}),this.wrapResourceMethod(t,"delete",async(e,r,i)=>{const[s]=r;return this.removeRecordFromIndex(t.name,s).catch(()=>{}),e}),this.wrapResourceMethod(t,"deleteMany",async(e,r,i)=>{const[s]=r;for(const e of s)this.removeRecordFromIndex(t.name,e).catch(()=>{});return e})}async indexRecord(t,e,r){const i=this.getIndexedFields(t);if(i&&0!==i.length)for(const s of i){const i=this.getFieldValue(r,s);if(!i)continue;const n=this.tokenize(i);for(const r of n){if(r.length<this.config.minWordLength)continue;const i=`${t}:${s}:${r.toLowerCase()}`,n=this.indexes.get(i)||{recordIds:[],count:0};n.recordIds.includes(e)||(n.recordIds.push(e),n.count=n.recordIds.length),this.indexes.set(i,n)}}}async removeRecordFromIndex(t,e){for(const[r,i]of this.indexes.entries())if(r.startsWith(`${t}:`)){const t=i.recordIds.indexOf(e);t>-1&&(i.recordIds.splice(t,1),i.count=i.recordIds.length,0===i.recordIds.length?this.indexes.delete(r):this.indexes.set(r,i))}}getFieldValue(t,e){if(!e.includes("."))return t&&void 0!==t[e]?t[e]:null;const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return null;i=i[t]}return i}tokenize(t){if(!t)return[];return String(t).toLowerCase().replace(/[^\w\s\u00C0-\u017F]/g," ").split(/\s+/).filter(t=>t.length>0)}getIndexedFields(t){if(this.config.fields)return this.config.fields;return{users:["name","email"],products:["name","description"],articles:["title","content"]}[t]||[]}async search(t,e,r={}){const{fields:i=null,limit:s=this.config.maxResults,offset:n=0,exactMatch:a=!1}=r;if(!e||0===e.trim().length)return[];const o=this.tokenize(e),c=new Map,l=i||this.getIndexedFields(t);if(0===l.length)return[];for(const e of o)if(!(e.length<this.config.minWordLength))for(const r of l)if(a){const i=`${t}:${r}:${e.toLowerCase()}`,s=this.indexes.get(i);if(s)for(const t of s.recordIds){const e=c.get(t)||0;c.set(t,e+1)}}else for(const[i,s]of this.indexes.entries())if(i.startsWith(`${t}:${r}:${e.toLowerCase()}`))for(const t of s.recordIds){const e=c.get(t)||0;c.set(t,e+1)}return Array.from(c.entries()).map(([t,e])=>({recordId:t,score:e})).sort((t,e)=>e.score-t.score).slice(n,n+s)}async searchRecords(t,e,r={}){const i=await this.search(t,e,r);if(0===i.length)return[];const s=this.database.resources[t];if(!s)throw new Error(`Resource '${t}' not found`);const n=i.map(t=>t.recordId);return(await s.getMany(n)).filter(t=>t&&"object"==typeof t).map(t=>{const e=i.find(e=>e.recordId===t.id);return{...t,_searchScore:e?e.score:0}}).sort((t,e)=>e._searchScore-t._searchScore)}async rebuildIndex(t){const e=this.database.resources[t];if(!e)throw new Error(`Resource '${t}' not found`);for(const[e]of this.indexes.entries())e.startsWith(`${t}:`)&&this.indexes.delete(e);const r=await e.getAll();for(let e=0;e<r.length;e+=100){const i=r.slice(e,e+100);for(const e of i){const[r,i]=await wt(()=>this.indexRecord(t,e.id,e))}}await this.saveIndexes()}async getIndexStats(){const t={totalIndexes:this.indexes.size,resources:{},totalWords:0};for(const[e,r]of this.indexes.entries()){const[i,s]=e.split(":");t.resources[i]||(t.resources[i]={fields:{},totalRecords:new Set,totalWords:0}),t.resources[i].fields[s]||(t.resources[i].fields[s]={words:0,totalOccurrences:0}),t.resources[i].fields[s].words++,t.resources[i].fields[s].totalOccurrences+=r.count,t.resources[i].totalWords++;for(const e of r.recordIds)t.resources[i].totalRecords.add(e);t.totalWords++}for(const e in t.resources)t.resources[e].totalRecords=t.resources[e].totalRecords.size;return t}async rebuildAllIndexes({timeout:t}={}){return t?Promise.race([this._rebuildAllIndexesInternal(),new Promise((e,r)=>setTimeout(()=>r(new Error("Timeout")),t))]):this._rebuildAllIndexesInternal()}async _rebuildAllIndexesInternal(){const t=Object.keys(this.database.resources).filter(t=>"fulltext_indexes"!==t);for(const e of t){const[t,r]=await wt(()=>this.rebuildIndex(e))}}async clearIndex(t){for(const[e]of this.indexes.entries())e.startsWith(`${t}:`)&&this.indexes.delete(e);await this.saveIndexes()}async clearAllIndexes(){this.indexes.clear(),await this.saveIndexes()}}class Ci extends Tt{constructor(t={}){super(),this.config={collectPerformance:!1!==t.collectPerformance,collectErrors:!1!==t.collectErrors,collectUsage:!1!==t.collectUsage,retentionDays:t.retentionDays||30,flushInterval:t.flushInterval||6e4,...t},this.metrics={operations:{insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}},resources:{},errors:[],performance:[],startTime:(new Date).toISOString()},this.flushTimer=null}async setup(t){if(this.database=t,"undefined"!=typeof process&&"test"===process.env.NODE_ENV)return;const[e,r]=await wt(async()=>{const[e,r,i]=await wt(()=>t.createResource({name:"metrics",attributes:{id:"string|required",type:"string|required",resourceName:"string",operation:"string",count:"number|required",totalTime:"number|required",errors:"number|required",avgTime:"number|required",timestamp:"string|required",metadata:"json"}}));this.metricsResource=e?i:t.resources.metrics;const[s,n,a]=await wt(()=>t.createResource({name:"error_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",error:"string|required",timestamp:"string|required",metadata:"json"}}));this.errorsResource=s?a:t.resources.error_logs;const[o,c,l]=await wt(()=>t.createResource({name:"performance_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",duration:"number|required",timestamp:"string|required",metadata:"json"}}));this.performanceResource=o?l:t.resources.performance_logs});e||(this.metricsResource=t.resources.metrics,this.errorsResource=t.resources.error_logs,this.performanceResource=t.resources.performance_logs),this.installMetricsHooks(),"undefined"!=typeof process&&"test"!==process.env.NODE_ENV&&this.startFlushTimer()}async start(){}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"undefined"!=typeof process&&"test"!==process.env.NODE_ENV&&await this.flushMetrics()}installMetricsHooks(){for(const t of Object.values(this.database.resources))["metrics","error_logs","performance_logs"].includes(t.name)||this.installResourceHooks(t);this.database._createResource=this.database.createResource,this.database.createResource=async function(...t){const e=await this._createResource(...t);return this.plugins?.metrics&&!["metrics","error_logs","performance_logs"].includes(e.name)&&this.plugins.metrics.installResourceHooks(e),e}}installResourceHooks(t){t._insert=t.insert,t._update=t.update,t._delete=t.delete,t._deleteMany=t.deleteMany,t._get=t.get,t._getMany=t.getMany,t._getAll=t.getAll,t._list=t.list,t._listIds=t.listIds,t._count=t.count,t._page=t.page,t.insert=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._insert(...e));if(this.recordOperation(t.name,"insert",Date.now()-r,!i),i||this.recordError(t.name,"insert",s),!i)throw s;return n}.bind(this),t.update=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._update(...e));if(this.recordOperation(t.name,"update",Date.now()-r,!i),i||this.recordError(t.name,"update",s),!i)throw s;return n}.bind(this),t.delete=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._delete(...e));if(this.recordOperation(t.name,"delete",Date.now()-r,!i),i||this.recordError(t.name,"delete",s),!i)throw s;return n}.bind(this),t.deleteMany=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._deleteMany(...e));if(this.recordOperation(t.name,"delete",Date.now()-r,!i),i||this.recordError(t.name,"delete",s),!i)throw s;return n}.bind(this),t.get=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._get(...e));if(this.recordOperation(t.name,"get",Date.now()-r,!i),i||this.recordError(t.name,"get",s),!i)throw s;return n}.bind(this),t.getMany=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._getMany(...e));if(this.recordOperation(t.name,"get",Date.now()-r,!i),i||this.recordError(t.name,"get",s),!i)throw s;return n}.bind(this),t.getAll=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._getAll(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this),t.list=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._list(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this),t.listIds=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._listIds(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this),t.count=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._count(...e));if(this.recordOperation(t.name,"count",Date.now()-r,!i),i||this.recordError(t.name,"count",s),!i)throw s;return n}.bind(this),t.page=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._page(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this)}recordOperation(t,e,r,i){this.metrics.operations[e]&&(this.metrics.operations[e].count++,this.metrics.operations[e].totalTime+=r,i&&this.metrics.operations[e].errors++),this.metrics.resources[t]||(this.metrics.resources[t]={insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}}),this.metrics.resources[t][e]&&(this.metrics.resources[t][e].count++,this.metrics.resources[t][e].totalTime+=r,i&&this.metrics.resources[t][e].errors++),this.config.collectPerformance&&this.metrics.performance.push({resourceName:t,operation:e,duration:r,timestamp:(new Date).toISOString()})}recordError(t,e,r){this.config.collectErrors&&this.metrics.errors.push({resourceName:t,operation:e,error:r.message,stack:r.stack,timestamp:(new Date).toISOString()})}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flushMetrics().catch(()=>{})},this.config.flushInterval))}async flushMetrics(){if(!this.metricsResource)return;const[t,e]=await wt(async()=>{let t,e,r,i;"undefined"!=typeof process&&"test"===process.env.NODE_ENV?(t={},e={},r={},i={}):(t={global:"true"},e={perf:"true"},r={error:"true"},i={resource:"true"});for(const[e,r]of Object.entries(this.metrics.operations))r.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:"global",operation:e,count:r.count,totalTime:r.totalTime,errors:r.errors,avgTime:r.count>0?r.totalTime/r.count:0,timestamp:(new Date).toISOString(),metadata:t});for(const[t,e]of Object.entries(this.metrics.resources))for(const[r,s]of Object.entries(e))s.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:t,operation:r,count:s.count,totalTime:s.totalTime,errors:s.errors,avgTime:s.count>0?s.totalTime/s.count:0,timestamp:(new Date).toISOString(),metadata:i});if(this.config.collectPerformance&&this.metrics.performance.length>0)for(const t of this.metrics.performance)await this.performanceResource.insert({id:`perf-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.resourceName,operation:t.operation,duration:t.duration,timestamp:t.timestamp,metadata:e});if(this.config.collectErrors&&this.metrics.errors.length>0)for(const t of this.metrics.errors)await this.errorsResource.insert({id:`error-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.resourceName,operation:t.operation,error:t.error,stack:t.stack,timestamp:t.timestamp,metadata:r});this.resetMetrics()})}resetMetrics(){for(const t of Object.keys(this.metrics.operations))this.metrics.operations[t]={count:0,totalTime:0,errors:0};for(const t of Object.keys(this.metrics.resources))for(const e of Object.keys(this.metrics.resources[t]))this.metrics.resources[t][e]={count:0,totalTime:0,errors:0};this.metrics.performance=[],this.metrics.errors=[]}async getMetrics(t={}){const{type:e="operation",resourceName:r,operation:i,startDate:s,endDate:n,limit:a=100,offset:o=0}=t;if(!this.metricsResource)return[];let c=(await this.metricsResource.getAll()).filter(t=>(!e||t.type===e)&&((!r||t.resourceName===r)&&((!i||t.operation===i)&&(!(s&&new Date(t.timestamp)<new Date(s))&&!(n&&new Date(t.timestamp)>new Date(n))))));return c.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),c.slice(o,o+a)}async getErrorLogs(t={}){if(!this.errorsResource)return[];const{resourceName:e,operation:r,startDate:i,endDate:s,limit:n=100,offset:a=0}=t;let o=(await this.errorsResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(i&&new Date(t.timestamp)<new Date(i))&&!(s&&new Date(t.timestamp)>new Date(s)))));return o.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),o.slice(a,a+n)}async getPerformanceLogs(t={}){if(!this.performanceResource)return[];const{resourceName:e,operation:r,startDate:i,endDate:s,limit:n=100,offset:a=0}=t;let o=(await this.performanceResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(i&&new Date(t.timestamp)<new Date(i))&&!(s&&new Date(t.timestamp)>new Date(s)))));return o.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),o.slice(a,a+n)}async getStats(){const t=new Date,e=new Date(t.getTime()-864e5),[r,i,s]=await Promise.all([this.getMetrics({startDate:e.toISOString()}),this.getErrorLogs({startDate:e.toISOString()}),this.getPerformanceLogs({startDate:e.toISOString()})]),n={period:"24h",totalOperations:0,totalErrors:i.length,avgResponseTime:0,operationsByType:{},resources:{},uptime:{startTime:this.metrics.startTime,duration:t.getTime()-new Date(this.metrics.startTime).getTime()}};for(const t of r)if("operation"===t.type){n.totalOperations+=t.count,n.operationsByType[t.operation]||(n.operationsByType[t.operation]={count:0,errors:0,avgTime:0}),n.operationsByType[t.operation].count+=t.count,n.operationsByType[t.operation].errors+=t.errors;const e=n.operationsByType[t.operation],r=e.count,i=(e.avgTime*(r-t.count)+t.totalTime)/r;e.avgTime=i}const a=r.reduce((t,e)=>t+e.totalTime,0),o=r.reduce((t,e)=>t+e.count,0);return n.avgResponseTime=o>0?a/o:0,n}async cleanupOldData(){const t=new Date;if(t.setDate(t.getDate()-this.config.retentionDays),this.metricsResource){const e=await this.getMetrics({endDate:t.toISOString()});for(const t of e)await this.metricsResource.delete(t.id)}if(this.errorsResource){const e=await this.getErrorLogs({endDate:t.toISOString()});for(const t of e)await this.errorsResource.delete(t.id)}if(this.performanceResource){const e=await this.getPerformanceLogs({endDate:t.toISOString()});for(const t of e)await this.performanceResource.delete(t.id)}}}var Ti=class extends At{constructor(t={}){super(),this.config=t,this.name=this.constructor.name,this.enabled=!1!==t.enabled}async initialize(t){this.database=t,this.emit("initialized",{replicator:this.name})}async replicate(t,e,r,i){throw new Error(`replicate() method must be implemented by ${this.name}`)}async replicateBatch(t,e){throw new Error(`replicateBatch() method must be implemented by ${this.name}`)}async testConnection(){throw new Error(`testConnection() method must be implemented by ${this.name}`)}async getStatus(){return{name:this.name,config:this.config,connected:!1}}async cleanup(){this.emit("cleanup",{replicator:this.name})}validateConfig(){return{isValid:!0,errors:[]}}};var Mi=class extends Ti{constructor(t={},e={}){super(t),this.projectId=t.projectId,this.datasetId=t.datasetId,this.bigqueryClient=null,this.credentials=t.credentials,this.location=t.location||"US",this.logTable=t.logTable,this.resources=this.parseResourcesConfig(e)}parseResourcesConfig(t){const e={};for(const[r,i]of Object.entries(t))"string"==typeof i?e[r]=[{table:i,actions:["insert"],transform:null}]:Array.isArray(i)?e[r]=i.map(t=>"string"==typeof t?{table:t,actions:["insert"],transform:null}:{table:t.table,actions:t.actions||["insert"],transform:t.transform||null}):"object"==typeof i&&(e[r]=[{table:i.table,actions:i.actions||["insert"],transform:i.transform||null}]);return e}validateConfig(){const t=[];this.projectId||t.push("projectId is required"),this.datasetId||t.push("datasetId is required"),0===Object.keys(this.resources).length&&t.push("At least one resource must be configured");for(const[e,r]of Object.entries(this.resources))for(const i of r){i.table||t.push(`Table name is required for resource '${e}'`),Array.isArray(i.actions)&&0!==i.actions.length||t.push(`Actions array is required for resource '${e}'`);const r=["insert","update","delete"],s=i.actions.filter(t=>!r.includes(t));s.length>0&&t.push(`Invalid actions for resource '${e}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`),i.transform&&"function"!=typeof i.transform&&t.push(`Transform must be a function for resource '${e}'`)}return{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);const[e,r,i]=await wt(()=>import("@google-cloud/bigquery"));if(!e)throw this.config.verbose&&console.warn(`[BigqueryReplicator] Failed to import BigQuery SDK: ${r.message}`),this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{BigQuery:s}=i;this.bigqueryClient=new s({projectId:this.projectId,credentials:this.credentials,location:this.location}),this.emit("initialized",{replicator:this.name,projectId:this.projectId,datasetId:this.datasetId,resources:Object.keys(this.resources)})}shouldReplicateResource(t){return this.resources.hasOwnProperty(t)}shouldReplicateAction(t,e){return!!this.resources[t]&&this.resources[t].some(t=>t.actions.includes(e))}getTablesForResource(t,e){return this.resources[t]?this.resources[t].filter(t=>t.actions.includes(e)).map(t=>({table:t.table,transform:t.transform})):[]}applyTransform(t,e){let r=this._cleanInternalFields(t);return e?e(JSON.parse(JSON.stringify(r))):r}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}async replicate(t,e,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(t,e))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(t,e);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const a=[],o=[],[c,l,u]=await wt(async()=>{const s=this.bigqueryClient.dataset(this.datasetId);for(const t of n){const[n,c]=await wt(async()=>{const n=s.table(t.table);let o;if("insert"===e){const e=this.applyTransform(r,t.transform);try{o=await n.insert([e])}catch(t){const{errors:e,response:r}=t;throw this.config.verbose&&(console.error("[BigqueryReplicator] BigQuery insert error details:"),e&&console.error("Errors:",JSON.stringify(e,null,2)),r&&console.error("Response:",JSON.stringify(r,null,2))),t}}else if("update"===e){const e=this.applyTransform(r,t.transform),s=Object.keys(e).filter(t=>"id"!==t).map(t=>`${t} = @${t}`).join(", "),n={id:i,...e},a=`UPDATE \`${this.projectId}.${this.datasetId}.${t.table}\` SET ${s} WHERE id = @id`,c=2;let l=null;for(let t=1;t<=c;t++){const[e,r]=await wt(async()=>{const[t]=await this.bigqueryClient.createQueryJob({query:a,params:n,location:this.location});return await t.getQueryResults(),[t]});if(e){o=e;break}if(l=r,this.config.verbose&&(console.warn(`[BigqueryReplicator] Update attempt ${t} failed: ${r.message}`),r.errors&&(console.error("[BigqueryReplicator] BigQuery update error details:"),console.error("Errors:",JSON.stringify(r.errors,null,2)))),r?.message?.includes("streaming buffer")&&t<c){const t=30;this.config.verbose&&console.warn(`[BigqueryReplicator] Retrying in ${t} seconds due to streaming buffer issue`),await new Promise(e=>setTimeout(e,1e3*t));continue}throw r}if(!o)throw l}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const e=`DELETE FROM \`${this.projectId}.${this.datasetId}.${t.table}\` WHERE id = @id`;try{const[t]=await this.bigqueryClient.createQueryJob({query:e,params:{id:i},location:this.location});await t.getQueryResults(),o=[t]}catch(t){throw this.config.verbose&&(console.error("[BigqueryReplicator] BigQuery delete error details:"),console.error("Query:",e),t.errors&&console.error("Errors:",JSON.stringify(t.errors,null,2)),t.response&&console.error("Response:",JSON.stringify(t.response,null,2))),t}}}a.push({table:t.table,success:!0,jobId:o[0]?.id})});n||o.push({table:t.table,error:c.message})}if(this.logTable){const[n,a]=await wt(async()=>{const n=s.table(this.logTable);await n.insert([{resource_name:t,operation:e,record_id:i,data:JSON.stringify(r),timestamp:(new Date).toISOString(),source:"s3db-replicator"}])})}const c=0===o.length;return o.length>0&&console.warn(`[BigqueryReplicator] Replication completed with errors for ${t}:`,o),this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:i,tables:n.map(t=>t.table),results:a,errors:o,success:c}),{success:c,results:a,errors:o,tables:n.map(t=>t.table)}});return c?u:(this.config.verbose&&console.warn(`[BigqueryReplicator] Replication failed for ${t}: ${l.message}`),this.emit("replicator_error",{replicator:this.name,resourceName:t,operation:e,id:i,error:l.message}),{success:!1,error:l.message})}async replicateBatch(t,e){const r=[],i=[];for(const s of e){const[e,n,a]=await wt(()=>this.replicate(t,s.operation,s.data,s.id,s.beforeData));e?r.push(a):(this.config.verbose&&console.warn(`[BigqueryReplicator] Batch replication failed for record ${s.id}: ${n.message}`),i.push({id:s.id,error:n.message}))}return i.length>0&&console.warn(`[BigqueryReplicator] Batch replication completed with ${i.length} error(s) for ${t}:`,i),{success:0===i.length,results:r,errors:i}}async testConnection(){const[t,e]=await wt(async()=>{this.bigqueryClient||await this.initialize();const t=this.bigqueryClient.dataset(this.datasetId);return await t.getMetadata(),!0});return!!t||(this.config.verbose&&console.warn(`[BigqueryReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}async cleanup(){}getStatus(){return{...super.getStatus(),projectId:this.projectId,datasetId:this.datasetId,resources:this.resources,logTable:this.logTable}}};var Li=class extends Ti{constructor(t={},e={}){super(t),this.connectionString=t.connectionString,this.host=t.host,this.port=t.port||5432,this.database=t.database,this.user=t.user,this.password=t.password,this.client=null,this.ssl=t.ssl,this.logTable=t.logTable,this.resources=this.parseResourcesConfig(e)}parseResourcesConfig(t){const e={};for(const[r,i]of Object.entries(t))"string"==typeof i?e[r]=[{table:i,actions:["insert"]}]:Array.isArray(i)?e[r]=i.map(t=>"string"==typeof t?{table:t,actions:["insert"]}:{table:t.table,actions:t.actions||["insert"]}):"object"==typeof i&&(e[r]=[{table:i.table,actions:i.actions||["insert"]}]);return e}validateConfig(){const t=[];this.connectionString||this.host&&this.database||t.push("Either connectionString or host+database must be provided"),0===Object.keys(this.resources).length&&t.push("At least one resource must be configured");for(const[e,r]of Object.entries(this.resources))for(const i of r){i.table||t.push(`Table name is required for resource '${e}'`),Array.isArray(i.actions)&&0!==i.actions.length||t.push(`Actions array is required for resource '${e}'`);const r=["insert","update","delete"],s=i.actions.filter(t=>!r.includes(t));s.length>0&&t.push(`Invalid actions for resource '${e}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);const[e,r,i]=await wt(()=>import("pg"));if(!e)throw this.config.verbose&&console.warn(`[PostgresReplicator] Failed to import pg SDK: ${r.message}`),this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{Client:s}=i,n=this.connectionString?{connectionString:this.connectionString,ssl:this.ssl}:{host:this.host,port:this.port,database:this.database,user:this.user,password:this.password,ssl:this.ssl};this.client=new s(n),await this.client.connect(),this.logTable&&await this.createLogTableIfNotExists(),this.emit("initialized",{replicator:this.name,database:this.database||"postgres",resources:Object.keys(this.resources)})}async createLogTableIfNotExists(){const t=`\n CREATE TABLE IF NOT EXISTS ${this.logTable} (\n id SERIAL PRIMARY KEY,\n resource_name VARCHAR(255) NOT NULL,\n operation VARCHAR(50) NOT NULL,\n record_id VARCHAR(255) NOT NULL,\n data JSONB,\n timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n source VARCHAR(100) DEFAULT 's3db-replicator',\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n );\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_resource_name ON ${this.logTable}(resource_name);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_operation ON ${this.logTable}(operation);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_record_id ON ${this.logTable}(record_id);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_timestamp ON ${this.logTable}(timestamp);\n `;await this.client.query(t)}shouldReplicateResource(t){return this.resources.hasOwnProperty(t)}shouldReplicateAction(t,e){return!!this.resources[t]&&this.resources[t].some(t=>t.actions.includes(e))}getTablesForResource(t,e){return this.resources[t]?this.resources[t].filter(t=>t.actions.includes(e)).map(t=>t.table):[]}async replicate(t,e,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(t,e))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(t,e);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const a=[],o=[],[c,l,u]=await wt(async()=>{for(const t of n){const[s,n]=await wt(async()=>{let s;if("insert"===e){const e=this._cleanInternalFields(r),i=Object.keys(e),n=i.map(t=>e[t]),a=i.map(t=>`"${t}"`).join(", "),o=i.map((t,e)=>`$${e+1}`).join(", "),c=`INSERT INTO ${t} (${a}) VALUES (${o}) ON CONFLICT (id) DO NOTHING RETURNING *`;s=await this.client.query(c,n)}else if("update"===e){const e=this._cleanInternalFields(r),n=Object.keys(e).filter(t=>"id"!==t),a=n.map((t,e)=>`"${t}"=$${e+1}`).join(", "),o=n.map(t=>e[t]);o.push(i);const c=`UPDATE ${t} SET ${a} WHERE id=$${n.length+1} RETURNING *`;s=await this.client.query(c,o)}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const e=`DELETE FROM ${t} WHERE id=$1 RETURNING *`;s=await this.client.query(e,[i])}}a.push({table:t,success:!0,rows:s.rows,rowCount:s.rowCount})});s||o.push({table:t,error:n.message})}if(this.logTable){const[s,n]=await wt(async()=>{await this.client.query(`INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,[t,e,i,JSON.stringify(r),(new Date).toISOString(),"s3db-replicator"])})}const s=0===o.length;return o.length>0&&console.warn(`[PostgresReplicator] Replication completed with errors for ${t}:`,o),this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:i,tables:n,results:a,errors:o,success:s}),{success:s,results:a,errors:o,tables:n}});return c?u:(this.config.verbose&&console.warn(`[PostgresReplicator] Replication failed for ${t}: ${l.message}`),this.emit("replicator_error",{replicator:this.name,resourceName:t,operation:e,id:i,error:l.message}),{success:!1,error:l.message})}async replicateBatch(t,e){const r=[],i=[];for(const s of e){const[e,n,a]=await wt(()=>this.replicate(t,s.operation,s.data,s.id,s.beforeData));e?r.push(a):(this.config.verbose&&console.warn(`[PostgresReplicator] Batch replication failed for record ${s.id}: ${n.message}`),i.push({id:s.id,error:n.message}))}return i.length>0&&console.warn(`[PostgresReplicator] Batch replication completed with ${i.length} error(s) for ${t}:`,i),{success:0===i.length,results:r,errors:i}}async testConnection(){const[t,e]=await wt(async()=>(this.client||await this.initialize(),await this.client.query("SELECT 1"),!0));return!!t||(this.config.verbose&&console.warn(`[PostgresReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}async cleanup(){this.client&&await this.client.end()}getStatus(){return{...super.getStatus(),database:this.database||"postgres",resources:this.resources,logTable:this.logTable}}};class Ui{constructor(t){let e;const[r,i,s]=wt(()=>new URL(t));if(!r)throw new ft("Invalid connection string: "+t,{original:i,input:t});e=s,this.region="us-east-1","s3:"===e.protocol?this.defineFromS3(e):this.defineFromCustomUri(e);for(const[t,r]of e.searchParams.entries())this[t]=r}defineFromS3(t){const[e,r,i]=bt(()=>decodeURIComponent(t.hostname));if(!e)throw new ft("Invalid bucket in connection string",{original:r,input:t.hostname});this.bucket=i||"s3db";const[s,n,a]=bt(()=>decodeURIComponent(t.username));if(!s)throw new ft("Invalid accessKeyId in connection string",{original:n,input:t.username});this.accessKeyId=a;const[o,c,l]=bt(()=>decodeURIComponent(t.password));if(!o)throw new ft("Invalid secretAccessKey in connection string",{original:c,input:t.password});if(this.secretAccessKey=l,this.endpoint="https://s3.us-east-1.amazonaws.com",["/","",null].includes(t.pathname))this.keyPrefix="";else{let[,...e]=t.pathname.split("/");this.keyPrefix=[...e||[]].join("/")}}defineFromCustomUri(t){this.forcePathStyle=!0,this.endpoint=t.origin;const[e,r,i]=bt(()=>decodeURIComponent(t.username));if(!e)throw new ft("Invalid accessKeyId in connection string",{original:r,input:t.username});this.accessKeyId=i;const[s,n,a]=bt(()=>decodeURIComponent(t.password));if(!s)throw new ft("Invalid secretAccessKey in connection string",{original:n,input:t.password});if(this.secretAccessKey=a,["/","",null].includes(t.pathname))this.bucket="s3db",this.keyPrefix="";else{let[,e,...r]=t.pathname.split("/");if(e){const[t,r,i]=bt(()=>decodeURIComponent(e));if(!t)throw new ft("Invalid bucket in connection string",{original:r,input:e});this.bucket=i}else this.bucket="s3db";this.keyPrefix=[...r||[]].join("/")}}}class Fi extends At{constructor({verbose:t=!1,id:e=null,AwsS3Client:r,connectionString:i,parallelism:s=10}){super(),this.verbose=t,this.id=e??jt(),this.parallelism=s,this.config=new Ui(i),this.client=r||this.createClient()}createClient(){let t={region:this.config.region,endpoint:this.config.endpoint};this.config.forcePathStyle&&(t.forcePathStyle=!0),this.config.accessKeyId&&(t.credentials={accessKeyId:this.config.accessKeyId,secretAccessKey:this.config.secretAccessKey});const e=new R(t);return e.middlewareStack.add((t,e)=>async r=>{if("DeleteObjectsCommand"===e.commandName){const t=r.request.body;if(t&&"string"==typeof t){const e=await Ot(t);r.request.headers["Content-MD5"]=e}}return t(r)},{step:"build",name:"addContentMd5ForDeleteObjects",priority:"high"}),e}async sendCommand(t){this.emit("command.request",t.constructor.name,t.input);const[e,r,i]=await wt(()=>this.client.send(t));if(!e){throw ht(r,{bucket:this.config.bucket,key:t.input&&t.input.Key,commandName:t.constructor.name,commandInput:t.input})}return this.emit("command.response",t.constructor.name,i,t.input),i}async putObject({key:t,metadata:e,contentType:r,body:i,contentEncoding:s,contentLength:n}){const a="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";a&&Wt.join(a,t);const o={};if(e)for(const[t,r]of Object.entries(e)){o[String(t).replace(/[^a-zA-Z0-9\-_]/g,"_")]=String(r)}const c={Bucket:this.config.bucket,Key:a?Wt.join(a,t):t,Metadata:o,Body:i||Buffer.alloc(0)};let l,u;void 0!==r&&(c.ContentType=r),void 0!==s&&(c.ContentEncoding=s),void 0!==n&&(c.ContentLength=n);try{return l=await this.sendCommand(new j(c)),l}catch(e){throw u=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"PutObjectCommand",commandInput:c})}finally{this.emit("putObject",u||l,{key:t,metadata:e,contentType:r,body:i,contentEncoding:s,contentLength:n})}}async getObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?Wt.join(e,t):t};let i,s;try{return i=await this.sendCommand(new x(r)),i}catch(e){throw s=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"GetObjectCommand",commandInput:r})}finally{this.emit("getObject",s||i,{key:t})}}async headObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?Wt.join(e,t):t};let i,s;try{return i=await this.sendCommand(new E(r)),i}catch(e){throw s=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"HeadObjectCommand",commandInput:r})}finally{this.emit("headObject",s||i,{key:t})}}async copyObject({from:t,to:e}){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?Wt.join(this.config.keyPrefix,e):e,CopySource:Wt.join(this.config.bucket,this.config.keyPrefix?Wt.join(this.config.keyPrefix,t):t)};let i,s;try{return i=await this.sendCommand(new D(r)),i}catch(t){throw s=t,ht(t,{bucket:this.config.bucket,key:e,commandName:"CopyObjectCommand",commandInput:r})}finally{this.emit("copyObject",s||i,{from:t,to:e})}}async exists(t){const[e,r]=await wt(()=>this.headObject(t));if(e)return!0;if("NoSuchKey"===r.name||"NotFound"===r.name)return!1;throw r}async deleteObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";e&&Wt.join(e,t);const r={Bucket:this.config.bucket,Key:e?Wt.join(e,t):t};let i,s;try{return i=await this.sendCommand(new A(r)),i}catch(e){throw s=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"DeleteObjectCommand",commandInput:r})}finally{this.emit("deleteObject",s||i,{key:t})}}async deleteObjects(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r=d(t,1e3),{results:s,errors:n}=await i.for(r).withConcurrency(this.parallelism).process(async t=>{for(const r of t)e&&Wt.join(e,r),this.config.bucket,await this.exists(r);const r={Bucket:this.config.bucket,Delete:{Objects:t.map(t=>({Key:e?Wt.join(e,t):t}))}};let i;const[s,n,a]=await wt(()=>this.sendCommand(new N(r)));if(!s)throw n;return i=a,i&&i.Errors&&i.Errors.length,i&&i.Deleted&&(i.Deleted.length,t.length),i}),a={deleted:s,notFound:n};return this.emit("deleteObjects",a,t),a}async deleteAll({prefix:t}={}){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,i=0;do{const s=new I({Bucket:this.config.bucket,Prefix:e?Wt.join(e,t||""):t||"",ContinuationToken:r}),n=await this.client.send(s);if(n.Contents&&n.Contents.length>0){const e=new N({Bucket:this.config.bucket,Delete:{Objects:n.Contents.map(t=>({Key:t.Key}))}}),r=await this.client.send(e),s=r.Deleted?r.Deleted.length:0;i+=s,this.emit("deleteAll",{prefix:t,batch:s,total:i})}r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:t,totalDeleted:i}),i}async moveObject({from:t,to:e}){const[r,i]=await wt(async()=>{await this.copyObject({from:t,to:e}),await this.deleteObject(t)});if(!r)throw new lt("Unknown error in moveObject",{bucket:this.config.bucket,from:t,to:e,original:i});return!0}async listObjects({prefix:t,maxKeys:e=1e3,continuationToken:r}={}){const i={Bucket:this.config.bucket,MaxKeys:e,ContinuationToken:r,Prefix:this.config.keyPrefix?Wt.join(this.config.keyPrefix,t||""):t||""},[s,n,a]=await wt(()=>this.sendCommand(new I(i)));if(!s)throw new lt("Unknown error in listObjects",{prefix:t,bucket:this.config.bucket,original:n});return this.emit("listObjects",a,i),a}async count({prefix:t}={}){let e,r=0,i=!0;for(;i;){const s={prefix:t,continuationToken:e},n=await this.listObjects(s);r+=n.KeyCount||0,i=n.IsTruncated||!1,e=n.NextContinuationToken}return this.emit("count",r,{prefix:t}),r}async getAllKeys({prefix:t}={}){let e,r=[],i=!0;for(;i;){const s={prefix:t,continuationToken:e},n=await this.listObjects(s);n.Contents&&(r=r.concat(n.Contents.map(t=>t.Key))),i=n.IsTruncated||!1,e=n.NextContinuationToken}return this.config.keyPrefix&&(r=r.map(t=>t.replace(this.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t)),this.emit("getAllKeys",r,{prefix:t}),r}async getContinuationTokenAfterOffset(t={}){const{prefix:e,offset:r=1e3}=t;if(0===r)return null;let i,s=!0,n=0;for(;s;){const t={prefix:e,maxKeys:r<1e3?r:r-n>1e3?1e3:r-n,continuationToken:i},a=await this.listObjects(t);if(a.Contents&&(n+=a.Contents.length),s=a.IsTruncated||!1,i=a.NextContinuationToken,n>=r)break}return this.emit("getContinuationTokenAfterOffset",i||null,t),i||null}async getKeysPage(t={}){const{prefix:e,offset:r=0,amount:i=100}=t;let s,n=[],a=!0;if(r>0&&(s=await this.getContinuationTokenAfterOffset({prefix:e,offset:r}),!s))return this.emit("getKeysPage",[],t),[];for(;a;){const t={prefix:e,continuationToken:s},r=await this.listObjects(t);if(r.Contents&&(n=n.concat(r.Contents.map(t=>t.Key))),a=r.IsTruncated||!1,s=r.NextContinuationToken,n.length>=i){n=n.slice(0,i);break}}return this.config.keyPrefix&&(n=n.map(t=>t.replace(this.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t)),this.emit("getKeysPage",n,t),n}async moveAllObjects({prefixFrom:t,prefixTo:e}){const r=await this.getAllKeys({prefix:t}),{results:s,errors:n}=await i.for(r).withConcurrency(this.parallelism).process(async r=>{const i=r.replace(t,e),[s,n]=await wt(async()=>{await this.moveObject({from:r,to:i})});if(!s)throw new lt("Unknown error in moveAllObjects",{bucket:this.config.bucket,from:r,to:i,original:n});return i});if(this.emit("moveAllObjects",{results:s,errors:n},{prefixFrom:t,prefixTo:e}),n.length>0)throw new Error("Some objects could not be moved");return s}}var qi=Fi;async function Bi(t,e,r){if(!this.passphrase)return e.push(new Z("Missing configuration for secrets encryption.",{actual:t,type:"encryptionKeyMissing",suggestion:"Provide a passphrase for secret encryption."})),t;const[i,s,n]=await wt(()=>_t(String(t),this.passphrase));return i?n:(e.push(new Z("Problem encrypting secret.",{actual:t,type:"encryptionProblem",error:s,suggestion:"Check the passphrase and input value."})),t)}async function zi(t,e,r){if(g(t))return t;const[i,s,n]=bt(()=>JSON.stringify(t));if(!i)throw new Z("Failed to stringify JSON",{original:s,input:t});return n}class Vi extends C{constructor({options:t,passphrase:e,autoEncrypt:r=!0}={}){super(p({},{useNewCustomCheckerFunction:!0,messages:{encryptionKeyMissing:"Missing configuration for secrets encryption.",encryptionProblem:"Problem encrypting secret. Actual: {actual}. Error: {error}"},defaults:{string:{trim:!0},object:{strict:"remove"},number:{convert:!0}}},t)),this.passphrase=e,this.autoEncrypt=r,this.alias("secret",{type:"string",custom:this.autoEncrypt?Bi:void 0,messages:{string:"The '{field}' field must be a string.",stringMin:"This secret '{field}' field length must be at least {expected} long."}}),this.alias("secretAny",{type:"any",custom:this.autoEncrypt?Bi:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Bi:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?zi:void 0})}}const Ki=new Proxy(Vi,{instance:null,construct(t,e){return this.instance||(this.instance=new t(...e)),this.instance}});const Wi={trim:t=>null==t?t:t.trim(),encrypt:async(t,{passphrase:e})=>{if(null==t)return t;const[r,i,s]=await yt(()=>_t(t,e));return r?s:t},decrypt:async(t,{passphrase:e})=>{if(null==t)return t;const[r,i,s]=await yt(()=>kt(t,e));return r?"null"===s?null:"undefined"!==s?s:void 0:t},toString:t=>null==t?t:String(t),fromArray:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>"string"==typeof t?t.replace(/\\/g,"\\\\").replace(new RegExp(`\\${e}`,"g"),`\\${e}`):String(t)).join(e)},toArray:(t,{separator:e})=>{if(Array.isArray(t))return t;if(null==t)return t;if(""===t)return[];const r=[];let i="",s=0;const n=String(t);for(;s<n.length;)"\\"===n[s]&&s+1<n.length?(i+=n[s+1],s+=2):n[s]===e?(r.push(i),i="",s++):(i+=n[s],s++);return r.push(i),r},toJSON:t=>{if(null===t)return null;if(void 0===t)return;if("string"==typeof t){const[e,r,i]=bt(()=>JSON.parse(t));return t}const[e,r,i]=bt(()=>JSON.stringify(t));return e?i:t},fromJSON:t=>{if(null===t)return null;if(void 0===t)return;if("string"!=typeof t)return t;if(""===t)return"";const[e,r,i]=bt(()=>JSON.parse(t));return e?i:t},toNumber:t=>g(t)?t.includes(".")?parseFloat(t):parseInt(t):t,toBool:t=>[!0,1,"true","1","yes","y"].includes(t),fromBool:t=>[!0,1,"true","1","yes","y"].includes(t)?"1":"0",fromBase62:t=>{if(null==t||""===t)return t;if("number"==typeof t)return t;if("string"==typeof t){const e=U(t);return isNaN(e)?void 0:e}},toBase62:t=>{if(null==t||""===t)return t;if("number"==typeof t)return L(t);if("string"==typeof t){const e=Number(t);return isNaN(e)?t:L(e)}return t},fromBase62Decimal:t=>{if(null==t||""===t)return t;if("number"==typeof t)return t;if("string"==typeof t){const e=q(t);return isNaN(e)?void 0:e}},toBase62Decimal:t=>{if(null==t||""===t)return t;if("number"==typeof t)return F(t);if("string"==typeof t){const e=Number(t);return isNaN(e)?t:F(e)}return t},fromArrayOfNumbers:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>{if("number"==typeof t&&!isNaN(t))return L(t);const e=Number(t);return isNaN(e)?"":L(e)}).join(e)},toArrayOfNumbers:(t,{separator:e})=>{if(Array.isArray(t))return t.map(t=>"number"==typeof t?t:U(t));if(null==t)return t;if(""===t)return[];const r=String(t),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===e?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(t=>{if("number"==typeof t)return t;if("string"==typeof t&&""!==t){const e=U(t);return isNaN(e)?NaN:e}return NaN})},fromArrayOfDecimals:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>{if("number"==typeof t&&!isNaN(t))return F(t);const e=Number(t);return isNaN(e)?"":F(e)}).join(e)},toArrayOfDecimals:(t,{separator:e})=>{if(Array.isArray(t))return t.map(t=>"number"==typeof t?t:q(t));if(null==t)return t;if(""===t)return[];const r=String(t),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===e?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(t=>{if("number"==typeof t)return t;if("string"==typeof t&&""!==t){const e=q(t);return isNaN(e)?NaN:e}return NaN})}};class Ji{constructor(t){const{map:e,name:r,attributes:i,passphrase:s,version:n=1,options:a={}}=t;this.name=r,this.version=n,this.attributes=i||{},this.passphrase=s??"secret",this.options=p({},this.defaultOptions(),a),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const o=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new Ki({autoEncrypt:!1}).compile(p({$$async:!0},o)),this.options.generateAutoHooks&&this.generateAutoHooks(),m(e)){const t=$(this.attributes,{safe:!0}),e=Object.keys(t).filter(t=>!t.includes("$$")),r=this.extractObjectKeys(this.attributes),i=[...new Set([...e,...r])],{mapping:s,reversedMapping:n}=function(t){const e={},r={};return t.forEach((t,i)=>{const s=L(i);e[t]=s,r[s]=t}),{mapping:e,reversedMapping:r}}(i);this.map=s,this.reversedMap=n}else this.map=e,this.reversedMap=y(e)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(t,e,r){this.options.hooks[t][e]||(this.options.hooks[t][e]=[]),this.options.hooks[t][e]=b([...this.options.hooks[t][e],r])}extractObjectKeys(t,e=""){const r=[];for(const[i,s]of Object.entries(t)){if(i.startsWith("$$"))continue;const t=e?`${e}.${i}`:i;"object"!=typeof s||null===s||Array.isArray(s)||(r.push(t),"object"===s.$$type&&r.push(...this.extractObjectKeys(s,t)))}return r}generateAutoHooks(){const t=$(w(this.attributes),{safe:!0});for(const[e,r]of Object.entries(t))if(r.includes("array")){if(r.includes("items:string"))this.addHook("beforeMap",e,"fromArray"),this.addHook("afterUnmap",e,"toArray");else if(r.includes("items:number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",e,"fromArrayOfNumbers"),this.addHook("afterUnmap",e,"toArrayOfNumbers")):(this.addHook("beforeMap",e,"fromArrayOfDecimals"),this.addHook("afterUnmap",e,"toArrayOfDecimals"))}}else if(r.includes("secret"))this.options.autoEncrypt&&this.addHook("beforeMap",e,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",e,"decrypt");else{if(r.includes("number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",e,"toBase62"),this.addHook("afterUnmap",e,"fromBase62")):(this.addHook("beforeMap",e,"toBase62Decimal"),this.addHook("afterUnmap",e,"fromBase62Decimal"));continue}r.includes("boolean")?(this.addHook("beforeMap",e,"fromBool"),this.addHook("afterUnmap",e,"toBool")):(r.includes("json")||"object"===r||r.includes("object"))&&(this.addHook("beforeMap",e,"toJSON"),this.addHook("afterUnmap",e,"fromJSON"))}}static import(t){let{map:e,name:r,options:i,version:s,attributes:n}=g(t)?JSON.parse(t):t;const[a,o,c]=bt(()=>Ji._importAttributes(n));if(!a)throw new pt("Failed to import schema attributes",{original:o,input:n});n=c;return new Ji({map:e,name:r,options:i,version:s,attributes:n})}static _importAttributes(t){if("string"==typeof t){const[e,r,i]=bt(()=>JSON.parse(t));if(e&&"object"==typeof i&&null!==i){const[e,r,s]=bt(()=>Ji._importAttributes(i));if(!e)throw new pt("Failed to parse nested schema attribute",{original:r,input:t});return s}return t}if(Array.isArray(t)){const[e,r,i]=bt(()=>t.map(t=>Ji._importAttributes(t)));if(!e)throw new pt("Failed to import array schema attributes",{original:r,input:t});return i}if("object"==typeof t&&null!==t){const e={};for(const[r,i]of Object.entries(t)){const[t,s,n]=bt(()=>Ji._importAttributes(i));if(!t)throw new pt("Failed to import object schema attribute",{original:s,key:r,input:i});e[r]=n}return e}return t}export(){return{version:this.version,name:this.name,options:this.options,attributes:this._exportAttributes(this.attributes),map:this.map}}_exportAttributes(t){if("string"==typeof t)return t;if(Array.isArray(t))return t.map(t=>this._exportAttributes(t));if("object"==typeof t&&null!==t){const e={};for(const[r,i]of Object.entries(t))e[r]=this._exportAttributes(i);return e}return t}async applyHooksActions(t,e){const r=w(t);for(const[t,i]of Object.entries(this.options.hooks[e]))for(const e of i){const i=v(r,t);void 0!==i&&"function"==typeof Wi[e]&&S(r,t,await Wi[e](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}return r}async validate(t,{mutateOriginal:e=!1}={}){let r=e?t:w(t);return await this.validator(r)}async mapper(t){let e=w(t);e=await this.applyHooksActions(e,"beforeMap");const r=$(e,{safe:!0}),i={_v:this.version+""};for(const[t,e]of Object.entries(r)){const r=this.map[t]||t,s=this.getAttributeDefinition(t);"number"==typeof e&&"string"==typeof s&&s.includes("number")?i[r]=L(e):"string"==typeof e?"[object Object]"===e?i[r]="{}":(e.startsWith("{")||e.startsWith("["),i[r]=e):Array.isArray(e)||"object"==typeof e&&null!==e?i[r]=JSON.stringify(e):i[r]=e}return await this.applyHooksActions(i,"afterMap"),i}async unmapper(t,e){let r=w(t);delete r._v,r=await this.applyHooksActions(r,"beforeUnmap");const i=e?y(e):this.reversedMap,s={};for(const[t,e]of Object.entries(r)){const r=i&&i[t]?i[t]:t;let n=e;const a=this.getAttributeDefinition(r);if("string"!=typeof a||!a.includes("number")||a.includes("array")||a.includes("decimal")){if("string"==typeof e)if("[object Object]"===e)n={};else if(e.startsWith("{")||e.startsWith("[")){const[t,r,i]=bt(()=>JSON.parse(e));t&&(n=i)}}else"string"==typeof n&&""!==n?n=U(n):"number"==typeof n||(n=void 0);if(this.attributes&&"string"==typeof a&&a.includes("array"))if(Array.isArray(n));else if("string"==typeof n&&n.trim().startsWith("[")){const[t,e,r]=bt(()=>JSON.parse(n));t&&Array.isArray(r)&&(n=r)}else n=Wi.toArray(n,{separator:this.options.arraySeparator});if(this.options.hooks&&this.options.hooks.afterUnmap&&this.options.hooks.afterUnmap[r])for(const t of this.options.hooks.afterUnmap[r])"function"==typeof Wi[t]&&(n=await Wi[t](n,{passphrase:this.passphrase,separator:this.options.arraySeparator}));s[r]=n}await this.applyHooksActions(s,"afterUnmap");const n=P(s);for(const[e,r]of Object.entries(t))e.startsWith("$")&&(n[e]=r);return n}getAttributeDefinition(t){const e=t.split(".");let r=this.attributes;for(const t of e){if(!r)return;r=r[t]}return r}preprocessAttributesForValidation(t){const e={};for(const[r,i]of Object.entries(t))if("object"!=typeof i||null===i||Array.isArray(i))e[r]=i;else{const t=i.$$type&&i.$$type.includes("required"),s=i.$$type&&i.$$type.includes("optional"),n={type:"object",properties:this.preprocessAttributesForValidation(i),strict:!1};t||(s||this.allNestedObjectsOptional)&&(n.optional=!0),e[r]=n}return e}}var Hi=Ji;const Yi=2047;var Gi=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:Yi,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r,originalData:i}){const s=W(r),n=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}});if(s>n)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${s} bytes, effective limit: ${n} bytes, absolute limit: 2047 bytes`);return{mappedData:r,body:JSON.stringify(r)}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){const n=W(i),a=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}});if(n>a)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, effective limit: ${a} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:JSON.stringify(i)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){const s=W(i),n=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}});if(s>n)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${s} bytes, effective limit: ${n} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:""}}});var Qi=Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r,originalData:i}){const s=W(r);return s>Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}})&&t.emit("exceedsLimit",{operation:"insert",totalSize:s,limit:2047,excess:s-2047,data:i||e}),{mappedData:r,body:JSON.stringify(e)}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){const n=W(i);return n>Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}})&&t.emit("exceedsLimit",{operation:"update",id:e,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){const n=W(i);return n>Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}})&&t.emit("exceedsLimit",{operation:"upsert",id:e,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}}});const Xi="$truncated",Zi="true",ts=B(Xi)+B(Zi);async function es({resource:t,data:e,mappedData:r,originalData:i}){const s=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}}),n=K(r),a=Object.entries(n).sort(([,t],[,e])=>t-e),o={};let c=0,l=!1;r._v&&(o._v=r._v,c+=n._v);for(const[t,e]of a){if("_v"===t)continue;const i=r[t];if(!(c+(e+(l?0:ts))<=s)){const e=s-c-(l?0:ts);if(e>0){const r=rs(i,e);o[t]=r,l=!0,c+=B(r)}else o[t]="",l=!0;break}o[t]=i,c+=e}let u=W(o)+(l?ts:0);for(;u>s;){const t=Object.keys(o).filter(t=>"_v"!==t&&"$truncated"!==t);if(0===t.length)break;o[t[t.length-1]]="",u=W(o)+ts,l=!0}return l&&(o[Xi]=Zi),{mappedData:o,body:JSON.stringify(r)}}function rs(t,e){if("string"==typeof t)return is(t,e);if("object"==typeof t&&null!==t){return is(JSON.stringify(t),e)}return is(String(t),e)}function is(t,e){const r=new TextEncoder;let i=r.encode(t);if(i.length<=e)return t;let s=t.length;for(;s>0;){const n=t.substring(0,s);if(i=r.encode(n),i.length<=e)return n;s--}return""}var ss=Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:es,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){return es({resource:t,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return es({resource:t,data:r,mappedData:i})}});const ns="$overflow",as="true",os=B(ns)+B(as);async function cs({resource:t,data:e,mappedData:r,originalData:i}){const s=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}}),n=K(r),a=Object.entries(n).sort(([,t],[,e])=>t-e),o={},c={};let l=0,u=!1;r._v&&(o._v=r._v,l+=n._v);let h=s;for(const[t,e]of a)"_v"!==t&&(!u&&l+e>s&&(h-=os,u=!0),!u&&l+e<=h?(o[t]=r[t],l+=e):(c[t]=r[t],u=!0));u&&(o[ns]=as);const f=Object.keys(c).length>0;let d=f?JSON.stringify(c):"";return f||(d="{}"),{mappedData:o,body:d}}async function ls({resource:t,data:e,mappedData:r}){const i={_v:r._v||String(t.version)};i._map=JSON.stringify(t.schema.map);return{mappedData:i,body:JSON.stringify(r)}}const us={"user-managed":Qi,"enforce-limits":Gi,"truncate-data":ss,"body-overflow":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){let i={};if(r&&""!==r.trim()){const[t,e,s]=bt(()=>JSON.parse(r));i=t?s:{}}const s={...i,...e};return delete s.$overflow,{metadata:s,body:r}},handleInsert:cs,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){return cs({resource:t,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return cs({resource:t,data:r,mappedData:i})}}),"body-only":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){let i={};if(r&&""!==r.trim()){const[t,e,s]=bt(()=>JSON.parse(r));i=t?s:{}}return{metadata:{...i,...e},body:r}},handleInsert:ls,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i}){const s={_v:i._v||String(t.version)};return s._map=JSON.stringify(t.schema.map),{mappedData:s,body:JSON.stringify(i)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return ls({resource:t,data:r,mappedData:i})}})};function hs(t){const e=us[t];if(!e)throw new Error(`Unknown behavior: ${t}. Available behaviors: ${Object.keys(us).join(", ")}`);return e}const fs=Object.keys(us),ds="user-managed";class ps extends At{constructor(t={}){super(),this._instanceId=Math.random().toString(36).slice(2,8);const e=function(t){const e=[];t.name?"string"!=typeof t.name?e.push("Resource 'name' must be a string"):""===t.name.trim()&&e.push("Resource 'name' cannot be empty"):e.push("Resource 'name' is required");t.client||e.push("S3 'client' is required");t.attributes?"object"!=typeof t.attributes||Array.isArray(t.attributes)?e.push("Resource 'attributes' must be an object"):0===Object.keys(t.attributes).length&&e.push("Resource 'attributes' cannot be empty"):e.push("Resource 'attributes' are required");void 0!==t.version&&"string"!=typeof t.version&&e.push("Resource 'version' must be a string");void 0!==t.behavior&&"string"!=typeof t.behavior&&e.push("Resource 'behavior' must be a string");void 0!==t.passphrase&&"string"!=typeof t.passphrase&&e.push("Resource 'passphrase' must be a string");void 0!==t.parallelism&&("number"==typeof t.parallelism&&Number.isInteger(t.parallelism)?t.parallelism<1&&e.push("Resource 'parallelism' must be greater than 0"):e.push("Resource 'parallelism' must be an integer"));void 0===t.observers||Array.isArray(t.observers)||e.push("Resource 'observers' must be an array");const r=["cache","autoDecrypt","timestamps","paranoid","allNestedObjectsOptional"];for(const i of r)void 0!==t[i]&&"boolean"!=typeof t[i]&&e.push(`Resource '${i}' must be a boolean`);void 0!==t.idGenerator&&("function"!=typeof t.idGenerator&&"number"!=typeof t.idGenerator?e.push("Resource 'idGenerator' must be a function or a number (size)"):"number"==typeof t.idGenerator&&t.idGenerator<=0&&e.push("Resource 'idGenerator' size must be greater than 0"));void 0!==t.idSize&&("number"==typeof t.idSize&&Number.isInteger(t.idSize)?t.idSize<=0&&e.push("Resource 'idSize' must be greater than 0"):e.push("Resource 'idSize' must be an integer"));if(void 0!==t.partitions)if("object"!=typeof t.partitions||Array.isArray(t.partitions))e.push("Resource 'partitions' must be an object");else for(const[r,i]of Object.entries(t.partitions))if("object"!=typeof i||Array.isArray(i))e.push(`Partition '${r}' must be an object`);else if(i.fields)if("object"!=typeof i.fields||Array.isArray(i.fields))e.push(`Partition '${r}.fields' must be an object`);else for(const[t,s]of Object.entries(i.fields))"string"!=typeof s&&e.push(`Partition '${r}.fields.${t}' must be a string`);else e.push(`Partition '${r}' must have a 'fields' property`);if(void 0!==t.hooks)if("object"!=typeof t.hooks||Array.isArray(t.hooks))e.push("Resource 'hooks' must be an object");else{const r=["beforeInsert","afterInsert","beforeUpdate","afterUpdate","beforeDelete","afterDelete"];for(const[i,s]of Object.entries(t.hooks))if(r.includes(i))if(Array.isArray(s))for(let t=0;t<s.length;t++){const e=s[t];if("function"==typeof e);else if("string"==typeof e)continue}else e.push(`Resource 'hooks.${i}' must be an array`);else e.push(`Invalid hook event '${i}'. Valid events: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}(t);if(!e.isValid)throw new gt(`Invalid Resource ${t.name} configuration`,{resourceName:t.name,validation:e.errors,operation:"constructor",suggestion:"Check resource config and attributes."});const{name:r,client:i,version:s="1",attributes:n={},behavior:a=ds,passphrase:o="secret",parallelism:c=10,observers:l=[],cache:u=!1,autoDecrypt:h=!0,timestamps:f=!1,partitions:d={},paranoid:p=!0,allNestedObjectsOptional:g=!0,hooks:m={},idGenerator:y,idSize:b=22,versioningEnabled:w=!1}=t;if(this.name=r,this.client=i,this.version=s,this.behavior=a,this.observers=l,this.parallelism=c,this.passphrase=o??"secret",this.versioningEnabled=w,this.idGenerator=this.configureIdGenerator(y,b),this.config={cache:u,hooks:m,paranoid:p,timestamps:f,partitions:d,autoDecrypt:h,allNestedObjectsOptional:g},this.hooks={beforeInsert:[],afterInsert:[],beforeUpdate:[],afterUpdate:[],beforeDelete:[],afterDelete:[]},this.attributes=n||{},this.map=t.map,this.applyConfiguration({map:this.map}),m)for(const[t,e]of Object.entries(m))if(Array.isArray(e)&&this.hooks[t])for(const r of e)"function"==typeof r&&this.hooks[t].push(r.bind(this));this._initMiddleware()}configureIdGenerator(r,i){return"function"==typeof r?r:"number"==typeof r&&r>0?t(e,r):"number"==typeof i&&i>0&&22!==i?t(e,i):jt}get options(){return{timestamps:this.config.timestamps,partitions:this.config.partitions||{},cache:this.config.cache,autoDecrypt:this.config.autoDecrypt,paranoid:this.config.paranoid,allNestedObjectsOptional:this.config.allNestedObjectsOptional}}export(){const t=this.schema.export();return t.behavior=this.behavior,t.timestamps=this.config.timestamps,t.partitions=this.config.partitions||{},t.paranoid=this.config.paranoid,t.allNestedObjectsOptional=this.config.allNestedObjectsOptional,t.autoDecrypt=this.config.autoDecrypt,t.cache=this.config.cache,t.hooks=this.hooks,t.map=this.map,t}applyConfiguration({map:t}={}){this.config.timestamps&&(this.attributes.createdAt||(this.attributes.createdAt="string|optional"),this.attributes.updatedAt||(this.attributes.updatedAt="string|optional"),this.config.partitions||(this.config.partitions={}),this.config.partitions.byCreatedDate||(this.config.partitions.byCreatedDate={fields:{createdAt:"date|maxlength:10"}}),this.config.partitions.byUpdatedDate||(this.config.partitions.byUpdatedDate={fields:{updatedAt:"date|maxlength:10"}})),this.setupPartitionHooks(),this.versioningEnabled&&(this.config.partitions.byVersion||(this.config.partitions.byVersion={fields:{_v:"string"}})),this.schema=new Hi({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:this.version,options:{autoDecrypt:this.config.autoDecrypt,allNestedObjectsOptional:this.config.allNestedObjectsOptional},map:t||this.map}),this.validatePartitions()}updateAttributes(t){const e=this.attributes;return this.attributes=t,this.applyConfiguration({map:this.schema?.map}),{oldAttributes:e,newAttributes:t}}addHook(t,e){this.hooks[t]&&this.hooks[t].push(e.bind(this))}async executeHooks(t,e){if(!this.hooks[t])return e;let r=e;for(const e of this.hooks[t])r=await e(r);return r}setupPartitionHooks(){if(!this.config.partitions)return;const t=this.config.partitions;0!==Object.keys(t).length&&(this.hooks.afterInsert||(this.hooks.afterInsert=[]),this.hooks.afterInsert.push(async t=>(await this.createPartitionReferences(t),t)),this.hooks.afterDelete||(this.hooks.afterDelete=[]),this.hooks.afterDelete.push(async t=>(await this.deletePartitionReferences(t),t)))}async validate(t){const e={original:w(t),isValid:!1,errors:[]},r=await this.schema.validate(t,{mutateOriginal:!1});return!0===r?e.isValid=!0:e.errors=r,e.data=t,e}validatePartitions(){if(!this.config.partitions)return;const t=this.config.partitions;if(0===Object.keys(t).length)return;const e=Object.keys(this.attributes||{});for(const[r,i]of Object.entries(t))if(i.fields)for(const t of Object.keys(i.fields))if(!this.fieldExistsInAttributes(t))throw new mt(`Partition '${r}' uses field '${t}' which does not exist in resource attributes. Available fields: ${e.join(", ")}.`,{resourceName:this.name,partitionName:r,fieldName:t,availableFields:e,operation:"validatePartitions"})}fieldExistsInAttributes(t){if(t.startsWith("_"))return!0;if(!t.includes("."))return Object.keys(this.attributes||{}).includes(t);const e=t.split(".");let r=this.attributes||{};for(const t of e){if(!r||"object"!=typeof r||!(t in r))return!1;r=r[t]}return!0}applyPartitionRule(t,e){if(null==t)return t;let r=t;if("string"==typeof e&&e.includes("maxlength:")){const t=e.match(/maxlength:(\d+)/);if(t){const e=parseInt(t[1]);"string"==typeof r&&r.length>e&&(r=r.substring(0,e))}}if(e.includes("date"))if(r instanceof Date)r=r.toISOString().split("T")[0];else if("string"==typeof r)if(r.includes("T")&&r.includes("Z"))r=r.split("T")[0];else{const t=new Date(r);isNaN(t.getTime())||(r=t.toISOString().split("T")[0])}return r}getResourceKey(t){return Kt("resource="+this.name,"data",`id=${t}`)}getPartitionKey({partitionName:t,id:e,data:r}){if(!this.config.partitions||!this.config.partitions[t])throw new mt(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"getPartitionKey"});const i=this.config.partitions[t],s=[],n=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of n){const i=this.getNestedFieldValue(r,t),n=this.applyPartitionRule(i,e);if(null==n)return null;s.push(`${t}=${n}`)}if(0===s.length)return null;const a=e||r?.id;return a?Kt(`resource=${this.name}`,`partition=${t}`,...s,`id=${a}`):null}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return;i=i[t]}return i}calculateContentLength(t){return t?Buffer.isBuffer(t)?t.length:"string"==typeof t?Buffer.byteLength(t,"utf8"):"object"==typeof t?Buffer.byteLength(JSON.stringify(t),"utf8"):Buffer.byteLength(String(t),"utf8"):0}async insert({id:t,...e}){if(await this.exists(t))throw new Error(`Resource with id '${t}' already exists`);this.getResourceKey(t||"(auto)"),this.options.timestamps&&(e.createdAt=(new Date).toISOString(),e.updatedAt=(new Date).toISOString());const r={id:t,...this.applyDefaults(e)},i=await this.executeHooks("beforeInsert",r),s=Object.keys(i).filter(t=>!(t in r)||i[t]!==r[t]),n={};for(const t of s)n[t]=i[t];const{errors:a,isValid:o,data:c}=await this.validate(i);if(!o){const t=a&&a.length&&a[0].message?a[0].message:"Insert failed";throw new ct({bucket:this.client.config.bucket,resourceName:this.name,attributes:i,validation:a,message:t})}const{id:l,...u}=c;Object.assign(u,n);const h=l||t||this.idGenerator(),f=await this.schema.mapper(u);f._v=String(this.version);const d=hs(this.behavior),{mappedData:p,body:g}=await d.handleInsert({resource:this,data:u,mappedData:f,originalData:r}),m=p,y=this.getResourceKey(h);let b;if(g&&""!==g){const[t,e]=await wt(()=>Promise.resolve(JSON.parse(g)));t&&(b="application/json")}if("body-only"===this.behavior&&(!g||""===g))throw new Error(`[Resource.insert] Attempt to save object without body! Data: id=${h}, resource=${this.name}`);const[w,v,S]=await wt(()=>this.client.putObject({key:y,body:g,contentType:b,metadata:m}));if(!w){const t=v&&v.message?v.message:"";if(t.includes("metadata headers exceed")||t.includes("Insert failed")){const t=W(m),e=Y({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:h}}),r=t-e;throw v.totalSize=t,v.limit=2047,v.effectiveLimit=e,v.excess=r,new gt("metadata headers exceed",{resourceName:this.name,operation:"insert",id:h,totalSize:t,effectiveLimit:e,excess:r,suggestion:"Reduce metadata size or number of fields."})}throw ht(v,{bucket:this.client.config.bucket,key:y,resourceName:this.name,operation:"insert",id:h})}let _=await this.composeFullObjectFromWrite({id:h,metadata:m,body:g,behavior:this.behavior});const k=await this.executeHooks("afterInsert",_);return this.emit("insert",{..._,$before:{...r},$after:{...k}}),k}async get(t){if(_(t))throw new Error("id cannot be an object");if(m(t))throw new Error("id cannot be empty");const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.getObject(e));if(!r)throw ht(i,{bucket:this.client.config.bucket,key:e,resourceName:this.name,operation:"get",id:t});if(0===s.ContentLength){const r=new Error(`No such key: ${e} [bucket:${this.client.config.bucket}]`);throw r.name="NoSuchKey",ht(r,{bucket:this.client.config.bucket,key:e,resourceName:this.name,operation:"get",id:t})}const n=s.Metadata?._v||this.version,a="string"==typeof n&&n.startsWith("v")?n.slice(1):n,o=await this.getSchemaForVersion(a);let c=await o.unmapper(s.Metadata);const l=hs(this.behavior);let u="";if(s.ContentLength>0){const[t,r,i]=await wt(()=>this.client.getObject(e));u=t?await ji(i.Body):""}const{metadata:h}=await l.handleGet({resource:this,metadata:c,body:u});let f=await this.composeFullObjectFromWrite({id:t,metadata:h,body:u,behavior:this.behavior});f._contentLength=s.ContentLength,f._lastModified=s.LastModified,f._hasContent=s.ContentLength>0,f._mimeType=s.ContentType||null,f._v=a,s.VersionId&&(f._versionId=s.VersionId),s.Expiration&&(f._expiresAt=s.Expiration),f._definitionHash=this.getDefinitionHash(),a!==this.version&&(f=await this.applyVersionMapping(f,a,this.version)),this.emit("get",f);return f}async exists(t){const e=this.getResourceKey(t),[r,i]=await wt(()=>this.client.headObject(e));return r}async update(t,e){if(m(t))throw new Error("id cannot be empty");if(!await this.exists(t))throw new Error(`Resource with id '${t}' does not exist`);const r=await this.get(t),i=w(e);let s=w(r);for(const[t,e]of Object.entries(i))if(t.includes(".")){let r=s;const i=t.split(".");for(let t=0;t<i.length-1;t++)"object"==typeof r[i[t]]&&null!==r[i[t]]||(r[i[t]]={}),r=r[i[t]];r[i[i.length-1]]=w(e)}else"object"!=typeof e||null===e||Array.isArray(e)?s[t]=w(e):s[t]=p({},s[t],e);if(this.config.timestamps){const t=(new Date).toISOString();s.updatedAt=t,s.metadata||(s.metadata={}),s.metadata.updatedAt=t}const n=await this.executeHooks("beforeUpdate",w(s)),a={...r,...n,id:t},{isValid:o,errors:c,data:l}=await this.validate(w(a));if(!o)throw new ct({bucket:this.client.config.bucket,resourceName:this.name,attributes:n,validation:c,message:"validation: "+(c&&c.length?JSON.stringify(c):"unknown")});await this.schema.mapper(l);const u=hs(this.behavior),h=await this.schema.mapper({...r,...n});h._v=String(this.version),await u.handleUpdate({resource:this,id:t,data:{...r,...n},mappedData:h,originalData:{...i,id:t}});const{id:f,...d}=l,g={...r,id:t},y={...d,id:t};await this.handlePartitionReferenceUpdates(g,y);const b=await this.schema.mapper(d);b._v=String(this.version);const v=hs(this.behavior),{mappedData:S,body:_}=await v.handleUpdate({resource:this,id:t,data:d,mappedData:b,originalData:{...i,id:t}}),k=S,O=this.getResourceKey(t);let R,j=_;if(""===_&&"body-overflow"!==this.behavior){const[t,e,r]=await wt(()=>this.client.getObject(O));if(t&&r.ContentLength>0){const t=Buffer.from(await r.Body.transformToByteArray()),e=t.toString(),[i,s]=await wt(()=>Promise.resolve(JSON.parse(e)));i||(j=t,R=r.ContentType)}}let x=R;if(j&&""!==j&&!x){const[t,e]=await wt(()=>Promise.resolve(JSON.parse(j)));t&&(x="application/json")}this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(t,r);const[E,D]=await wt(()=>this.client.putObject({key:O,body:j,contentType:x,metadata:k}));if(!E&&D&&D.message&&D.message.includes("metadata headers exceed")){const e=W(k),r=Y({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:t}}),i=e-r;throw D.totalSize=e,D.limit=2047,D.effectiveLimit=r,D.excess=i,this.emit("exceedsLimit",{operation:"update",totalSize:e,limit:2047,effectiveLimit:r,excess:i,data:d}),new gt("metadata headers exceed",{resourceName:this.name,operation:"update",id:t,totalSize:e,effectiveLimit:r,excess:i,suggestion:"Reduce metadata size or number of fields."})}if(!E)throw ht(D,{bucket:this.client.config.bucket,key:O,resourceName:this.name,operation:"update",id:t});const A=await this.composeFullObjectFromWrite({id:t,metadata:k,body:j,behavior:this.behavior}),N=await this.executeHooks("afterUpdate",A);return this.emit("update",{...A,$before:{...r},$after:{...N}}),N}async delete(t){if(m(t))throw new Error("id cannot be empty");let e,r=null;const[i,s,n]=await wt(()=>this.get(t));i?e=n:(e={id:t},r=s),await this.executeHooks("beforeDelete",e);const a=this.getResourceKey(t),[o,c,l]=await wt(()=>this.client.deleteObject(a));if(this.emit("delete",{...e,$before:{...e},$after:null}),r)throw ht(r,{bucket:this.client.config.bucket,key:a,resourceName:this.name,operation:"delete",id:t});if(!o)throw ht(c,{key:a,resourceName:this.name,operation:"delete",id:t});return await this.executeHooks("afterDelete",e),l}async upsert({id:t,...e}){return await this.exists(t)?this.update(t,e):this.insert({id:t,...e})}async count({partition:t=null,partitionValues:e={}}={}){let r;if(t&&Object.keys(e).length>0){const i=this.config.partitions[t];if(!i)throw new mt(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"count"});const s=[],n=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,r]of n){const i=e[t];if(null!=i){const e=this.applyPartitionRule(i,r);s.push(`${t}=${e}`)}}r=s.length>0?`resource=${this.name}/partition=${t}/${s.join("/")}`:`resource=${this.name}/partition=${t}`}else r=`resource=${this.name}/data`;const i=await this.client.count({prefix:r});return this.emit("count",i),i}async insertMany(t){const{results:e}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,e),this.observers.map(r=>r.emit("error",this.name,t,e))}).process(async t=>await this.insert(t));return this.emit("insertMany",t.length),e}async deleteMany(t){const e=d(t.map(t=>this.getResourceKey(t)),1e3);t.map(t=>this.getResourceKey(t));const{results:r}=await i.for(e).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,e),this.observers.map(r=>r.emit("error",this.name,t,e))}).process(async t=>{const e=await this.client.deleteObjects(t);return t.forEach(t=>{const e=t.split("/").find(t=>t.startsWith("id=")),r=e?e.replace("id=",""):null;r&&(this.emit("deleted",r),this.observers.map(t=>t.emit("deleted",this.name,r)))}),e});return this.emit("deleteMany",t.length),r}async deleteAll(){if(!1!==this.config.paranoid)throw new gt("deleteAll() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAll",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAll."});const t=`resource=${this.name}/data`,e=await this.client.deleteAll({prefix:t});return this.emit("deleteAll",{version:this.version,prefix:t,deletedCount:e}),{deletedCount:e,version:this.version}}async deleteAllData(){if(!1!==this.config.paranoid)throw new gt("deleteAllData() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAllData",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAllData."});const t=`resource=${this.name}`,e=await this.client.deleteAll({prefix:t});return this.emit("deleteAllData",{resource:this.name,prefix:t,deletedCount:e}),{deletedCount:e,resource:this.name}}async listIds({partition:t=null,partitionValues:e={},limit:r,offset:i=0}={}){let s;if(t&&Object.keys(e).length>0){if(!this.config.partitions||!this.config.partitions[t])throw new mt(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"listIds"});const r=this.config.partitions[t],i=[],n=Object.entries(r.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,r]of n){const s=e[t];if(null!=s){const e=this.applyPartitionRule(s,r);i.push(`${t}=${e}`)}}s=i.length>0?`resource=${this.name}/partition=${t}/${i.join("/")}`:`resource=${this.name}/partition=${t}`}else s=`resource=${this.name}/data`;const n=(await this.client.getKeysPage({prefix:s,offset:i,amount:r||1e3})).map(t=>{const e=t.split("/").find(t=>t.startsWith("id="));return e?e.replace("id=",""):null}).filter(Boolean);return this.emit("listIds",n.length),n}async list({partition:t=null,partitionValues:e={},limit:r,offset:i=0}={}){const[s,n,a]=await wt(async()=>t?await this.listPartition({partition:t,partitionValues:e,limit:r,offset:i}):await this.listMain({limit:r,offset:i}));return s?a:this.handleListError(n,{partition:t,partitionValues:e})}async listMain({limit:t,offset:e=0}){const[r,i,s]=await wt(()=>this.listIds({limit:t,offset:e}));if(!r)throw i;const n=await this.processListResults(s,"main");return this.emit("list",{count:n.length,errors:0}),n}async listPartition({partition:t,partitionValues:e,limit:r,offset:i=0}){if(!this.config.partitions?.[t])return this.emit("list",{partition:t,partitionValues:e,count:0,errors:0}),[];const s=this.config.partitions[t],n=this.buildPartitionPrefix(t,s,e),[a,o,c]=await wt(()=>this.client.getAllKeys({prefix:n}));if(!a)throw o;const l=this.extractIdsFromKeys(c).slice(i),u=r?l.slice(0,r):l,h=await this.processPartitionResults(u,t,s,c);return this.emit("list",{partition:t,partitionValues:e,count:h.length,errors:0}),h}buildPartitionPrefix(t,e,r){const i=[],s=Object.entries(e.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of s){const s=r[t];if(null!=s){const r=this.applyPartitionRule(s,e);i.push(`${t}=${r}`)}}return i.length>0?`resource=${this.name}/partition=${t}/${i.join("/")}`:`resource=${this.name}/partition=${t}`}extractIdsFromKeys(t){return t.map(t=>{const e=t.split("/").find(t=>t.startsWith("id="));return e?e.replace("id=",""):null}).filter(Boolean)}async processListResults(t,e="main"){const{results:r,errors:s}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content))}).process(async t=>{const[r,i,s]=await wt(()=>this.get(t));return r?s:this.handleResourceError(i,t,e)});return this.emit("list",{count:r.length,errors:0}),r}async processPartitionResults(t,e,r,s){const n=Object.entries(r.fields).sort(([t],[e])=>t.localeCompare(e)),{results:a,errors:o}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content))}).process(async t=>{const[r,i,a]=await wt(async()=>{const r=this.extractPartitionValuesFromKey(t,s,n);return await this.getFromPartition({id:t,partitionName:e,partitionValues:r})});return r?a:this.handleResourceError(i,t,"partition")});return a.filter(t=>null!==t)}extractPartitionValuesFromKey(t,e,r){const i=e.find(e=>e.includes(`id=${t}`));if(!i)throw new mt(`Partition key not found for ID ${t}`,{resourceName:this.name,id:t,operation:"extractPartitionValuesFromKey"});const s=i.split("/"),n={};for(const[t]of r){const e=s.find(e=>e.startsWith(`${t}=`));if(e){const r=e.replace(`${t}=`,"");n[t]=r}}return n}handleResourceError(t,e,r){if(t.message.includes("Cipher job failed")||t.message.includes("OperationError"))return{id:e,_decryptionFailed:!0,_error:t.message,..."partition"===r&&{_partition:r}};throw t}handleListError(t,{partition:e,partitionValues:r}){return t.message.includes("Partition '")&&t.message.includes("' not found"),this.emit("list",{partition:e,partitionValues:r,count:0,errors:1}),[]}async getMany(t){const{results:e,errors:r}=await i.for(t).withConcurrency(this.client.parallelism).handleError(async(t,e)=>(this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content)),{id:e,_error:t.message,_decryptionFailed:t.message.includes("Cipher job failed")||t.message.includes("OperationError")})).process(async t=>{const[e,r,i]=await wt(()=>this.get(t));if(e)return i;if(r.message.includes("Cipher job failed")||r.message.includes("OperationError"))return{id:t,_decryptionFailed:!0,_error:r.message};throw r});return this.emit("getMany",t.length),e}async getAll(){const[t,e,r]=await wt(()=>this.listIds());if(!t)throw e;const i=[];for(const t of r){const[e,r,s]=await wt(()=>this.get(t));e&&i.push(s)}return i}async page({offset:t=0,size:e=100,partition:r=null,partitionValues:i={},skipCount:s=!1}={}){const[n,a,o]=await wt(async()=>{let n=null,a=null;if(!s){const[t,s,o]=await wt(()=>this.count({partition:r,partitionValues:i}));t?(n=o,a=Math.ceil(n/e)):(n=null,a=null)}const o=Math.floor(t/e);let c=[];if(e<=0)c=[];else{const[s,n,a]=await wt(()=>this.list({partition:r,partitionValues:i,limit:e,offset:t}));c=s?a:[]}const l={items:c,totalItems:n,page:o,pageSize:e,totalPages:a,hasMore:c.length===e&&t+e<(n||1/0),_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:c.length,skipCount:s,hasTotalItems:null!==n}};return this.emit("page",l),l});return n?o:{items:[],totalItems:null,page:Math.floor(t/e),pageSize:e,totalPages:null,_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:0,skipCount:s,hasTotalItems:!1,error:a.message}}}readable(){return new Oi({resource:this}).build()}writable(){return new Ri({resource:this}).build()}async setContent({id:t,buffer:e,contentType:r="application/octet-stream"}){const[i,s,n]=await wt(()=>this.get(t));if(!i||!n)throw new gt(`Resource with id '${t}' not found`,{resourceName:this.name,id:t,operation:"setContent"});const a={...n,_hasContent:!0,_contentLength:e.length,_mimeType:r},o=await this.schema.mapper(a),[c,l]=await wt(()=>this.client.putObject({key:this.getResourceKey(t),metadata:o,body:e,contentType:r}));if(!c)throw l;return this.emit("setContent",{id:t,contentType:r,contentLength:e.length}),a}async content(t){const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.getObject(e));if(!r){if("NoSuchKey"===i.name)return{buffer:null,contentType:null};throw i}const n=Buffer.from(await s.Body.transformToByteArray()),a=s.ContentType||null;return this.emit("content",t,n.length,a),{buffer:n,contentType:a}}async hasContent(t){const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.headObject(e));return!!r&&s.ContentLength>0}async deleteContent(t){const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.headObject(e));if(!r)throw i;const n=s.Metadata||{},[a,o,c]=await wt(()=>this.client.putObject({key:e,body:"",metadata:n}));if(!a)throw o;return this.emit("deleteContent",t),c}getDefinitionHash(){const t={attributes:this.attributes,behavior:this.behavior},e=O(t);return`sha256:${f("sha256").update(e).digest("hex")}`}extractVersionFromKey(t){const e=t.split("/").find(t=>t.startsWith("v="));return e?e.replace("v=",""):null}async getSchemaForVersion(t){if(t===this.version)return this.schema;const[e,r,i]=await wt(()=>Promise.resolve(new Hi({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:t,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})));return e?i:this.schema}async createPartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,i]of Object.entries(e)){const e=this.getPartitionKey({partitionName:r,id:t.id,data:t});if(e){const t={_v:String(this.version)};await this.client.putObject({key:e,metadata:t,body:"",contentType:void 0})}}}async deletePartitionReferences(t){const e=this.config.partitions;if(!e||0===Object.keys(e).length)return;const r=[];for(const[i,s]of Object.entries(e)){const e=this.getPartitionKey({partitionName:i,id:t.id,data:t});e&&r.push(e)}if(r.length>0){const[t,e]=await wt(()=>this.client.deleteObjects(r))}}async query(t={},{limit:e=100,offset:r=0,partition:i=null,partitionValues:s={}}={}){if(0===Object.keys(t).length)return await this.list({partition:i,partitionValues:s,limit:e,offset:r});const n=[];let a=r;const o=Math.min(e,50);for(;n.length<e;){const e=await this.list({partition:i,partitionValues:s,limit:o,offset:a});if(0===e.length)break;const r=e.filter(e=>Object.entries(t).every(([t,r])=>e[t]===r));if(n.push(...r),a+=o,e.length<o)break}return n.slice(0,e)}async handlePartitionReferenceUpdates(t,e){const r=this.config.partitions;if(!r||0===Object.keys(r).length)return;for(const[i,s]of Object.entries(r)){const[r,n]=await wt(()=>this.handlePartitionReferenceUpdate(i,s,t,e))}const i=e.id||t.id;for(const[t,s]of Object.entries(r)){const r=`resource=${this.name}/partition=${t}`;let s=[];const[n,a,o]=await wt(()=>this.client.getAllKeys({prefix:r}));if(!n)continue;s=o;const c=this.getPartitionKey({partitionName:t,id:i,data:e});for(const t of s)if(t.endsWith(`/id=${i}`)&&t!==c){const[e,r]=await wt(()=>this.client.deleteObject(t))}}}async handlePartitionReferenceUpdate(t,e,r,i){const s=i.id||r.id,n=this.getPartitionKey({partitionName:t,id:s,data:r}),a=this.getPartitionKey({partitionName:t,id:s,data:i});if(n!==a){if(n){const[t,e]=await wt(async()=>{await this.client.deleteObject(n)})}if(a){const[t,e]=await wt(async()=>{const t={_v:String(this.version)};await this.client.putObject({key:a,metadata:t,body:"",contentType:void 0})})}}else if(a){const[t,e]=await wt(async()=>{const t={_v:String(this.version)};await this.client.putObject({key:a,metadata:t,body:"",contentType:void 0})})}}async updatePartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,i]of Object.entries(e)){if(!i||!i.fields||"object"!=typeof i.fields)continue;const e=this.getPartitionKey({partitionName:r,id:t.id,data:t});if(e){const t={_v:String(this.version)},[r,i]=await wt(async()=>{await this.client.putObject({key:e,metadata:t,body:"",contentType:void 0})})}}}async getFromPartition({id:t,partitionName:e,partitionValues:r={}}){if(!this.config.partitions||!this.config.partitions[e])throw new mt(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"getFromPartition"});const i=this.config.partitions[e],s=[],n=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of n){const i=r[t];if(null!=i){const r=this.applyPartitionRule(i,e);s.push(`${t}=${r}`)}}if(0===s.length)throw new mt(`No partition values provided for partition '${e}'`,{resourceName:this.name,partitionName:e,operation:"getFromPartition"});const a=Kt(`resource=${this.name}`,`partition=${e}`,...s,`id=${t}`),[o,c]=await wt(async()=>{await this.client.headObject(a)});if(!o)throw new gt(`Resource with id '${t}' not found in partition '${e}'`,{resourceName:this.name,id:t,partitionName:e,operation:"getFromPartition"});const l=await this.get(t);return l._partition=e,l._partitionValues=r,this.emit("getFromPartition",l),l}async createHistoricalVersion(t,e){const r=Kt(`resource=${this.name}`,"historical",`id=${t}`),i={...e,_v:e._v||this.version,_historicalTimestamp:(new Date).toISOString()},s=await this.schema.mapper(i),n=hs(this.behavior),{mappedData:a,body:o}=await n.handleInsert({resource:this,data:i,mappedData:s}),c={...a,_v:e._v||this.version,_historicalTimestamp:i._historicalTimestamp};let l;if(o&&""!==o){const[t,e]=await wt(()=>Promise.resolve(JSON.parse(o)));t&&(l="application/json")}await this.client.putObject({key:r,metadata:c,body:o,contentType:l})}async applyVersionMapping(t,e,r){if(e===r)return t;return{...t,_v:r,_originalVersion:e,_versionMapped:!0}}async composeFullObjectFromWrite({id:t,metadata:e,body:r,behavior:i}){const s={};e&&"true"===e.$truncated&&(s.$truncated="true"),e&&"true"===e.$overflow&&(s.$overflow="true");let n={};const[a,o,c]=await wt(()=>this.schema.unmapper(e));n=a?c:e;const l=t=>{if(!t||"object"!=typeof t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||(e[r]=i);return e},u=t=>{if("object"==typeof t&&null!==t)return t;if("string"==typeof t){if("[object Object]"===t)return{};if(t.startsWith("{")||t.startsWith("[")){const[e,r,i]=bt(()=>JSON.parse(t));return e?i:t}return t}return t};if("body-overflow"===i){const i=e&&"true"===e.$overflow;let s={};if(i&&r){const[t,e,i]=await wt(()=>Promise.resolve(JSON.parse(r)));if(t){const[t,e,r]=await wt(()=>this.schema.unmapper(i));s=t?r:{}}}const a={...n,...s,id:t};Object.keys(a).forEach(t=>{a[t]=u(a[t])});const o=l(a);return i&&(o.$overflow="true"),o}if("body-only"===i){const[i,s,n]=await wt(()=>Promise.resolve(r?JSON.parse(r):{}));let a=this.schema.map;if(e&&e._map){const[t,r,i]=await wt(()=>Promise.resolve("string"==typeof e._map?JSON.parse(e._map):e._map));a=t?i:this.schema.map}const[o,c,l]=await wt(()=>this.schema.unmapper(n,a)),h=o?{...l,id:t}:{id:t};return Object.keys(h).forEach(t=>{h[t]=u(h[t])}),h}const h={...n,id:t};Object.keys(h).forEach(t=>{h[t]=u(h[t])});const f=l(h);return s.$truncated&&(f.$truncated=s.$truncated),s.$overflow&&(f.$overflow=s.$overflow),f}emit(t,...e){return super.emit(t,...e)}async replace(t,e){await this.delete(t),await new Promise(t=>setTimeout(t,100));const r=Date.now();for(;Date.now()-r<5e3;){if(!await this.exists(t))break;await new Promise(t=>setTimeout(t,50))}try{return await this.insert({...e,id:t})}catch(r){if(r&&r.message&&r.message.includes("already exists")){return await this.update(t,e)}throw r}}_initMiddleware(){this._middlewares=new Map,this._middlewareMethods=["get","list","listIds","getAll","count","page","insert","update","delete","deleteMany","exists","getMany"];for(const t of this._middlewareMethods)this._middlewares.set(t,[]),this[`_original_${t}`]||(this[`_original_${t}`]=this[t].bind(this),this[t]=async(...e)=>{const r={resource:this,args:e,method:t};let i=-1;const s=this._middlewares.get(t),n=async e=>{if(e<=i)throw new Error("next() called multiple times");return i=e,e<s.length?await s[e](r,()=>n(e+1)):await this[`_original_${t}`](...r.args)};return await n(0)})}useMiddleware(t,e){if(this._middlewares||this._initMiddleware(),!this._middlewares.has(t))throw new gt(`No such method for middleware: ${t}`,{operation:"useMiddleware",method:t});this._middlewares.get(t).push(e)}applyDefaults(t){const e={...t};for(const[t,r]of Object.entries(this.attributes))if(void 0===e[t]&&"string"==typeof r&&r.includes("default:")){const i=r.match(/default:([^|]+)/);if(i){let s=i[1];r.includes("boolean")?s="true"===s:r.includes("number")&&(s=Number(s)),e[t]=s}}return e}}var gs=ps;class ms extends At{constructor(t){super(),this.version="1",this.s3dbVersion=(()=>{const[t,e,r]=wt(()=>"7.3.8");return t?r:"latest"})(),this.resources={},this.savedMetadata=null,this.options=t,this.verbose=t.verbose||!1,this.parallelism=parseInt(t.parallelism+"")||10,this.plugins=t.plugins||[],this.pluginList=t.plugins||[],this.cache=t.cache,this.passphrase=t.passphrase||"secret",this.versioningEnabled=t.versioningEnabled||!1;let e=t.connectionString;if(!e&&(t.bucket||t.accessKeyId||t.secretAccessKey)){const{bucket:r,region:i,accessKeyId:s,secretAccessKey:n,endpoint:a,forcePathStyle:o}=t;if(a){const t=new URL(a);s&&(t.username=encodeURIComponent(s)),n&&(t.password=encodeURIComponent(n)),t.pathname=`/${r||"s3db"}`,o&&t.searchParams.set("forcePathStyle","true"),e=t.toString()}else if(s&&n){const t=new URLSearchParams;t.set("region",i||"us-east-1"),o&&t.set("forcePathStyle","true"),e=`s3://${encodeURIComponent(s)}:${encodeURIComponent(n)}@${r||"s3db"}?${t.toString()}`}}this.client=t.client||new qi({verbose:this.verbose,parallelism:this.parallelism,connectionString:e}),this.bucket=this.client.bucket,this.keyPrefix=this.client.keyPrefix,this._exitListenerRegistered||(this._exitListenerRegistered=!0,"undefined"!=typeof process&&process.on("exit",async()=>{if(this.isConnected())try{await this.disconnect()}catch(t){}}))}async connect(){await this.startPlugins();let t=null;if(await this.client.exists("s3db.json")){const e=await this.client.getObject("s3db.json");t=JSON.parse(await ji(e?.Body))}else t=this.blankMetadataStructure(),await this.uploadMetadataFile();this.savedMetadata=t;const e=this.detectDefinitionChanges(t);for(const[e,r]of Object.entries(t.resources||{})){const t=r.currentVersion||"v0",i=r.versions?.[t];i&&(this.resources[e]=new gs({name:e,client:this.client,database:this,version:t,attributes:i.attributes,behavior:i.behavior||"user-managed",parallelism:this.parallelism,passphrase:this.passphrase,observers:[this],cache:this.cache,timestamps:void 0!==i.timestamps&&i.timestamps,partitions:r.partitions||i.partitions||{},paranoid:void 0===i.paranoid||i.paranoid,allNestedObjectsOptional:void 0===i.allNestedObjectsOptional||i.allNestedObjectsOptional,autoDecrypt:void 0===i.autoDecrypt||i.autoDecrypt,hooks:i.hooks||{},versioningEnabled:this.versioningEnabled,map:i.map}))}e.length>0&&this.emit("resourceDefinitionsChanged",{changes:e,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(t){const e=[];for(const[r,i]of Object.entries(this.resources)){const s=this.generateDefinitionHash(i.export()),n=t.resources?.[r];if(n){const t=n.currentVersion||"v0",i=n.versions?.[t],a=i?.hash;a!==s&&e.push({type:"changed",resourceName:r,currentHash:s,savedHash:a,fromVersion:t,toVersion:this.getNextVersion(n.versions)})}else e.push({type:"new",resourceName:r,currentHash:s,savedHash:null})}for(const[r,i]of Object.entries(t.resources||{}))if(!this.resources[r]){const t=i.currentVersion||"v0",s=i.versions?.[t];e.push({type:"deleted",resourceName:r,currentHash:null,savedHash:s?.hash,deletedVersion:t})}return e}generateDefinitionHash(t,e=void 0){const r={...t.attributes};t.timestamps&&(delete r.createdAt,delete r.updatedAt);const i={attributes:r,behavior:e||t.behavior||"user-managed",partitions:t.partitions||{}},s=O(i);return`sha256:${f("sha256").update(s).digest("hex")}`}getNextVersion(t={}){const e=Object.keys(t).filter(t=>t.startsWith("v")).map(t=>parseInt(t.substring(1))).filter(t=>!isNaN(t));return`v${(e.length>0?Math.max(...e):-1)+1}`}async startPlugins(){const t=this;if(!m(this.pluginList)){const e=this.pluginList.map(t=>k(t)?new t(this):t),r=e.map(async e=>{e.beforeSetup&&await e.beforeSetup(),await e.setup(t),e.afterSetup&&await e.afterSetup()});await Promise.all(r);const i=e.map(async t=>{t.beforeStart&&await t.beforeStart(),await t.start(),t.afterStart&&await t.afterStart()});await Promise.all(i)}}async usePlugin(t,e=null){const r=e||t.constructor.name.replace("Plugin","").toLowerCase();return this.plugins[r]=t,this.isConnected()&&(await t.setup(this),await t.start()),t}async uploadMetadataFile(){const t={version:this.version,s3dbVersion:this.s3dbVersion,lastUpdated:(new Date).toISOString(),resources:{}};Object.entries(this.resources).forEach(([e,r])=>{const i=r.export(),s=this.generateDefinitionHash(i),n=this.savedMetadata?.resources?.[e],a=n?.currentVersion||"v0",o=n?.versions?.[a];let c,l;o&&o.hash===s?(c=a,l=!1):(c=this.getNextVersion(n?.versions),l=!0),t.resources[e]={currentVersion:c,partitions:r.config.partitions||{},versions:{...n?.versions,[c]:{hash:s,attributes:i.attributes,behavior:i.behavior||"user-managed",timestamps:r.config.timestamps,partitions:r.config.partitions,paranoid:r.config.paranoid,allNestedObjectsOptional:r.config.allNestedObjectsOptional,autoDecrypt:r.config.autoDecrypt,cache:r.config.cache,hooks:r.config.hooks,createdAt:l?(new Date).toISOString():o?.createdAt}}},r.version!==c&&(r.version=c,r.emit("versionUpdated",{oldVersion:a,newVersion:c}))}),await this.client.putObject({key:"s3db.json",body:JSON.stringify(t,null,2),contentType:"application/json"}),this.savedMetadata=t,this.emit("metadataUploaded",t)}blankMetadataStructure(){return{version:"1",s3dbVersion:this.s3dbVersion,resources:{}}}resourceExists(t){return!!this.resources[t]}resourceExistsWithSameHash({name:t,attributes:e,behavior:r="user-managed",partitions:i={},options:s={}}){if(!this.resources[t])return{exists:!1,sameHash:!1,hash:null};const n=this.resources[t],a=this.generateDefinitionHash(n.export()),o=new gs({name:t,attributes:e,behavior:r,partitions:i,client:this.client,version:n.version,passphrase:this.passphrase,versioningEnabled:this.versioningEnabled,...s}),c=this.generateDefinitionHash(o.export());return{exists:!0,sameHash:a===c,hash:c,existingHash:a}}async createResource({name:t,attributes:e,behavior:r="user-managed",hooks:i,...s}){if(this.resources[t]){const n=this.resources[t];if(Object.assign(n.config,{cache:this.cache,...s}),r&&(n.behavior=r),n.versioningEnabled=this.versioningEnabled,n.updateAttributes(e),i)for(const[t,e]of Object.entries(i))if(Array.isArray(e)&&n.hooks[t])for(const r of e)"function"==typeof r&&n.hooks[t].push(r.bind(n));const a=this.generateDefinitionHash(n.export(),n.behavior),o=this.savedMetadata?.resources?.[t],c=o?.currentVersion||"v0",l=o?.versions?.[c];return l&&l.hash===a||await this.uploadMetadataFile(),this.emit("s3db.resourceUpdated",t),n}const n=this.savedMetadata?.resources?.[t],a=n?.currentVersion||"v0",o=new gs({name:t,client:this.client,version:void 0!==s.version?s.version:a,attributes:e,behavior:r,parallelism:this.parallelism,passphrase:void 0!==s.passphrase?s.passphrase:this.passphrase,observers:[this],cache:void 0!==s.cache?s.cache:this.cache,timestamps:void 0!==s.timestamps&&s.timestamps,partitions:s.partitions||{},paranoid:void 0===s.paranoid||s.paranoid,allNestedObjectsOptional:void 0===s.allNestedObjectsOptional||s.allNestedObjectsOptional,autoDecrypt:void 0===s.autoDecrypt||s.autoDecrypt,hooks:i||{},versioningEnabled:this.versioningEnabled,map:s.map,idGenerator:s.idGenerator,idSize:s.idSize});return o.database=this,this.resources[t]=o,await this.uploadMetadataFile(),this.emit("s3db.resourceCreated",t),o}resource(t){return this.resources[t]?this.resources[t]:Promise.reject(`resource ${t} does not exist`)}async listResources(){return Object.keys(this.resources).map(t=>({name:t}))}async getResource(t){if(!this.resources[t])throw new it({bucket:this.client.config.bucket,resourceName:t,id:t});return this.resources[t]}get config(){return{version:this.version,s3dbVersion:this.s3dbVersion,bucket:this.bucket,keyPrefix:this.keyPrefix,parallelism:this.parallelism,verbose:this.verbose}}isConnected(){return!!this.savedMetadata}async disconnect(){try{if(this.pluginList&&this.pluginList.length>0){for(const t of this.pluginList)t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners();const t=this.pluginList.map(async t=>{try{t&&"function"==typeof t.stop&&await t.stop()}catch(t){}});await Promise.all(t)}if(this.resources&&Object.keys(this.resources).length>0){for(const[t,e]of Object.entries(this.resources))try{e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners(),e._pluginWrappers&&e._pluginWrappers.clear(),e._pluginMiddlewares&&(e._pluginMiddlewares={}),e.observers&&Array.isArray(e.observers)&&(e.observers=[])}catch(t){}Object.keys(this.resources).forEach(t=>delete this.resources[t])}this.client&&"function"==typeof this.client.removeAllListeners&&this.client.removeAllListeners(),this.removeAllListeners(),this.savedMetadata=null,this.plugins={},this.pluginList=[],this.emit("disconnected",new Date)}catch(t){}}}class ys extends ms{}function bs(t){return"string"==typeof t?t.trim().toLowerCase():t}var ws=class extends Ti{constructor(t={},e=[],r=null){super(t),this.instanceId=Math.random().toString(36).slice(2,10),this.client=r,this.connectionString=t.connectionString;let i=e;if(e)if(Array.isArray(e)){i={};for(const t of e)"string"==typeof t&&(i[bs(t)]=t)}else"string"==typeof e&&(i[bs(e)]=e);else i={};this.resourcesMap=this._normalizeResources(i)}_normalizeResources(t){if(!t)return{};if(Array.isArray(t)){const e={};for(const r of t)"string"==typeof r?e[bs(r)]=r:"object"==typeof r&&r.resource&&(e[bs(r.resource)]=r);return e}if("object"==typeof t){const e={};for(const[r,i]of Object.entries(t)){const t=bs(r);"string"==typeof i?e[t]=i:Array.isArray(i)?e[t]=i.map(t=>("string"==typeof t||"object"==typeof t&&t.resource,t)):("function"==typeof i||"object"==typeof i&&i.resource)&&(e[t]=i)}return e}return"function"==typeof t?t:{}}validateConfig(){const t=[];return this.client||this.connectionString||t.push("You must provide a client or a connectionString"),(!this.resourcesMap||"object"==typeof this.resourcesMap&&0===Object.keys(this.resourcesMap).length)&&t.push("You must provide a resources map or array"),{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);const[e,r]=await wt(async()=>{if(this.client)this.targetDatabase=this.client;else{if(!this.connectionString)throw new Error("S3dbReplicator: No client or connectionString provided");{const t={connectionString:this.connectionString,region:this.region,keyPrefix:this.keyPrefix,verbose:this.config.verbose||!1};this.targetDatabase=new ys(t),await this.targetDatabase.connect()}}this.emit("connected",{replicator:this.name,target:this.connectionString||"client-provided"})});if(!e)throw this.config.verbose&&console.warn(`[S3dbReplicator] Initialization failed: ${r.message}`),r}async replicate(t,e,r,i,s){let n,a,o,c;"object"==typeof t&&t.resource?(n=t.resource,a=t.operation,o=t.data,c=t.id):(n=t,a=e,o=r,c=i);const l=bs(n),u=this.resourcesMap[l];if(!u)throw new Error(`[S3dbReplicator] Resource not configured: ${n}`);if(Array.isArray(u)){const t=[];for(const e of u){const[r,i,s]=await wt(async()=>await this._replicateToSingleDestination(e,l,a,o,c));if(!r)throw this.config&&this.config.verbose&&console.warn(`[S3dbReplicator] Failed to replicate to destination ${JSON.stringify(e)}: ${i.message}`),i;t.push(s)}return t}{const[t,e,r]=await wt(async()=>await this._replicateToSingleDestination(u,l,a,o,c));if(!t)throw this.config&&this.config.verbose&&console.warn(`[S3dbReplicator] Failed to replicate to destination ${JSON.stringify(u)}: ${e.message}`),e;return r}}async _replicateToSingleDestination(t,e,r,i,s){let n;if(n="string"==typeof t?t:"object"==typeof t&&t.resource?t.resource:e,"object"==typeof t&&t.actions&&Array.isArray(t.actions)&&!t.actions.includes(r))return{skipped:!0,reason:"action_not_supported",action:r,destination:n};const a=this._getDestResourceObj(n);let o,c;if("object"==typeof t&&t.transform&&"function"==typeof t.transform?(o=t.transform(i),o&&i&&i.id&&!o.id&&(o.id=i.id)):"object"==typeof t&&t.transformer&&"function"==typeof t.transformer?(o=t.transformer(i),o&&i&&i.id&&!o.id&&(o.id=i.id)):o=i,!o&&i&&(o=i),"insert"===r)c=await a.insert(o);else if("update"===r)c=await a.update(s,o);else{if("delete"!==r)throw new Error(`Invalid operation: ${r}. Supported operations are: insert, update, delete`);c=await a.delete(s)}return c}_applyTransformer(t,e){let r=this._cleanInternalFields(e);const i=bs(t),s=this.resourcesMap[i];let n;if(!s)return r;if(Array.isArray(s)){for(const t of s){if("object"==typeof t&&t.transform&&"function"==typeof t.transform){n=t.transform(r);break}if("object"==typeof t&&t.transformer&&"function"==typeof t.transformer){n=t.transformer(r);break}}n||(n=r)}else"object"==typeof s?"function"==typeof s.transform?n=s.transform(r):"function"==typeof s.transformer&&(n=s.transformer(r)):n="function"==typeof s?s(r):r;return n&&r&&r.id&&!n.id&&(n.id=r.id),!n&&r&&(n=r),n}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}_resolveDestResource(t,e){const r=bs(t),i=this.resourcesMap[r];if(!i)return t;if(Array.isArray(i)){for(const t of i){if("string"==typeof t)return t;if("object"==typeof t&&t.resource)return t.resource}return t}return"string"==typeof i?i:"function"==typeof i?t:"object"==typeof i&&i.resource?i.resource:t}_getDestResourceObj(t){const e=Object.keys(this.client.resources||{}),r=bs(t),i=e.find(t=>bs(t)===r);if(!i)throw new Error(`[S3dbReplicator] Destination resource not found: ${t}. Available: ${e.join(", ")}`);return this.client.resources[i]}async replicateBatch(t,e){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};const r=[],i=[];for(const s of e){const[e,n,a]=await wt(()=>this.replicate({resource:t,operation:s.operation,id:s.id,data:s.data,beforeData:s.beforeData}));e?r.push(a):(this.config.verbose&&console.warn(`[S3dbReplicator] Batch replication failed for record ${s.id}: ${n.message}`),i.push({id:s.id,error:n.message}))}return i.length>0&&console.warn(`[S3dbReplicator] Batch replication completed with ${i.length} error(s) for ${t}:`,i),this.emit("batch_replicated",{replicator:this.name,resourceName:t,total:e.length,successful:r.length,errors:i.length}),{success:0===i.length,results:r,errors:i,total:e.length}}async testConnection(){const[t,e]=await wt(async()=>{if(!this.targetDatabase)throw new Error("No target database configured");return"function"==typeof this.targetDatabase.connect&&await this.targetDatabase.connect(),!0});return!!t||(this.config.verbose&&console.warn(`[S3dbReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.targetDatabase,targetDatabase:this.connectionString||"client-provided",resources:Object.keys(this.resourcesMap||{}),totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.targetDatabase&&this.targetDatabase.removeAllListeners(),await super.cleanup()}shouldReplicateResource(t,e){const r=bs(t),i=this.resourcesMap[r];if(!i)return!1;if(!e)return!0;if(Array.isArray(i)){for(const t of i)if("object"==typeof t&&t.resource){if(!t.actions||!Array.isArray(t.actions))return!0;if(t.actions.includes(e))return!0}else if("string"==typeof t)return!0;return!1}return"object"==typeof i&&i.resource?!i.actions||!Array.isArray(i.actions)||i.actions.includes(e):"string"==typeof i||"function"==typeof i}};const vs={s3db:ws,sqs:class extends Ti{constructor(t={},e=[],r=null){if(super(t),this.client=r,this.queueUrl=t.queueUrl,this.queues=t.queues||{},this.defaultQueue=t.defaultQueue||t.defaultQueueUrl||t.queueUrlDefault,this.region=t.region||"us-east-1",this.sqsClient=r||null,this.messageGroupId=t.messageGroupId,this.deduplicationId=t.deduplicationId,Array.isArray(e)){this.resources={};for(const t of e)"string"==typeof t?this.resources[t]=!0:"object"==typeof t&&t.name&&(this.resources[t.name]=t)}else if("object"==typeof e){this.resources=e;for(const[t,r]of Object.entries(e))r&&r.queueUrl&&(this.queues[t]=r.queueUrl)}else this.resources={}}validateConfig(){const t=[];return this.queueUrl||0!==Object.keys(this.queues).length||this.defaultQueue||this.resourceQueueMap||t.push("Either queueUrl, queues object, defaultQueue, or resourceQueueMap must be provided"),{isValid:0===t.length,errors:t}}getQueueUrlsForResource(t){if(this.resourceQueueMap&&this.resourceQueueMap[t])return this.resourceQueueMap[t];if(this.queues[t])return[this.queues[t]];if(this.queueUrl)return[this.queueUrl];if(this.defaultQueue)return[this.defaultQueue];throw new Error(`No queue URL found for resource '${t}'`)}_applyTransformer(t,e){let r=this._cleanInternalFields(e);const i=this.resources[t];let s=r;return i?("function"==typeof i.transform?s=i.transform(r):"function"==typeof i.transformer&&(s=i.transformer(r)),s||r):r}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}createMessage(t,e,r,i,s=null){const n={resource:t,action:e,timestamp:(new Date).toISOString(),source:"s3db-replicator"};switch(e){case"insert":case"delete":default:return{...n,data:r};case"update":return{...n,before:s,data:r}}}async initialize(t,e){if(await super.initialize(t),!this.sqsClient){const[t,r,i]=await wt(()=>import("@aws-sdk/client-sqs"));if(!t)throw this.config.verbose&&console.warn(`[SqsReplicator] Failed to import SQS SDK: ${r.message}`),this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{SQSClient:s}=i;this.sqsClient=e||new s({region:this.region,credentials:this.config.credentials}),this.emit("initialized",{replicator:this.name,queueUrl:this.queueUrl,queues:this.queues,defaultQueue:this.defaultQueue})}}async replicate(t,e,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};const[n,a,o]=await wt(async()=>{const{SendMessageCommand:n}=await import("@aws-sdk/client-sqs"),a=this.getQueueUrlsForResource(t),o=this._applyTransformer(t,r),c=this.createMessage(t,e,o,i,s),l=[];for(const r of a){const s=new n({QueueUrl:r,MessageBody:JSON.stringify(c),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${t}:${e}:${i}`:void 0}),a=await this.sqsClient.send(s);l.push({queueUrl:r,messageId:a.MessageId}),this.emit("replicated",{replicator:this.name,resource:t,operation:e,id:i,queueUrl:r,messageId:a.MessageId,success:!0})}return{success:!0,results:l}});return n?o:(this.config.verbose&&console.warn(`[SqsReplicator] Replication failed for ${t}: ${a.message}`),this.emit("replicator_error",{replicator:this.name,resource:t,operation:e,id:i,error:a.message}),{success:!1,error:a.message})}async replicateBatch(t,e){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};const[r,i,s]=await wt(async()=>{const{SendMessageBatchCommand:r}=await import("@aws-sdk/client-sqs"),i=this.getQueueUrlsForResource(t),s=[];for(let t=0;t<e.length;t+=10)s.push(e.slice(t,t+10));const n=[],a=[];for(const e of s){const[s,o]=await wt(async()=>{const s=e.map((e,r)=>({Id:`${e.id}-${r}`,MessageBody:JSON.stringify(this.createMessage(t,e.operation,e.data,e.id,e.beforeData)),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${t}:${e.operation}:${e.id}`:void 0})),a=new r({QueueUrl:i[0],Entries:s}),o=await this.sqsClient.send(a);n.push(o)});if(!s&&(a.push({batch:e.length,error:o.message}),o.message&&(o.message.includes("Batch error")||o.message.includes("Connection")||o.message.includes("Network"))))throw o}return a.length>0&&console.warn(`[SqsReplicator] Batch replication completed with ${a.length} error(s) for ${t}:`,a),this.emit("batch_replicated",{replicator:this.name,resource:t,queueUrl:i[0],total:e.length,successful:n.length,errors:a.length}),{success:0===a.length,results:n,errors:a,total:e.length,queueUrl:i[0]}});if(r)return s;const n=i?.message||i||"Unknown error";return this.config.verbose&&console.warn(`[SqsReplicator] Batch replication failed for ${t}: ${n}`),this.emit("batch_replicator_error",{replicator:this.name,resource:t,error:n}),{success:!1,error:n}}async testConnection(){const[t,e]=await wt(async()=>{this.sqsClient||await this.initialize(this.database);const{GetQueueAttributesCommand:t}=await import("@aws-sdk/client-sqs"),e=new t({QueueUrl:this.queueUrl,AttributeNames:["QueueArn"]});return await this.sqsClient.send(e),!0});return!!t||(this.config.verbose&&console.warn(`[SqsReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.sqsClient,queueUrl:this.queueUrl,region:this.region,resources:Object.keys(this.resources||{}),totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.sqsClient&&this.sqsClient.destroy(),await super.cleanup()}shouldReplicateResource(t){return this.resourceQueueMap&&Object.keys(this.resourceQueueMap).includes(t)||this.queues&&Object.keys(this.queues).includes(t)||!(!this.defaultQueue&&!this.queueUrl)||this.resources&&Object.keys(this.resources).includes(t)||!1}},bigquery:Mi,postgres:Li};function Ss(t){return"string"==typeof t?t.trim().toLowerCase():t}class _s extends Tt{constructor(t={}){if(super(),!t.replicators||!Array.isArray(t.replicators))throw new Error("ReplicatorPlugin: replicators array is required");for(const e of t.replicators){if(!e.driver)throw new Error("ReplicatorPlugin: each replicator must have a driver");if(!e.resources||"object"!=typeof e.resources)throw new Error("ReplicatorPlugin: each replicator must have resources config");if(0===Object.keys(e.resources).length)throw new Error("ReplicatorPlugin: each replicator must have at least one resource configured")}this.config={replicators:t.replicators||[],logErrors:!1!==t.logErrors,replicatorLogResource:t.replicatorLogResource||"replicator_log",enabled:!1!==t.enabled,batchSize:t.batchSize||100,maxRetries:t.maxRetries||3,timeout:t.timeout||3e4,verbose:t.verbose||!1,...t},this.replicators=[],this.database=null,this.eventListenersInstalled=new Set}async decompressData(t){return t}filterInternalFields(t){if(!t||"object"!=typeof t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||"$overflow"===r||"$before"===r||"$after"===r||(e[r]=i);return e}installEventListeners(t,e,r){t&&!this.eventListenersInstalled.has(t.name)&&t.name!==this.config.replicatorLogResource&&(t.on("insert",async e=>{const[i,s]=await wt(async()=>{const i={...e,createdAt:(new Date).toISOString()};await r.processReplicatorEvent("insert",t.name,i.id,i)});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Insert event failed for resource ${t.name}: ${s.message}`),this.emit("error",{operation:"insert",error:s.message,resource:t.name}))}),t.on("update",async(e,i)=>{const[s,n]=await wt(async()=>{const s={...e,updatedAt:(new Date).toISOString()};await r.processReplicatorEvent("update",t.name,s.id,s,i)});s||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Update event failed for resource ${t.name}: ${n.message}`),this.emit("error",{operation:"update",error:n.message,resource:t.name}))}),t.on("delete",async e=>{const[i,s]=await wt(async()=>{await r.processReplicatorEvent("delete",t.name,e.id,e)});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Delete event failed for resource ${t.name}: ${s.message}`),this.emit("error",{operation:"delete",error:s.message,resource:t.name}))}),this.eventListenersInstalled.add(t.name))}async getCompleteData(t,e){const[r,i,s]=await wt(()=>t.get(e.id));return r?s:e}async setup(t){this.database=t;const[e,r]=await wt(async()=>{await this.initializeReplicators(t)});if(!e)throw this.config.verbose&&console.warn(`[ReplicatorPlugin] Replicator initialization failed: ${r.message}`),this.emit("error",{operation:"setup",error:r.message}),r;const[i,s]=await wt(async()=>{if(this.config.replicatorLogResource){await t.createResource({name:this.config.replicatorLogResource,behavior:"body-overflow",attributes:{operation:"string",resourceName:"string",recordId:"string",data:"string",error:"string|optional",replicator:"string",timestamp:"string",status:"string"}})}});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to create log resource ${this.config.replicatorLogResource}: ${s.message}`),this.emit("replicator_log_resource_creation_error",{resourceName:this.config.replicatorLogResource,error:s.message})),await this.uploadMetadataFile(t);const n=t.createResource.bind(t);t.createResource=async e=>{const r=await n(e);return r&&this.installEventListeners(r,t,this),r};for(const e in t.resources){const r=t.resources[e];this.installEventListeners(r,t,this)}}createReplicator(t,e,r,i){return function(t,e={},r=[],i=null){const s=vs[t];if(!s)throw new Error(`Unknown replicator driver: ${t}. Available drivers: ${Object.keys(vs).join(", ")}`);return new s(e,r,i)}(t,e,r,i)}async initializeReplicators(t){for(const e of this.config.replicators){const{driver:r,config:i={},resources:s,client:n,...a}=e,o=s||i.resources||{},c={...i,...a},l=this.createReplicator(r,c,o,n);l&&(await l.initialize(t),this.replicators.push(l))}}async start(){}async stop(){}async uploadMetadataFile(t){"function"==typeof t.uploadMetadataFile&&await t.uploadMetadataFile()}async retryWithBackoff(t,e=3){let r;for(let i=1;i<=e;i++){const[s,n]=await wt(t);if(s)return s;{if(r=n,this.config.verbose&&console.warn(`[ReplicatorPlugin] Retry attempt ${i}/${e} failed: ${n.message}`),i===e)throw n;const t=1e3*Math.pow(2,i-1);this.config.verbose&&console.warn(`[ReplicatorPlugin] Waiting ${t}ms before retry...`),await new Promise(e=>setTimeout(e,t))}}throw r}async logError(t,e,r,i,s,n){const[a,o]=await wt(async()=>{const a=this.config.replicatorLogResource;if(this.database&&this.database.resources&&this.database.resources[a]){const o=this.database.resources[a];await o.insert({replicator:t.name||t.id,resourceName:e,operation:r,recordId:i,data:JSON.stringify(s),error:n.message,timestamp:(new Date).toISOString(),status:"error"})}});a||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to log error for ${e}: ${o.message}`),this.emit("replicator_log_error",{replicator:t.name||t.id,resourceName:e,operation:r,recordId:i,originalError:n.message,logError:o.message}))}async processReplicatorEvent(t,e,r,i,s=null){if(!this.config.enabled)return;const n=this.replicators.filter(r=>r.shouldReplicateResource&&r.shouldReplicateResource(e,t));if(0===n.length)return;const a=n.map(async n=>{const[a,o,c]=await wt(async()=>{const a=await this.retryWithBackoff(()=>n.replicate(e,t,i,r,s),this.config.maxRetries);return this.emit("replicated",{replicator:n.name||n.id,resourceName:e,operation:t,recordId:r,result:a,success:!0}),a});if(a)return c;throw this.config.verbose&&console.warn(`[ReplicatorPlugin] Replication failed for ${n.name||n.id} on ${e}: ${o.message}`),this.emit("replicator_error",{replicator:n.name||n.id,resourceName:e,operation:t,recordId:r,error:o.message}),this.config.logErrors&&this.database&&await this.logError(n,e,t,r,i,o),o});return Promise.allSettled(a)}async processreplicatorItem(t){const e=this.replicators.filter(e=>e.shouldReplicateResource&&e.shouldReplicateResource(t.resourceName,t.operation));if(0===e.length)return;const r=e.map(async e=>{const[r,i]=await wt(async()=>{const[r,i,s]=await wt(()=>e.replicate(t.resourceName,t.operation,t.data,t.recordId,t.beforeData));return r?(this.emit("replicated",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,result:s,success:!0}),{success:!0,result:s}):(this.config.verbose&&console.warn(`[ReplicatorPlugin] Replicator item processing failed for ${e.name||e.id} on ${t.resourceName}: ${i.message}`),this.emit("replicator_error",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,error:i.message}),this.config.logErrors&&this.database&&await this.logError(e,t.resourceName,t.operation,t.recordId,t.data,i),{success:!1,error:i.message})});return r||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Wrapper processing failed for ${e.name||e.id} on ${t.resourceName}: ${i.message}`),this.emit("replicator_error",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,error:i.message}),this.config.logErrors&&this.database&&await this.logError(e,t.resourceName,t.operation,t.recordId,t.data,i),{success:!1,error:i.message})});return Promise.allSettled(r)}async logreplicator(t){const e=this.replicatorLog||this.database.resources[Ss(this.config.replicatorLogResource)];if(!e)return this.database&&this.database.options&&this.database.options.connectionString,void this.emit("replicator.log.failed",{error:"replicator log resource not found",item:t});const r={id:t.id||`repl-${Date.now()}-${Math.random().toString(36).slice(2)}`,resource:t.resource||t.resourceName||"",action:t.operation||t.action||"",data:t.data||{},timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now(),createdAt:t.createdAt||(new Date).toISOString().slice(0,10)},[i,s]=await wt(async()=>{await e.insert(r)});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to log replicator item: ${s.message}`),this.emit("replicator.log.failed",{error:s,item:t}))}async updatereplicatorLog(t,e){if(!this.replicatorLog)return;const[r,i]=await wt(async()=>{await this.replicatorLog.update(t,{...e,lastAttempt:(new Date).toISOString()})});r||this.emit("replicator.updateLog.failed",{error:i.message,logId:t,updates:e})}async getreplicatorStats(){return{replicators:await Promise.all(this.replicators.map(async t=>{const e=await t.getStatus();return{id:t.id,driver:t.driver,config:t.config,status:e}})),queue:{length:this.queue.length,isProcessing:this.isProcessing},stats:this.stats,lastSync:this.stats.lastSync}}async getreplicatorLogs(t={}){if(!this.replicatorLog)return[];const{resourceName:e,operation:r,status:i,limit:s=100,offset:n=0}=t;let a={};e&&(a.resourceName=e),r&&(a.operation=r),i&&(a.status=i);return(await this.replicatorLog.list(a)).slice(n,n+s)}async retryFailedreplicators(){if(!this.replicatorLog)return{retried:0};const t=await this.replicatorLog.list({status:"failed"});let e=0;for(const r of t){const[t,i]=await wt(async()=>{await this.processReplicatorEvent(r.resourceName,r.operation,r.recordId,r.data)});t&&e++}return{retried:e}}async syncAllData(t){const e=this.replicators.find(e=>e.id===t);if(!e)throw new Error(`Replicator not found: ${t}`);this.stats.lastSync=(new Date).toISOString();for(const r in this.database.resources)if(Ss(r)!==Ss("replicator_logs")&&e.shouldReplicateResource(r)){this.emit("replicator.sync.resource",{resourceName:r,replicatorId:t});const i=this.database.resources[r],s=await i.getAll();for(const t of s)await e.replicate(r,"insert",t,t.id)}this.emit("replicator.sync.completed",{replicatorId:t,stats:this.stats})}async cleanup(){const[t,e]=await wt(async()=>{if(this.replicators&&this.replicators.length>0){const t=this.replicators.map(async t=>{const[e,r]=await wt(async()=>{t&&"function"==typeof t.cleanup&&await t.cleanup()});e||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to cleanup replicator ${t.name||t.id}: ${r.message}`),this.emit("replicator_cleanup_error",{replicator:t.name||t.id||"unknown",driver:t.driver||"unknown",error:r.message}))});await Promise.allSettled(t)}this.replicators=[],this.database=null,this.eventListenersInstalled.clear(),this.removeAllListeners()});t||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to cleanup plugin: ${e.message}`),this.emit("replicator_plugin_cleanup_error",{error:e.message}))}}export{fs as AVAILABLE_BEHAVIORS,Lt as AuditPlugin,tt as AuthenticationError,G as BaseError,Ii as CachePlugin,Fi as Client,Ui as ConnectionString,ft as ConnectionStringError,$i as CostsPlugin,dt as CryptoError,ds as DEFAULT_BEHAVIOR,ms as Database,X as DatabaseError,rt as EncryptionError,ut as ErrorMap,Pi as FullTextPlugin,ct as InvalidResourceItem,Ci as MetricsPlugin,ot as MissingMetadata,st as NoSuchBucket,nt as NoSuchKey,at as NotFound,mt as PartitionError,et as PermissionError,Tt as Plugin,Mt as PluginObject,_s as ReplicatorPlugin,ps as Resource,gt as ResourceError,ki as ResourceIdsPageReader,Si as ResourceIdsReader,it as ResourceNotFound,Oi as ResourceReader,Ri as ResourceWriter,ms as S3db,Q as S3dbError,Ji as Schema,pt as SchemaError,lt as UnknownError,Z as ValidationError,Vi as Validator,us as behaviors,z as calculateAttributeNamesSize,K as calculateAttributeSizes,Y as calculateEffectiveLimit,H as calculateSystemOverhead,W as calculateTotalSize,B as calculateUTF8Bytes,U as decode,q as decodeDecimal,kt as decrypt,ys as default,L as encode,F as encodeDecimal,_t as encrypt,hs as getBehavior,J as getSizeBreakdown,jt as idGenerator,ht as mapAwsError,Ot as md5,xt as passwordGenerator,St as sha256,ji as streamToString,V as transformValue,yt as tryFn,bt as tryFnSync};
1
+ import{customAlphabet as t,urlAlphabet as e}from"nanoid";import r from"node:zlib";import{PromisePool as i}from"@supercharge/promise-pool";import{ReadableStream as s}from"node:stream/web";import{mkdir as n,writeFile as a,readFile as o,stat as c,unlink as l,readdir as u,rm as h}from"fs/promises";import{createHash as f}from"crypto";import{chunk as d,merge as p,isString as g,isEmpty as m,invert as y,uniq as b,cloneDeep as w,get as v,set as S,isObject as _,isFunction as k}from"lodash-es";import O from"json-stable-stringify";import{S3Client as R,PutObjectCommand as j,GetObjectCommand as x,HeadObjectCommand as E,CopyObjectCommand as D,DeleteObjectCommand as A,DeleteObjectsCommand as N,ListObjectsV2Command as I}from"@aws-sdk/client-s3";import{flatten as $,unflatten as P}from"flat";import C from"fastest-validator";const T="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",M=Object.fromEntries([...T].map((t,e)=>[t,e])),L=t=>{if("number"!=typeof t||isNaN(t))return"undefined";if(!isFinite(t))return"undefined";if(0===t)return T[0];if(t<0)return"-"+L(-Math.floor(t));t=Math.floor(t);let e="";for(;t;)e=T[t%62]+e,t=Math.floor(t/62);return e},U=t=>{if("string"!=typeof t)return NaN;if(""===t)return 0;let e=!1;"-"===t[0]&&(e=!0,t=t.slice(1));let r=0;for(let e=0;e<t.length;e++){const i=M[t[e]];if(void 0===i)return NaN;r=62*r+i}return e?-r:r},F=t=>{if("number"!=typeof t||isNaN(t))return"undefined";if(!isFinite(t))return"undefined";const e=t<0;t=Math.abs(t);const[r,i]=t.toString().split("."),s=L(Number(r));return i?(e?"-":"")+s+"."+i:(e?"-":"")+s},q=t=>{if("string"!=typeof t)return NaN;let e=!1;"-"===t[0]&&(e=!0,t=t.slice(1));const[r,i]=t.split("."),s=U(r);if(isNaN(s))return NaN;const n=i?Number(s+"."+i):s;return e?-n:n};function B(t){"string"!=typeof t&&(t=String(t));let e=0;for(let r=0;r<t.length;r++){const i=t.codePointAt(r);i<=127?e+=1:i<=2047?e+=2:i<=65535?e+=3:i<=1114111&&(e+=4,i>65535&&r++)}return e}function z(t){let e=0;for(const r of Object.keys(t))e+=B(r);return e}function V(t){return null==t?"":"boolean"==typeof t?t?"1":"0":"number"==typeof t?String(t):"string"==typeof t?t:Array.isArray(t)?0===t.length?"[]":t.map(t=>String(t)).join("|"):"object"==typeof t?JSON.stringify(t):String(t)}function K(t){const e={};for(const[r,i]of Object.entries(t)){const t=B(V(i));e[r]=t}return e}function W(t){const e=K(t);return Object.values(e).reduce((t,e)=>t+e,0)+z(t)}function J(t){const e=K(t),r=z(t),i=Object.values(e).reduce((t,e)=>t+e,0),s=i+r,n=Object.entries(e).sort(([,t],[,e])=>e-t).map(([t,e])=>({attribute:t,size:e,percentage:(e/s*100).toFixed(2)+"%"}));return{total:s,valueSizes:e,namesSize:r,valueTotal:i,breakdown:n,detailedBreakdown:{values:i,names:r,total:s}}}function H(t={}){const{version:e="1",timestamps:r=!1,id:i=""}=t,s={_v:String(e)};r&&(s.createdAt="2024-01-01T00:00:00.000Z",s.updatedAt="2024-01-01T00:00:00.000Z"),i&&(s.id=i);const n={};for(const[t,e]of Object.entries(s))n[t]=e;return W(n)}function Y(t={}){const{s3Limit:e=2048,systemConfig:r={}}=t;return e-H(r)}class G extends Error{constructor({verbose:t,bucket:e,key:r,message:i,code:s,statusCode:n,requestId:a,awsMessage:o,original:c,commandName:l,commandInput:u,metadata:h,suggestion:f,...d}){t&&(i+=`\n\nVerbose:\n\n${JSON.stringify(d,null,2)}`),super(i),"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error(i).stack,super.name=this.constructor.name,this.name=this.constructor.name,this.bucket=e,this.key=r,this.thrownAt=new Date,this.code=s,this.statusCode=n,this.requestId=a,this.awsMessage=o,this.original=c,this.commandName=l,this.commandInput=u,this.metadata=h,this.suggestion=f,this.data={bucket:e,key:r,...d,verbose:t,message:i}}toJson(){return{name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,requestId:this.requestId,awsMessage:this.awsMessage,bucket:this.bucket,key:this.key,thrownAt:this.thrownAt,commandName:this.commandName,commandInput:this.commandInput,metadata:this.metadata,suggestion:this.suggestion,data:this.data,original:this.original,stack:this.stack}}toString(){return`${this.name} | ${this.message}`}}class Q extends G{constructor(t,e={}){let r,i,s,n,a,o;e.original&&(a=e.original,r=a.code||a.Code||a.name,i=a.statusCode||a.$metadata&&a.$metadata.httpStatusCode,s=a.requestId||a.$metadata&&a.$metadata.requestId,n=a.message,o=a.$metadata?{...a.$metadata}:void 0),super({message:t,...e,code:r,statusCode:i,requestId:s,awsMessage:n,original:a,metadata:o})}}class X extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class Z extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class tt extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class et extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class rt extends Q{constructor(t,e={}){super(t,e),Object.assign(this,e)}}class it extends Q{constructor({bucket:t,resourceName:e,id:r,original:i,...s}){if("string"!=typeof r)throw new Error("id must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");if("string"!=typeof e)throw new Error("resourceName must be a string");super(`Resource not found: ${e}/${r} [bucket:${t}]`,{bucket:t,resourceName:e,id:r,original:i,...s})}}class st extends Q{constructor({bucket:t,original:e,...r}){if("string"!=typeof t)throw new Error("bucket must be a string");super(`Bucket does not exists [bucket:${t}]`,{bucket:t,original:e,...r})}}class nt extends Q{constructor({bucket:t,key:e,resourceName:r,id:i,original:s,...n}){if("string"!=typeof e)throw new Error("key must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");if(void 0!==i&&"string"!=typeof i)throw new Error("id must be a string");super(`No such key: ${e} [bucket:${t}]`,{bucket:t,key:e,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class at extends Q{constructor({bucket:t,key:e,resourceName:r,id:i,original:s,...n}){if("string"!=typeof e)throw new Error("key must be a string");if("string"!=typeof t)throw new Error("bucket must be a string");super(`Not found: ${e} [bucket:${t}]`,{bucket:t,key:e,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class ot extends Q{constructor({bucket:t,original:e,...r}){if("string"!=typeof t)throw new Error("bucket must be a string");super(`Missing metadata for bucket [bucket:${t}]`,{bucket:t,original:e,...r})}}class ct extends Q{constructor({bucket:t,resourceName:e,attributes:r,validation:i,message:s,original:n,...a}){if("string"!=typeof t)throw new Error("bucket must be a string");if("string"!=typeof e)throw new Error("resourceName must be a string");super(s||`Validation error: This item is not valid. Resource=${e} [bucket:${t}].\n${JSON.stringify(i,null,2)}`,{bucket:t,resourceName:e,attributes:r,validation:i,original:n,...a})}}class lt extends Q{}const ut={NotFound:at,NoSuchKey:nt,UnknownError:lt,NoSuchBucket:st,MissingMetadata:ot,InvalidResourceItem:ct};function ht(t,e={}){const r=t.code||t.Code||t.name,i=t.$metadata?{...t.$metadata}:void 0,s=e.commandName,n=e.commandInput;let a;return"NoSuchKey"===r||"NotFound"===r?(a="Check if the key exists in the specified bucket and if your credentials have permission.",new nt({...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"NoSuchBucket"===r?(a="Check if the bucket exists and if your credentials have permission.",new st({...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"AccessDenied"===r||403===t.statusCode||"Forbidden"===r?(a="Check your credentials and bucket policy.",new et("Access denied",{...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"ValidationError"===r||400===t.statusCode?(a="Check the request parameters and payload.",new Z("Validation error",{...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):"MissingMetadata"===r?(a="Check if the object metadata is present and valid.",new ot({...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a})):(a="Check the error details and AWS documentation.",new lt("Unknown error",{...e,original:t,metadata:i,commandName:s,commandInput:n,suggestion:a}))}class ft extends Q{constructor(t,e={}){super(t,{...e,suggestion:"Check the connection string format and credentials."})}}class dt extends Q{constructor(t,e={}){super(t,{...e,suggestion:"Check if the crypto library is available and input is valid."})}}class pt extends Q{constructor(t,e={}){super(t,{...e,suggestion:"Check schema definition and input data."})}}class gt extends Q{constructor(t,e={}){super(t,{...e,suggestion:e.suggestion||"Check resource configuration, attributes, and operation context."}),Object.assign(this,e)}}class mt extends Q{constructor(t,e={}){super(t,{...e,suggestion:e.suggestion||"Check partition definition, fields, and input values."})}}function yt(t){if(null==t){const t=new Error("fnOrPromise cannot be null or undefined");return t.stack=(new Error).stack,[!1,t,void 0]}if("function"==typeof t)try{const e=t();return null==e?[!0,null,e]:"function"==typeof e.then?e.then(t=>[!0,null,t]).catch(t=>{if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}):[!0,null,e]}catch(t){if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}return"function"==typeof t.then?Promise.resolve(t).then(t=>[!0,null,t]).catch(t=>{if(t instanceof Error&&Object.isExtensible(t)){const e=Object.getOwnPropertyDescriptor(t,"stack");if(e&&e.writable&&e.configurable&&t.hasOwnProperty("stack"))try{t.stack=(new Error).stack}catch(t){}}return[!1,t,void 0]}):[!0,null,t]}function bt(t){try{return[!0,null,t()]}catch(t){return[!1,t,null]}}var wt=yt;async function vt(){let t;if("undefined"!=typeof process){const[e,r,i]=await wt(async()=>{const{webcrypto:t}=await import("crypto");return t});if(!e)throw new dt("Crypto API not available",{original:r,context:"dynamicCrypto"});t=i}else"undefined"!=typeof window&&(t=window.crypto);if(!t)throw new dt("Could not load any crypto library",{context:"dynamicCrypto"});return t}async function St(t){const[e,r,i]=await wt(vt);if(!e)throw new dt("Crypto API not available",{original:r});const s=(new TextEncoder).encode(t),[n,a,o]=await wt(()=>i.subtle.digest("SHA-256",s));if(!n)throw new dt("SHA-256 digest failed",{original:a,input:t});return Array.from(new Uint8Array(o)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function _t(t,e){const[r,i,s]=await wt(vt);if(!r)throw new dt("Crypto API not available",{original:i});const n=s.getRandomValues(new Uint8Array(16)),[a,o,c]=await wt(()=>Rt(e,n));if(!a)throw new dt("Key derivation failed",{original:o,passphrase:e,salt:n});const l=s.getRandomValues(new Uint8Array(12)),u=(new TextEncoder).encode(t),[h,f,d]=await wt(()=>s.subtle.encrypt({name:"AES-GCM",iv:l},c,u));if(!h)throw new dt("Encryption failed",{original:f,content:t});const p=new Uint8Array(n.length+l.length+d.byteLength);return p.set(n),p.set(l,n.length),p.set(new Uint8Array(d),n.length+l.length),function(t){if("undefined"!=typeof process)return Buffer.from(t).toString("base64");{const[e,r,i]=bt(()=>String.fromCharCode.apply(null,new Uint8Array(t)));if(!e)throw new dt("Failed to convert ArrayBuffer to base64 (browser)",{original:r});return window.btoa(i)}}(p)}async function kt(t,e){const[r,i,s]=await wt(vt);if(!r)throw new dt("Crypto API not available",{original:i});const n=function(t){if("undefined"!=typeof process)return new Uint8Array(Buffer.from(t,"base64"));{const[e,r,i]=bt(()=>window.atob(t));if(!e)throw new dt("Failed to decode base64 (browser)",{original:r});const s=i.length,n=new Uint8Array(s);for(let t=0;t<s;t++)n[t]=i.charCodeAt(t);return n}}(t),a=n.slice(0,16),o=n.slice(16,28),c=n.slice(28),[l,u,h]=await wt(()=>Rt(e,a));if(!l)throw new dt("Key derivation failed (decrypt)",{original:u,passphrase:e,salt:a});const[f,d,p]=await wt(()=>s.subtle.decrypt({name:"AES-GCM",iv:o},h,c));if(!f)throw new dt("Decryption failed",{original:d,encryptedBase64:t});return(new TextDecoder).decode(p)}async function Ot(t){if("undefined"==typeof process)throw new dt("MD5 hashing is only available in Node.js environment",{context:"md5"});const[e,r,i]=await wt(async()=>{const{createHash:e}=await import("crypto");return e("md5").update(t).digest("base64")});if(!e)throw new dt("MD5 hashing failed",{original:r,data:t});return i}async function Rt(t,e){const[r,i,s]=await wt(vt);if(!r)throw new dt("Crypto API not available",{original:i});const n=(new TextEncoder).encode(t),[a,o,c]=await wt(()=>s.subtle.importKey("raw",n,{name:"PBKDF2"},!1,["deriveKey"]));if(!a)throw new dt("importKey failed",{original:o,passphrase:t});const[l,u,h]=await wt(()=>s.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:1e5,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]));if(!l)throw new dt("deriveKey failed",{original:u,passphrase:t,salt:e});return h}const jt=t(e,22),xt=t("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",16);var Et;function Dt(){}function At(){At.init.call(this)}function Nt(t){return void 0===t._maxListeners?At.defaultMaxListeners:t._maxListeners}function It(t,e,r,i){var s,n,a,o;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=t._events)?(n.newListener&&(t.emit("newListener",e,r.listener?r.listener:r),n=t._events),a=n[e]):(n=t._events=new Dt,t._eventsCount=0),a){if("function"==typeof a?a=n[e]=i?[r,a]:[a,r]:i?a.unshift(r):a.push(r),!a.warned&&(s=Nt(t))&&s>0&&a.length>s){a.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+e+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=a.length,o=c,"function"==typeof console.warn?console.warn(o):console.log(o)}}else a=n[e]=r,++t._eventsCount;return t}function $t(t,e,r){var i=!1;function s(){t.removeListener(e,s),i||(i=!0,r.apply(t,arguments))}return s.listener=r,s}function Pt(t){var e=this._events;if(e){var r=e[t];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Ct(t,e){for(var r=new Array(e);e--;)r[e]=t[e];return r}Dt.prototype=Object.create(null),At.EventEmitter=At,At.usingDomains=!1,At.prototype.domain=void 0,At.prototype._events=void 0,At.prototype._maxListeners=void 0,At.defaultMaxListeners=10,At.init=function(){this.domain=null,At.usingDomains&&(!Et.active||this instanceof Et.Domain||(this.domain=Et.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Dt,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},At.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=t,this},At.prototype.getMaxListeners=function(){return Nt(this)},At.prototype.emit=function(t){var e,r,i,s,n,a,o,c="error"===t;if(a=this._events)c=c&&null==a.error;else if(!c)return!1;if(o=this.domain,c){if(e=arguments[1],!o){if(e instanceof Error)throw e;var l=new Error('Uncaught, unspecified "error" event. ('+e+")");throw l.context=e,l}return e||(e=new Error('Uncaught, unspecified "error" event')),e.domainEmitter=this,e.domain=o,e.domainThrown=!1,o.emit("error",e),!1}if(!(r=a[t]))return!1;var u="function"==typeof r;switch(i=arguments.length){case 1:!function(t,e,r){if(e)t.call(r);else for(var i=t.length,s=Ct(t,i),n=0;n<i;++n)s[n].call(r)}(r,u,this);break;case 2:!function(t,e,r,i){if(e)t.call(r,i);else for(var s=t.length,n=Ct(t,s),a=0;a<s;++a)n[a].call(r,i)}(r,u,this,arguments[1]);break;case 3:!function(t,e,r,i,s){if(e)t.call(r,i,s);else for(var n=t.length,a=Ct(t,n),o=0;o<n;++o)a[o].call(r,i,s)}(r,u,this,arguments[1],arguments[2]);break;case 4:!function(t,e,r,i,s,n){if(e)t.call(r,i,s,n);else for(var a=t.length,o=Ct(t,a),c=0;c<a;++c)o[c].call(r,i,s,n)}(r,u,this,arguments[1],arguments[2],arguments[3]);break;default:for(s=new Array(i-1),n=1;n<i;n++)s[n-1]=arguments[n];!function(t,e,r,i){if(e)t.apply(r,i);else for(var s=t.length,n=Ct(t,s),a=0;a<s;++a)n[a].apply(r,i)}(r,u,this,s)}return!0},At.prototype.addListener=function(t,e){return It(this,t,e,!1)},At.prototype.on=At.prototype.addListener,At.prototype.prependListener=function(t,e){return It(this,t,e,!0)},At.prototype.once=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.on(t,$t(this,t,e)),this},At.prototype.prependOnceListener=function(t,e){if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');return this.prependListener(t,$t(this,t,e)),this},At.prototype.removeListener=function(t,e){var r,i,s,n,a;if("function"!=typeof e)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[t]))return this;if(r===e||r.listener&&r.listener===e)0===--this._eventsCount?this._events=new Dt:(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===e||r[n].listener&&r[n].listener===e){a=r[n].listener,s=n;break}if(s<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new Dt,this;delete i[t]}else!function(t,e){for(var r=e,i=r+1,s=t.length;i<s;r+=1,i+=1)t[r]=t[i];t.pop()}(r,s);i.removeListener&&this.emit("removeListener",t,a||e)}return this},At.prototype.off=function(t,e){return this.removeListener(t,e)},At.prototype.removeAllListeners=function(t){var e,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Dt,this._eventsCount=0):r[t]&&(0===--this._eventsCount?this._events=new Dt:delete r[t]),this;if(0===arguments.length){for(var i,s=Object.keys(r),n=0;n<s.length;++n)"removeListener"!==(i=s[n])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new Dt,this._eventsCount=0,this}if("function"==typeof(e=r[t]))this.removeListener(t,e);else if(e)do{this.removeListener(t,e[e.length-1])}while(e[0]);return this},At.prototype.listeners=function(t){var e,r=this._events;return r&&(e=r[t])?"function"==typeof e?[e.listener||e]:function(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}(e):[]},At.listenerCount=function(t,e){return"function"==typeof t.listenerCount?t.listenerCount(e):Pt.call(t,e)},At.prototype.listenerCount=Pt,At.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var Tt=class extends At{constructor(t={}){super(),this.name=this.constructor.name,this.options=t,this.hooks=new Map}async setup(t){this.database=t,this.beforeSetup(),await this.onSetup(),this.afterSetup()}async start(){this.beforeStart(),await this.onStart(),this.afterStart()}async stop(){this.beforeStop(),await this.onStop(),this.afterStop()}async onSetup(){}async onStart(){}async onStop(){}addHook(t,e,r){this.hooks.has(t)||this.hooks.set(t,new Map);const i=this.hooks.get(t);i.has(e)||i.set(e,[]),i.get(e).push(r)}removeHook(t,e,r){const i=this.hooks.get(t);if(i&&i.has(e)){const t=i.get(e),s=t.indexOf(r);s>-1&&t.splice(s,1)}}wrapResourceMethod(t,e,r){const i=t[e];if(t._pluginWrappers||(t._pluginWrappers=new Map),t._pluginWrappers.has(e)||t._pluginWrappers.set(e,[]),t._pluginWrappers.get(e).push(r),!t[`_wrapped_${e}`]){t[`_wrapped_${e}`]=i;const r=i&&i._isMockFunction;t[e]=async function(...r){let i=await t[`_wrapped_${e}`](...r);for(const s of t._pluginWrappers.get(e))i=await s.call(this,i,r,e);return i},r&&(Object.setPrototypeOf(t[e],Object.getPrototypeOf(i)),Object.assign(t[e],i))}}addMiddleware(t,e,r){if(t._pluginMiddlewares||(t._pluginMiddlewares={}),!t._pluginMiddlewares[e]){t._pluginMiddlewares[e]=[];const r=t[e].bind(t);t[e]=async function(...i){let s=-1;const n=async(...i)=>(s++,s<t._pluginMiddlewares[e].length?await t._pluginMiddlewares[e][s].call(this,n,...i):await r(...i));return await n(...i)}}t._pluginMiddlewares[e].push(r)}getPartitionValues(t,e){if(!e.config?.partitions)return{};const r={};for(const[i,s]of Object.entries(e.config.partitions))if(s.fields){r[i]={};for(const[n,a]of Object.entries(s.fields)){const s=this.getNestedFieldValue(t,n);null!=s&&(r[i][n]=e.applyPartitionRule(s,a))}}else r[i]={};return r}getNestedFieldValue(t,e){if(!e.includes("."))return t[e]??null;const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return null;i=i[t]}return i??null}beforeSetup(){this.emit("plugin.beforeSetup",new Date)}afterSetup(){this.emit("plugin.afterSetup",new Date)}beforeStart(){this.emit("plugin.beforeStart",new Date)}afterStart(){this.emit("plugin.afterStart",new Date)}beforeStop(){this.emit("plugin.beforeStop",new Date)}afterStop(){this.emit("plugin.afterStop",new Date)}};const Mt={setup(t){},start(){},stop(){}};class Lt extends Tt{constructor(t={}){super(t),this.auditResource=null,this.config={includeData:!1!==t.includeData,includePartitions:!1!==t.includePartitions,maxDataSize:t.maxDataSize||1e4,...t}}async onSetup(){const[t,e,r]=await wt(()=>this.database.createResource({name:"audits",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",recordId:"string|required",userId:"string|optional",timestamp:"string|required",oldData:"string|optional",newData:"string|optional",partition:"string|optional",partitionValues:"string|optional",metadata:"string|optional"},behavior:"body-overflow"}));this.auditResource=t?r:this.database.resources.audits||null,(t||this.auditResource)&&(this.installDatabaseProxy(),this.installEventListeners())}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._auditProxyInstalled)return;const t=this.installEventListenersForResource.bind(this);this.database._originalCreateResource=this.database.createResource,this.database.createResource=async function(...e){const r=await this._originalCreateResource(...e);return"audits"!==r.name&&t(r),r},this.database._auditProxyInstalled=!0}installEventListeners(){for(const t of Object.values(this.database.resources))"audits"!==t.name&&this.installEventListenersForResource(t)}installEventListenersForResource(t){t.on("insert",async e=>{const r=e.id||"auto-generated",i=this.config.includePartitions?this.getPartitionValues(e,t):null,s={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"insert",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(e)),partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(s).catch(()=>{})}),t.on("update",async e=>{const r=e.id;let i=e.$before;if(this.config.includeData&&!i){const[e,s,n]=await wt(()=>t.get(r));e&&(i=n)}const s=this.config.includePartitions?this.getPartitionValues(e,t):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"update",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(e)),partition:this.config.includePartitions?this.getPrimaryPartition(s):null,partitionValues:this.config.includePartitions&&s&&Object.keys(s).length>0?JSON.stringify(s):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(n).catch(()=>{})}),t.on("delete",async e=>{const r=e.id;let i=e;if(this.config.includeData&&!i){const[e,s,n]=await wt(()=>t.get(r));e&&(i=n)}const s=i&&this.config.includePartitions?this.getPartitionValues(i,t):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"delete",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:i&&!1===this.config.includeData?null:i?JSON.stringify(this.truncateData(i)):null,newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(s):null,partitionValues:this.config.includePartitions&&s&&Object.keys(s).length>0?JSON.stringify(s):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(n).catch(()=>{})}),t.useMiddleware("deleteMany",async(e,r)=>{const i=e.args[0],s={};if(this.config.includeData)for(const e of i){const[r,i,n]=await wt(()=>t.get(e));s[e]=r?n:null}const n=await r();if(n&&n.length>0&&this.config.includeData)for(const e of i){const r=s[e],i=r&&this.config.includePartitions?this.getPartitionValues(r,t):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:t.name,operation:"delete",recordId:e,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(r)),newData:null,partition:this.config.includePartitions?this.getPrimaryPartition(i):null,partitionValues:this.config.includePartitions&&i&&Object.keys(i).length>0?JSON.stringify(i):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0",batchOperation:!0})};this.logAudit(n).catch(()=>{})}return n})}getPartitionValues(t,e){if(!t)return null;const r=e.config?.partitions||{},i={};for(const[e,s]of Object.entries(r))if(s.fields){const r={};for(const[e,i]of Object.entries(s.fields)){const i=this.getNestedFieldValue(t,e);null!=i&&(r[e]=i)}Object.keys(r).length>0&&(i[e]=r)}return i}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return;i=i[t]}return i}getPrimaryPartition(t){if(!t)return null;const e=Object.keys(t);return e.length>0?e[0]:null}async logAudit(t){t.id||(t.id=`audit-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return await this.auditResource.insert(t)}truncateData(t){if(!t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||"$overflow"===r||(e[r]=i);const r=JSON.stringify(e);if(r.length<=this.config.maxDataSize)return e;let i={...e},s=JSON.stringify(i).length;const n=JSON.stringify({_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}).length,a=this.config.maxDataSize-n;for(const[t,e]of Object.entries(i))if("string"==typeof e&&s>a){const r=s-a,n=Math.max(0,e.length-r-3);n<e.length&&(i[t]=e.substring(0,n)+"...",s=JSON.stringify(i).length)}return{...i,_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}}async getAuditLogs(t={}){if(!this.auditResource)return[];const[e,r,i]=await wt(async()=>{const{resourceName:e,operation:r,recordId:i,userId:s,partition:n,startDate:a,endDate:o,limit:c=100,offset:l=0}=t;let u=(await this.auditResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&((!i||t.recordId===i)&&((!s||t.userId===s)&&((!n||t.partition===n)&&(!(a&&new Date(t.timestamp)<new Date(a))&&!(o&&new Date(t.timestamp)>new Date(o))))))));u.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp));return u.slice(l,l+c).map(t=>{const[e,,r]="string"==typeof t.oldData?bt(()=>JSON.parse(t.oldData)):[!0,null,t.oldData],[i,,s]="string"==typeof t.newData?bt(()=>JSON.parse(t.newData)):[!0,null,t.newData],[n,,a]=t.partitionValues&&"string"==typeof t.partitionValues?bt(()=>JSON.parse(t.partitionValues)):[!0,null,t.partitionValues],[o,,c]=t.metadata&&"string"==typeof t.metadata?bt(()=>JSON.parse(t.metadata)):[!0,null,t.metadata];return{...t,oldData:null===t.oldData||void 0===t.oldData||"null"===t.oldData?null:e?r:null,newData:null===t.newData||void 0===t.newData||"null"===t.newData?null:i?s:null,partitionValues:n?a:t.partitionValues,metadata:o?c:t.metadata}})});return e?i:[]}async getRecordHistory(t,e){return this.getAuditLogs({resourceName:t,recordId:e,limit:1e3})}async getPartitionHistory(t,e,r){return this.getAuditLogs({resourceName:t,partition:e,limit:1e3})}async getAuditStats(t={}){const{resourceName:e,startDate:r,endDate:i}=t,s=await this.getAuditLogs({resourceName:e,startDate:r,endDate:i,limit:1e4}),n={total:s.length,byOperation:{},byResource:{},byPartition:{},byUser:{},timeline:{}};for(const t of s)if(n.byOperation[t.operation]=(n.byOperation[t.operation]||0)+1,n.byResource[t.resourceName]=(n.byResource[t.resourceName]||0)+1,t.partition&&(n.byPartition[t.partition]=(n.byPartition[t.partition]||0)+1),n.byUser[t.userId]=(n.byUser[t.userId]||0)+1,t.timestamp){const e=t.timestamp.split("T")[0];n.timeline[e]=(n.timeline[e]||0)+1}return n}}function Ut(t,e){for(var r=0,i=t.length-1;i>=0;i--){var s=t[i];"."===s?t.splice(i,1):".."===s?(t.splice(i,1),r++):r&&(t.splice(i,1),r--)}if(e)for(;r--;r)t.unshift("..");return t}var Ft=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,qt=function(t){return Ft.exec(t).slice(1)};function Bt(){for(var t="",e=!1,r=arguments.length-1;r>=-1&&!e;r--){var i=r>=0?arguments[r]:"/";if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");i&&(t=i+"/"+t,e="/"===i.charAt(0))}return(e?"/":"")+(t=Ut(Jt(t.split("/"),function(t){return!!t}),!e).join("/"))||"."}function zt(t){var e=Vt(t),r="/"===Ht(t,-1);return(t=Ut(Jt(t.split("/"),function(t){return!!t}),!e).join("/"))||e||(t="."),t&&r&&(t+="/"),(e?"/":"")+t}function Vt(t){return"/"===t.charAt(0)}function Kt(){return zt(Jt(Array.prototype.slice.call(arguments,0),function(t,e){if("string"!=typeof t)throw new TypeError("Arguments to path.join must be strings");return t}).join("/"))}var Wt={extname:function(t){return qt(t)[3]},basename:function(t,e){var r=qt(t)[2];return e&&r.substr(-1*e.length)===e&&(r=r.substr(0,r.length-e.length)),r},dirname:function(t){var e=qt(t),r=e[0],i=e[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},sep:"/",delimiter:":",relative:function(t,e){function r(t){for(var e=0;e<t.length&&""===t[e];e++);for(var r=t.length-1;r>=0&&""===t[r];r--);return e>r?[]:t.slice(e,r-e+1)}t=Bt(t).substr(1),e=Bt(e).substr(1);for(var i=r(t.split("/")),s=r(e.split("/")),n=Math.min(i.length,s.length),a=n,o=0;o<n;o++)if(i[o]!==s[o]){a=o;break}var c=[];for(o=a;o<i.length;o++)c.push("..");return(c=c.concat(s.slice(a))).join("/")},join:Kt,isAbsolute:Vt,normalize:zt,resolve:Bt};function Jt(t,e){if(t.filter)return t.filter(e);for(var r=[],i=0;i<t.length;i++)e(t[i],i,t)&&r.push(t[i]);return r}var Ht="b"==="ab".substr(-1)?function(t,e,r){return t.substr(e,r)}:function(t,e,r){return e<0&&(e=t.length+e),t.substr(e,r)};class Yt extends At{constructor(t={}){super(),this.config=t}async _set(t,e){}async _get(t){}async _del(t){}async _clear(t){}validateKey(t){if(null==t||"string"!=typeof t||!t)throw new Error("Invalid key")}async set(t,e){return this.validateKey(t),await this._set(t,e),this.emit("set",e),e}async get(t){this.validateKey(t);const e=await this._get(t);return this.emit("get",e),e}async del(t){this.validateKey(t);const e=await this._del(t);return this.emit("delete",e),e}async delete(t){return this.del(t)}async clear(t){const e=await this._clear(t);return this.emit("clear",e),e}}function Gt(){throw new Error("setTimeout has not been defined")}function Qt(){throw new Error("clearTimeout has not been defined")}var Xt=Gt,Zt=Qt;function te(t){if(Xt===setTimeout)return setTimeout(t,0);if((Xt===Gt||!Xt)&&setTimeout)return Xt=setTimeout,setTimeout(t,0);try{return Xt(t,0)}catch(e){try{return Xt.call(null,t,0)}catch(e){return Xt.call(this,t,0)}}}"function"==typeof global.setTimeout&&(Xt=setTimeout),"function"==typeof global.clearTimeout&&(Zt=clearTimeout);var ee,re=[],ie=!1,se=-1;function ne(){ie&&ee&&(ie=!1,ee.length?re=ee.concat(re):se=-1,re.length&&ae())}function ae(){if(!ie){var t=te(ne);ie=!0;for(var e=re.length;e;){for(ee=re,re=[];++se<e;)ee&&ee[se].run();se=-1,e=re.length}ee=null,ie=!1,function(t){if(Zt===clearTimeout)return clearTimeout(t);if((Zt===Qt||!Zt)&&clearTimeout)return Zt=clearTimeout,clearTimeout(t);try{return Zt(t)}catch(e){try{return Zt.call(null,t)}catch(e){return Zt.call(this,t)}}}(t)}}function oe(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];re.push(new ce(t,e)),1!==re.length||ie||te(ae)}function ce(t,e){this.fun=t,this.array=e}ce.prototype.run=function(){this.fun.apply(null,this.array)};var le,ue={env:{}};le="function"==typeof Object.create?function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t};var he=/%[sdj%]/g;function fe(t){if(!Oe(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(me(arguments[r]));return e.join(" ")}r=1;for(var i=arguments,s=i.length,n=String(t).replace(he,function(t){if("%%"===t)return"%";if(r>=s)return t;switch(t){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(t){return"[Circular]"}default:return t}}),a=i[r];r<s;a=i[++r])ke(a)||!xe(a)?n+=" "+a:n+=" "+me(a);return n}function de(t,e){if(Re(global.process))return function(){return de(t,e).apply(this,arguments)};if(!0===ue.noDeprecation)return t;var r=!1;return function(){if(!r){if(ue.throwDeprecation)throw new Error(e);ue.traceDeprecation?console.trace(e):console.error(e),r=!0}return t.apply(this,arguments)}}var pe,ge={};function me(t,e){var r={seen:[],stylize:be};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),_e(e)?r.showHidden=e:e&&function(t,e){if(!e||!xe(e))return t;var r=Object.keys(e),i=r.length;for(;i--;)t[r[i]]=e[r[i]]}(r,e),Re(r.showHidden)&&(r.showHidden=!1),Re(r.depth)&&(r.depth=2),Re(r.colors)&&(r.colors=!1),Re(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=ye),we(r,t,r.depth)}function ye(t,e){var r=me.styles[e];return r?"["+me.colors[r][0]+"m"+t+"["+me.colors[r][1]+"m":t}function be(t,e){return t}function we(t,e,r){if(t.customInspect&&e&&Ae(e.inspect)&&e.inspect!==me&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(r,t);return Oe(i)||(i=we(t,i,r)),i}var s=function(t,e){if(Re(e))return t.stylize("undefined","undefined");if(Oe(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(i=e,"number"==typeof i)return t.stylize(""+e,"number");var i;if(_e(e))return t.stylize(""+e,"boolean");if(ke(e))return t.stylize("null","null")}(t,e);if(s)return s;var n=Object.keys(e),a=function(t){var e={};return t.forEach(function(t,r){e[t]=!0}),e}(n);if(t.showHidden&&(n=Object.getOwnPropertyNames(e)),De(e)&&(n.indexOf("message")>=0||n.indexOf("description")>=0))return ve(e);if(0===n.length){if(Ae(e)){var o=e.name?": "+e.name:"";return t.stylize("[Function"+o+"]","special")}if(je(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(Ee(e))return t.stylize(Date.prototype.toString.call(e),"date");if(De(e))return ve(e)}var c,l,u="",h=!1,f=["{","}"];(c=e,Array.isArray(c)&&(h=!0,f=["[","]"]),Ae(e))&&(u=" [Function"+(e.name?": "+e.name:"")+"]");return je(e)&&(u=" "+RegExp.prototype.toString.call(e)),Ee(e)&&(u=" "+Date.prototype.toUTCString.call(e)),De(e)&&(u=" "+ve(e)),0!==n.length||h&&0!=e.length?r<0?je(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),l=h?function(t,e,r,i,s){for(var n=[],a=0,o=e.length;a<o;++a)Ie(e,String(a))?n.push(Se(t,e,r,i,String(a),!0)):n.push("");return s.forEach(function(s){s.match(/^\d+$/)||n.push(Se(t,e,r,i,s,!0))}),n}(t,e,r,a,n):n.map(function(i){return Se(t,e,r,a,i,h)}),t.seen.pop(),function(t,e,r){var i=t.reduce(function(t,e){return e.indexOf("\n"),t+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(i>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(l,u,f)):f[0]+u+f[1]}function ve(t){return"["+Error.prototype.toString.call(t)+"]"}function Se(t,e,r,i,s,n){var a,o,c;if((c=Object.getOwnPropertyDescriptor(e,s)||{value:e[s]}).get?o=c.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):c.set&&(o=t.stylize("[Setter]","special")),Ie(i,s)||(a="["+s+"]"),o||(t.seen.indexOf(c.value)<0?(o=ke(r)?we(t,c.value,null):we(t,c.value,r-1)).indexOf("\n")>-1&&(o=n?o.split("\n").map(function(t){return" "+t}).join("\n").substr(2):"\n"+o.split("\n").map(function(t){return" "+t}).join("\n")):o=t.stylize("[Circular]","special")),Re(a)){if(n&&s.match(/^\d+$/))return o;(a=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+o}function _e(t){return"boolean"==typeof t}function ke(t){return null===t}function Oe(t){return"string"==typeof t}function Re(t){return void 0===t}function je(t){return xe(t)&&"[object RegExp]"===Ne(t)}function xe(t){return"object"==typeof t&&null!==t}function Ee(t){return xe(t)&&"[object Date]"===Ne(t)}function De(t){return xe(t)&&("[object Error]"===Ne(t)||t instanceof Error)}function Ae(t){return"function"==typeof t}function Ne(t){return Object.prototype.toString.call(t)}function Ie(t,e){return Object.prototype.hasOwnProperty.call(t,e)}me.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},me.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var $e=[],Pe=[],Ce="undefined"!=typeof Uint8Array?Uint8Array:Array,Te=!1;function Me(){Te=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0;e<64;++e)$e[e]=t[e],Pe[t.charCodeAt(e)]=e;Pe["-".charCodeAt(0)]=62,Pe["_".charCodeAt(0)]=63}function Le(t){return $e[t>>18&63]+$e[t>>12&63]+$e[t>>6&63]+$e[63&t]}function Ue(t,e,r){for(var i,s=[],n=e;n<r;n+=3)i=(t[n]<<16)+(t[n+1]<<8)+t[n+2],s.push(Le(i));return s.join("")}function Fe(t){var e;Te||Me();for(var r=t.length,i=r%3,s="",n=[],a=16383,o=0,c=r-i;o<c;o+=a)n.push(Ue(t,o,o+a>c?c:o+a));return 1===i?(e=t[r-1],s+=$e[e>>2],s+=$e[e<<4&63],s+="=="):2===i&&(e=(t[r-2]<<8)+t[r-1],s+=$e[e>>10],s+=$e[e>>4&63],s+=$e[e<<2&63],s+="="),n.push(s),n.join("")}function qe(t,e,r,i,s){var n,a,o=8*s-i-1,c=(1<<o)-1,l=c>>1,u=-7,h=r?s-1:0,f=r?-1:1,d=t[e+h];for(h+=f,n=d&(1<<-u)-1,d>>=-u,u+=o;u>0;n=256*n+t[e+h],h+=f,u-=8);for(a=n&(1<<-u)-1,n>>=-u,u+=i;u>0;a=256*a+t[e+h],h+=f,u-=8);if(0===n)n=1-l;else{if(n===c)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,i),n-=l}return(d?-1:1)*a*Math.pow(2,n-i)}function Be(t,e,r,i,s,n){var a,o,c,l=8*n-s-1,u=(1<<l)-1,h=u>>1,f=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,p=i?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=u):(a=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-a))<1&&(a--,c*=2),(e+=a+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(a++,c/=2),a+h>=u?(o=0,a=u):a+h>=1?(o=(e*c-1)*Math.pow(2,s),a+=h):(o=e*Math.pow(2,h-1)*Math.pow(2,s),a=0));s>=8;t[r+d]=255&o,d+=p,o/=256,s-=8);for(a=a<<s|o,l+=s;l>0;t[r+d]=255&a,d+=p,a/=256,l-=8);t[r+d-p]|=128*g}var ze={}.toString,Ve=Array.isArray||function(t){return"[object Array]"==ze.call(t)};function Ke(){return Je.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function We(t,e){if(Ke()<e)throw new RangeError("Invalid typed array length");return Je.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=Je.prototype:(null===t&&(t=new Je(e)),t.length=e),t}function Je(t,e,r){if(!(Je.TYPED_ARRAY_SUPPORT||this instanceof Je))return new Je(t,e,r);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return Ge(this,t)}return He(this,t,e,r)}function He(t,e,r,i){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,r,i){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(i||0))throw new RangeError("'length' is out of bounds");e=void 0===r&&void 0===i?new Uint8Array(e):void 0===i?new Uint8Array(e,r):new Uint8Array(e,r,i);Je.TYPED_ARRAY_SUPPORT?(t=e).__proto__=Je.prototype:t=Qe(t,e);return t}(t,e,r,i):"string"==typeof e?function(t,e,r){"string"==typeof r&&""!==r||(r="utf8");if(!Je.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|tr(e,r);t=We(t,i);var s=t.write(e,r);s!==i&&(t=t.slice(0,s));return t}(t,e,r):function(t,e){if(Ze(e)){var r=0|Xe(e.length);return 0===(t=We(t,r)).length||e.copy(t,0,0,r),t}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(i=e.length)!=i?We(t,0):Qe(t,e);if("Buffer"===e.type&&Ve(e.data))return Qe(t,e.data)}var i;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function Ye(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function Ge(t,e){if(Ye(e),t=We(t,e<0?0:0|Xe(e)),!Je.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function Qe(t,e){var r=e.length<0?0:0|Xe(e.length);t=We(t,r);for(var i=0;i<r;i+=1)t[i]=255&e[i];return t}function Xe(t){if(t>=Ke())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ke().toString(16)+" bytes");return 0|t}function Ze(t){return!(null==t||!t._isBuffer)}function tr(t,e){if(Ze(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return xr(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Er(t).length;default:if(i)return xr(t).length;e=(""+e).toLowerCase(),i=!0}}function er(t,e,r){var i=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return mr(this,e,r);case"utf8":case"utf-8":return fr(this,e,r);case"ascii":return pr(this,e,r);case"latin1":case"binary":return gr(this,e,r);case"base64":return hr(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return yr(this,e,r);default:if(i)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),i=!0}}function rr(t,e,r){var i=t[e];t[e]=t[r],t[r]=i}function ir(t,e,r,i,s){if(0===t.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=s?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(s)return-1;r=t.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof e&&(e=Je.from(e,i)),Ze(e))return 0===e.length?-1:sr(t,e,r,i,s);if("number"==typeof e)return e&=255,Je.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):sr(t,[e],r,i,s);throw new TypeError("val must be string, number or Buffer")}function sr(t,e,r,i,s){var n,a=1,o=t.length,c=e.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(t.length<2||e.length<2)return-1;a=2,o/=2,c/=2,r/=2}function l(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}if(s){var u=-1;for(n=r;n<o;n++)if(l(t,n)===l(e,-1===u?0:n-u)){if(-1===u&&(u=n),n-u+1===c)return u*a}else-1!==u&&(n-=n-u),u=-1}else for(r+c>o&&(r=o-c),n=r;n>=0;n--){for(var h=!0,f=0;f<c;f++)if(l(t,n+f)!==l(e,f)){h=!1;break}if(h)return n}return-1}function nr(t,e,r,i){r=Number(r)||0;var s=t.length-r;i?(i=Number(i))>s&&(i=s):i=s;var n=e.length;if(n%2!=0)throw new TypeError("Invalid hex string");i>n/2&&(i=n/2);for(var a=0;a<i;++a){var o=parseInt(e.substr(2*a,2),16);if(isNaN(o))return a;t[r+a]=o}return a}function ar(t,e,r,i){return Dr(xr(e,t.length-r),t,r,i)}function or(t,e,r,i){return Dr(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,i)}function cr(t,e,r,i){return or(t,e,r,i)}function lr(t,e,r,i){return Dr(Er(e),t,r,i)}function ur(t,e,r,i){return Dr(function(t,e){for(var r,i,s,n=[],a=0;a<t.length&&!((e-=2)<0);++a)i=(r=t.charCodeAt(a))>>8,s=r%256,n.push(s),n.push(i);return n}(e,t.length-r),t,r,i)}function hr(t,e,r){return 0===e&&r===t.length?Fe(t):Fe(t.slice(e,r))}function fr(t,e,r){r=Math.min(t.length,r);for(var i=[],s=e;s<r;){var n,a,o,c,l=t[s],u=null,h=l>239?4:l>223?3:l>191?2:1;if(s+h<=r)switch(h){case 1:l<128&&(u=l);break;case 2:128==(192&(n=t[s+1]))&&(c=(31&l)<<6|63&n)>127&&(u=c);break;case 3:n=t[s+1],a=t[s+2],128==(192&n)&&128==(192&a)&&(c=(15&l)<<12|(63&n)<<6|63&a)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:n=t[s+1],a=t[s+2],o=t[s+3],128==(192&n)&&128==(192&a)&&128==(192&o)&&(c=(15&l)<<18|(63&n)<<12|(63&a)<<6|63&o)>65535&&c<1114112&&(u=c)}null===u?(u=65533,h=1):u>65535&&(u-=65536,i.push(u>>>10&1023|55296),u=56320|1023&u),i.push(u),s+=h}return function(t){var e=t.length;if(e<=dr)return String.fromCharCode.apply(String,t);var r="",i=0;for(;i<e;)r+=String.fromCharCode.apply(String,t.slice(i,i+=dr));return r}(i)}Je.TYPED_ARRAY_SUPPORT=void 0===global.TYPED_ARRAY_SUPPORT||global.TYPED_ARRAY_SUPPORT,Ke(),Je.poolSize=8192,Je._augment=function(t){return t.__proto__=Je.prototype,t},Je.from=function(t,e,r){return He(null,t,e,r)},Je.TYPED_ARRAY_SUPPORT&&(Je.prototype.__proto__=Uint8Array.prototype,Je.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Je[Symbol.species]),Je.alloc=function(t,e,r){return function(t,e,r,i){return Ye(e),e<=0?We(t,e):void 0!==r?"string"==typeof i?We(t,e).fill(r,i):We(t,e).fill(r):We(t,e)}(null,t,e,r)},Je.allocUnsafe=function(t){return Ge(null,t)},Je.allocUnsafeSlow=function(t){return Ge(null,t)},Je.isBuffer=function(t){return null!=t&&(!!t._isBuffer||Ar(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&Ar(t.slice(0,0))}(t))},Je.compare=function(t,e){if(!Ze(t)||!Ze(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,i=e.length,s=0,n=Math.min(r,i);s<n;++s)if(t[s]!==e[s]){r=t[s],i=e[s];break}return r<i?-1:i<r?1:0},Je.isEncoding=function(t){switch(String(t).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}},Je.concat=function(t,e){if(!Ve(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return Je.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var i=Je.allocUnsafe(e),s=0;for(r=0;r<t.length;++r){var n=t[r];if(!Ze(n))throw new TypeError('"list" argument must be an Array of Buffers');n.copy(i,s),s+=n.length}return i},Je.byteLength=tr,Je.prototype._isBuffer=!0,Je.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)rr(this,e,e+1);return this},Je.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)rr(this,e,e+3),rr(this,e+1,e+2);return this},Je.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)rr(this,e,e+7),rr(this,e+1,e+6),rr(this,e+2,e+5),rr(this,e+3,e+4);return this},Je.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?fr(this,0,t):er.apply(this,arguments)},Je.prototype.equals=function(t){if(!Ze(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Je.compare(this,t)},Je.prototype.inspect=function(){var t="";return this.length>0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),"<Buffer "+t+">"},Je.prototype.compare=function(t,e,r,i,s){if(!Ze(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),e<0||r>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&e>=r)return 0;if(i>=s)return-1;if(e>=r)return 1;if(this===t)return 0;for(var n=(s>>>=0)-(i>>>=0),a=(r>>>=0)-(e>>>=0),o=Math.min(n,a),c=this.slice(i,s),l=t.slice(e,r),u=0;u<o;++u)if(c[u]!==l[u]){n=c[u],a=l[u];break}return n<a?-1:a<n?1:0},Je.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},Je.prototype.indexOf=function(t,e,r){return ir(this,t,e,r,!0)},Je.prototype.lastIndexOf=function(t,e,r){return ir(this,t,e,r,!1)},Je.prototype.write=function(t,e,r,i){if(void 0===e)i="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)i=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(r)?(r|=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var s=this.length-e;if((void 0===r||r>s)&&(r=s),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var n=!1;;)switch(i){case"hex":return nr(this,t,e,r);case"utf8":case"utf-8":return ar(this,t,e,r);case"ascii":return or(this,t,e,r);case"latin1":case"binary":return cr(this,t,e,r);case"base64":return lr(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ur(this,t,e,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},Je.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var dr=4096;function pr(t,e,r){var i="";r=Math.min(t.length,r);for(var s=e;s<r;++s)i+=String.fromCharCode(127&t[s]);return i}function gr(t,e,r){var i="";r=Math.min(t.length,r);for(var s=e;s<r;++s)i+=String.fromCharCode(t[s]);return i}function mr(t,e,r){var i=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>i)&&(r=i);for(var s="",n=e;n<r;++n)s+=jr(t[n]);return s}function yr(t,e,r){for(var i=t.slice(e,r),s="",n=0;n<i.length;n+=2)s+=String.fromCharCode(i[n]+256*i[n+1]);return s}function br(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function wr(t,e,r,i,s,n){if(!Ze(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>s||e<n)throw new RangeError('"value" argument is out of bounds');if(r+i>t.length)throw new RangeError("Index out of range")}function vr(t,e,r,i){e<0&&(e=65535+e+1);for(var s=0,n=Math.min(t.length-r,2);s<n;++s)t[r+s]=(e&255<<8*(i?s:1-s))>>>8*(i?s:1-s)}function Sr(t,e,r,i){e<0&&(e=4294967295+e+1);for(var s=0,n=Math.min(t.length-r,4);s<n;++s)t[r+s]=e>>>8*(i?s:3-s)&255}function _r(t,e,r,i,s,n){if(r+i>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function kr(t,e,r,i,s){return s||_r(t,0,r,4),Be(t,e,r,i,23,4),r+4}function Or(t,e,r,i,s){return s||_r(t,0,r,8),Be(t,e,r,i,52,8),r+8}Je.prototype.slice=function(t,e){var r,i=this.length;if((t=~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),(e=void 0===e?i:~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t),Je.TYPED_ARRAY_SUPPORT)(r=this.subarray(t,e)).__proto__=Je.prototype;else{var s=e-t;r=new Je(s,void 0);for(var n=0;n<s;++n)r[n]=this[n+t]}return r},Je.prototype.readUIntLE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=this[t],s=1,n=0;++n<e&&(s*=256);)i+=this[t+n]*s;return i},Je.prototype.readUIntBE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=this[t+--e],s=1;e>0&&(s*=256);)i+=this[t+--e]*s;return i},Je.prototype.readUInt8=function(t,e){return e||br(t,1,this.length),this[t]},Je.prototype.readUInt16LE=function(t,e){return e||br(t,2,this.length),this[t]|this[t+1]<<8},Je.prototype.readUInt16BE=function(t,e){return e||br(t,2,this.length),this[t]<<8|this[t+1]},Je.prototype.readUInt32LE=function(t,e){return e||br(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Je.prototype.readUInt32BE=function(t,e){return e||br(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Je.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=this[t],s=1,n=0;++n<e&&(s*=256);)i+=this[t+n]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*e)),i},Je.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||br(t,e,this.length);for(var i=e,s=1,n=this[t+--i];i>0&&(s*=256);)n+=this[t+--i]*s;return n>=(s*=128)&&(n-=Math.pow(2,8*e)),n},Je.prototype.readInt8=function(t,e){return e||br(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Je.prototype.readInt16LE=function(t,e){e||br(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},Je.prototype.readInt16BE=function(t,e){e||br(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},Je.prototype.readInt32LE=function(t,e){return e||br(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Je.prototype.readInt32BE=function(t,e){return e||br(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Je.prototype.readFloatLE=function(t,e){return e||br(t,4,this.length),qe(this,t,!0,23,4)},Je.prototype.readFloatBE=function(t,e){return e||br(t,4,this.length),qe(this,t,!1,23,4)},Je.prototype.readDoubleLE=function(t,e){return e||br(t,8,this.length),qe(this,t,!0,52,8)},Je.prototype.readDoubleBE=function(t,e){return e||br(t,8,this.length),qe(this,t,!1,52,8)},Je.prototype.writeUIntLE=function(t,e,r,i){(t=+t,e|=0,r|=0,i)||wr(this,t,e,r,Math.pow(2,8*r)-1,0);var s=1,n=0;for(this[e]=255&t;++n<r&&(s*=256);)this[e+n]=t/s&255;return e+r},Je.prototype.writeUIntBE=function(t,e,r,i){(t=+t,e|=0,r|=0,i)||wr(this,t,e,r,Math.pow(2,8*r)-1,0);var s=r-1,n=1;for(this[e+s]=255&t;--s>=0&&(n*=256);)this[e+s]=t/n&255;return e+r},Je.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,1,255,0),Je.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Je.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,65535,0),Je.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):vr(this,t,e,!0),e+2},Je.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,65535,0),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):vr(this,t,e,!1),e+2},Je.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,4294967295,0),Je.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):Sr(this,t,e,!0),e+4},Je.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,4294967295,0),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Sr(this,t,e,!1),e+4},Je.prototype.writeIntLE=function(t,e,r,i){if(t=+t,e|=0,!i){var s=Math.pow(2,8*r-1);wr(this,t,e,r,s-1,-s)}var n=0,a=1,o=0;for(this[e]=255&t;++n<r&&(a*=256);)t<0&&0===o&&0!==this[e+n-1]&&(o=1),this[e+n]=(t/a|0)-o&255;return e+r},Je.prototype.writeIntBE=function(t,e,r,i){if(t=+t,e|=0,!i){var s=Math.pow(2,8*r-1);wr(this,t,e,r,s-1,-s)}var n=r-1,a=1,o=0;for(this[e+n]=255&t;--n>=0&&(a*=256);)t<0&&0===o&&0!==this[e+n+1]&&(o=1),this[e+n]=(t/a|0)-o&255;return e+r},Je.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,1,127,-128),Je.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Je.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,32767,-32768),Je.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):vr(this,t,e,!0),e+2},Je.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,2,32767,-32768),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):vr(this,t,e,!1),e+2},Je.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,2147483647,-2147483648),Je.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):Sr(this,t,e,!0),e+4},Je.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||wr(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Je.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):Sr(this,t,e,!1),e+4},Je.prototype.writeFloatLE=function(t,e,r){return kr(this,t,e,!0,r)},Je.prototype.writeFloatBE=function(t,e,r){return kr(this,t,e,!1,r)},Je.prototype.writeDoubleLE=function(t,e,r){return Or(this,t,e,!0,r)},Je.prototype.writeDoubleBE=function(t,e,r){return Or(this,t,e,!1,r)},Je.prototype.copy=function(t,e,r,i){if(r||(r=0),i||0===i||(i=this.length),e>=t.length&&(e=t.length),e||(e=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-e<i-r&&(i=t.length-e+r);var s,n=i-r;if(this===t&&r<e&&e<i)for(s=n-1;s>=0;--s)t[s+e]=this[s+r];else if(n<1e3||!Je.TYPED_ARRAY_SUPPORT)for(s=0;s<n;++s)t[s+e]=this[s+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+n),e);return n},Je.prototype.fill=function(t,e,r,i){if("string"==typeof t){if("string"==typeof e?(i=e,e=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),1===t.length){var s=t.charCodeAt(0);s<256&&(t=s)}if(void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!Je.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;var n;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(n=e;n<r;++n)this[n]=t;else{var a=Ze(t)?t:xr(new Je(t,i).toString()),o=a.length;for(n=0;n<r-e;++n)this[n+e]=a[n%o]}return this};var Rr=/[^+\/0-9A-Za-z-_]/g;function jr(t){return t<16?"0"+t.toString(16):t.toString(16)}function xr(t,e){var r;e=e||1/0;for(var i=t.length,s=null,n=[],a=0;a<i;++a){if((r=t.charCodeAt(a))>55295&&r<57344){if(!s){if(r>56319){(e-=3)>-1&&n.push(239,191,189);continue}if(a+1===i){(e-=3)>-1&&n.push(239,191,189);continue}s=r;continue}if(r<56320){(e-=3)>-1&&n.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(e-=3)>-1&&n.push(239,191,189);if(s=null,r<128){if((e-=1)<0)break;n.push(r)}else if(r<2048){if((e-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;n.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function Er(t){return function(t){var e,r,i,s,n,a;Te||Me();var o=t.length;if(o%4>0)throw new Error("Invalid string. Length must be a multiple of 4");n="="===t[o-2]?2:"="===t[o-1]?1:0,a=new Ce(3*o/4-n),i=n>0?o-4:o;var c=0;for(e=0,r=0;e<i;e+=4,r+=3)s=Pe[t.charCodeAt(e)]<<18|Pe[t.charCodeAt(e+1)]<<12|Pe[t.charCodeAt(e+2)]<<6|Pe[t.charCodeAt(e+3)],a[c++]=s>>16&255,a[c++]=s>>8&255,a[c++]=255&s;return 2===n?(s=Pe[t.charCodeAt(e)]<<2|Pe[t.charCodeAt(e+1)]>>4,a[c++]=255&s):1===n&&(s=Pe[t.charCodeAt(e)]<<10|Pe[t.charCodeAt(e+1)]<<4|Pe[t.charCodeAt(e+2)]>>2,a[c++]=s>>8&255,a[c++]=255&s),a}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(Rr,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Dr(t,e,r,i){for(var s=0;s<i&&!(s+r>=e.length||s>=t.length);++s)e[s+r]=t[s];return s}function Ar(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}function Nr(){this.head=null,this.tail=null,this.length=0}Nr.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},Nr.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},Nr.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},Nr.prototype.clear=function(){this.head=this.tail=null,this.length=0},Nr.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},Nr.prototype.concat=function(t){if(0===this.length)return Je.alloc(0);if(1===this.length)return this.head.data;for(var e=Je.allocUnsafe(t>>>0),r=this.head,i=0;r;)r.data.copy(e,i),i+=r.data.length,r=r.next;return e};var Ir=Je.isEncoding||function(t){switch(t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function $r(t){switch(this.encoding=(t||"utf8").toLowerCase().replace(/[-_]/,""),function(t){if(t&&!Ir(t))throw new Error("Unknown encoding: "+t)}(t),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Cr;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Tr;break;default:return void(this.write=Pr)}this.charBuffer=new Je(6),this.charReceived=0,this.charLength=0}function Pr(t){return t.toString(this.encoding)}function Cr(t){this.charReceived=t.length%2,this.charLength=this.charReceived?2:0}function Tr(t){this.charReceived=t.length%3,this.charLength=this.charReceived?3:0}$r.prototype.write=function(t){for(var e="";this.charLength;){var r=t.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:t.length;if(t.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";if(t=t.slice(r,t.length),!((s=(e=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(e.length-1))>=55296&&s<=56319)){if(this.charReceived=this.charLength=0,0===t.length)return e;break}this.charLength+=this.surrogateSize,e=""}this.detectIncompleteChar(t);var i=t.length;this.charLength&&(t.copy(this.charBuffer,0,t.length-this.charReceived,i),i-=this.charReceived);var s;i=(e+=t.toString(this.encoding,0,i)).length-1;if((s=e.charCodeAt(i))>=55296&&s<=56319){var n=this.surrogateSize;return this.charLength+=n,this.charReceived+=n,this.charBuffer.copy(this.charBuffer,n,0,n),t.copy(this.charBuffer,0,0,n),e.substring(0,i)}return e},$r.prototype.detectIncompleteChar=function(t){for(var e=t.length>=3?3:t.length;e>0;e--){var r=t[t.length-e];if(1==e&&r>>5==6){this.charLength=2;break}if(e<=2&&r>>4==14){this.charLength=3;break}if(e<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=e},$r.prototype.end=function(t){var e="";if(t&&t.length&&(e=this.write(t)),this.charReceived){var r=this.charReceived,i=this.charBuffer,s=this.encoding;e+=i.slice(0,r).toString(s)}return e},Ur.ReadableState=Lr;var Mr=function(t){if(Re(pe)&&(pe=ue.env.NODE_DEBUG||""),t=t.toUpperCase(),!ge[t])if(new RegExp("\\b"+t+"\\b","i").test(pe)){ge[t]=function(){var e=fe.apply(null,arguments);console.error("%s %d: %s",t,0,e)}}else ge[t]=function(){};return ge[t]}("stream");function Lr(t,e){t=t||{},this.objectMode=!!t.objectMode,e instanceof di&&(this.objectMode=this.objectMode||!!t.readableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=new Nr,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(this.decoder=new $r(t.encoding),this.encoding=t.encoding)}function Ur(t){if(!(this instanceof Ur))return new Ur(t);this._readableState=new Lr(t,this),this.readable=!0,t&&"function"==typeof t.read&&(this._read=t.read),At.call(this)}function Fr(t,e,r,i,s){var n=function(t,e){var r=null;Buffer.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(n)t.emit("error",n);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,zr(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!s){var a=new Error("stream.push() after EOF");t.emit("error",a)}else if(e.endEmitted&&s){var o=new Error("stream.unshift() after end event");t.emit("error",o)}else{var c;!e.decoder||s||i||(r=e.decoder.write(r),c=!e.objectMode&&0===r.length),s||(e.reading=!1),c||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,s?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&zr(t))),function(t,e){e.readingMore||(e.readingMore=!0,oe(Kr,t,e))}(t,e)}else s||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(e)}le(Ur,At),Ur.prototype.push=function(t,e){var r=this._readableState;return r.objectMode||"string"!=typeof t||(e=e||r.defaultEncoding)!==r.encoding&&(t=Buffer.from(t,e),e=""),Fr(this,r,t,e,!1)},Ur.prototype.unshift=function(t){return Fr(this,this._readableState,t,"",!0)},Ur.prototype.isPaused=function(){return!1===this._readableState.flowing},Ur.prototype.setEncoding=function(t){return this._readableState.decoder=new $r(t),this._readableState.encoding=t,this};var qr=8388608;function Br(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=qr?t=qr:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function zr(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(Mr("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?oe(Vr,t):Vr(t))}function Vr(t){Mr("emit readable"),t.emit("readable"),Hr(t)}function Kr(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(Mr("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function Wr(t){Mr("readable nexttick read 0"),t.read(0)}function Jr(t,e){e.reading||(Mr("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),Hr(t),e.flowing&&!e.reading&&t.read(0)}function Hr(t){var e=t._readableState;for(Mr("flow",e.flowing);e.flowing&&null!==t.read(););}function Yr(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var i;t<e.head.data.length?(i=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):i=t===e.head.data.length?e.shift():r?function(t,e){var r=e.head,i=1,s=r.data;t-=s.length;for(;r=r.next;){var n=r.data,a=t>n.length?n.length:t;if(a===n.length?s+=n:s+=n.slice(0,t),0===(t-=a)){a===n.length?(++i,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=n.slice(a));break}++i}return e.length-=i,s}(t,e):function(t,e){var r=Buffer.allocUnsafe(t),i=e.head,s=1;i.data.copy(r),t-=i.data.length;for(;i=i.next;){var n=i.data,a=t>n.length?n.length:t;if(n.copy(r,r.length-t,0,a),0===(t-=a)){a===n.length?(++s,i.next?e.head=i.next:e.head=e.tail=null):(e.head=i,i.data=n.slice(a));break}++s}return e.length-=s,r}(t,e);return i}(t,e.buffer,e.decoder),r);var r}function Gr(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,oe(Qr,e,t))}function Qr(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function Xr(t,e){for(var r=0,i=t.length;r<i;r++)if(t[r]===e)return r;return-1}function Zr(){}function ti(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function ei(t,e){Object.defineProperty(this,"buffer",{get:de(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),t=t||{},this.objectMode=!!t.objectMode,e instanceof di&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var r=t.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var s=!1===t.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,i=r.sync,s=r.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,i,s){--e.pendingcb,r?oe(s,i):s(i);t._writableState.errorEmitted=!0,t.emit("error",i)}(t,r,i,e,s);else{var n=ai(r);n||r.corked||r.bufferProcessing||!r.bufferedRequest||ni(t,r),i?oe(si,t,r,n,s):si(t,r,n,s)}}(e,t)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new li(this)}function ri(t){if(!(this instanceof ri||this instanceof di))return new ri(t);this._writableState=new ei(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev)),At.call(this)}function ii(t,e,r,i,s,n,a){e.writelen=i,e.writecb=a,e.writing=!0,e.sync=!0,r?t._writev(s,e.onwrite):t._write(s,n,e.onwrite),e.sync=!1}function si(t,e,r,i){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,i(),ci(t,e)}function ni(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var i=e.bufferedRequestCount,s=new Array(i),n=e.corkedRequestsFree;n.entry=r;for(var a=0;r;)s[a]=r,r=r.next,a+=1;ii(t,e,!0,e.length,s,"",n.finish),e.pendingcb++,e.lastBufferedRequest=null,n.next?(e.corkedRequestsFree=n.next,n.next=null):e.corkedRequestsFree=new li(e)}else{for(;r;){var o=r.chunk,c=r.encoding,l=r.callback;if(ii(t,e,!1,e.objectMode?1:o.length,o,c,l),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function ai(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function oi(t,e){e.prefinished||(e.prefinished=!0,t.emit("prefinish"))}function ci(t,e){var r=ai(e);return r&&(0===e.pendingcb?(oi(t,e),e.finished=!0,t.emit("finish")):oi(t,e)),r}function li(t){var e=this;this.next=null,this.entry=null,this.finish=function(r){var i=e.entry;for(e.entry=null;i;){var s=i.callback;t.pendingcb--,s(r),i=i.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}}Ur.prototype.read=function(t){Mr("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return Mr("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?Gr(this):zr(this),null;if(0===(t=Br(t,e))&&e.ended)return 0===e.length&&Gr(this),null;var i,s=e.needReadable;return Mr("need readable",s),(0===e.length||e.length-t<e.highWaterMark)&&Mr("length less than watermark",s=!0),e.ended||e.reading?Mr("reading or ended",s=!1):s&&(Mr("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=Br(r,e))),null===(i=t>0?Yr(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Gr(this)),null!==i&&this.emit("data",i),i},Ur.prototype._read=function(t){this.emit("error",new Error("not implemented"))},Ur.prototype.pipe=function(t,e){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=t;break;case 1:i.pipes=[i.pipes,t];break;default:i.pipes.push(t)}i.pipesCount+=1,Mr("pipe count=%d opts=%j",i.pipesCount,e);var s=!e||!1!==e.end?a:l;function n(t){Mr("onunpipe"),t===r&&l()}function a(){Mr("onend"),t.end()}i.endEmitted?oe(s):r.once("end",s),t.on("unpipe",n);var o=function(t){return function(){var e=t._readableState;Mr("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&t.listeners("data").length&&(e.flowing=!0,Hr(t))}}(r);t.on("drain",o);var c=!1;function l(){Mr("cleanup"),t.removeListener("close",d),t.removeListener("finish",p),t.removeListener("drain",o),t.removeListener("error",f),t.removeListener("unpipe",n),r.removeListener("end",a),r.removeListener("end",l),r.removeListener("data",h),c=!0,!i.awaitDrain||t._writableState&&!t._writableState.needDrain||o()}var u=!1;function h(e){Mr("ondata"),u=!1,!1!==t.write(e)||u||((1===i.pipesCount&&i.pipes===t||i.pipesCount>1&&-1!==Xr(i.pipes,t))&&!c&&(Mr("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,u=!0),r.pause())}function f(e){var r;Mr("onerror",e),g(),t.removeListener("error",f),0===(r="error",t.listeners(r).length)&&t.emit("error",e)}function d(){t.removeListener("finish",p),g()}function p(){Mr("onfinish"),t.removeListener("close",d),g()}function g(){Mr("unpipe"),r.unpipe(t)}return r.on("data",h),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",f),t.once("close",d),t.once("finish",p),t.emit("pipe",r),i.flowing||(Mr("pipe resume"),r.resume()),t},Ur.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,i=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this);return this}var n=Xr(e.pipes,t);return-1===n||(e.pipes.splice(n,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this)),this},Ur.prototype.on=function(t,e){var r=At.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&zr(this):oe(Wr,this))}return r},Ur.prototype.addListener=Ur.prototype.on,Ur.prototype.resume=function(){var t=this._readableState;return t.flowing||(Mr("resume"),t.flowing=!0,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,oe(Jr,t,e))}(this,t)),this},Ur.prototype.pause=function(){return Mr("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Mr("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Ur.prototype.wrap=function(t){var e=this._readableState,r=!1,i=this;for(var s in t.on("end",function(){if(Mr("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&i.push(t)}i.push(null)}),t.on("data",function(s){(Mr("wrapped data"),e.decoder&&(s=e.decoder.write(s)),e.objectMode&&null==s)||(e.objectMode||s&&s.length)&&(i.push(s)||(r=!0,t.pause()))}),t)void 0===this[s]&&"function"==typeof t[s]&&(this[s]=function(e){return function(){return t[e].apply(t,arguments)}}(s));return function(t,e){for(var r=0,i=t.length;r<i;r++)e(t[r],r)}(["error","close","destroy","pause","resume"],function(e){t.on(e,i.emit.bind(i,e))}),i._read=function(e){Mr("wrapped _read",e),r&&(r=!1,t.resume())},i},Ur._fromList=Yr,ri.WritableState=ei,le(ri,At),ei.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},ri.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},ri.prototype.write=function(t,e,r){var i=this._writableState,s=!1;return"function"==typeof e&&(r=e,e=null),Je.isBuffer(t)?e="buffer":e||(e=i.defaultEncoding),"function"!=typeof r&&(r=Zr),i.ended?function(t,e){var r=new Error("write after end");t.emit("error",r),oe(e,r)}(this,r):function(t,e,r,i){var s=!0,n=!1;return null===r?n=new TypeError("May not write null values to stream"):Je.isBuffer(r)||"string"==typeof r||void 0===r||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n&&(t.emit("error",n),oe(i,n),s=!1),s}(this,i,t,r)&&(i.pendingcb++,s=function(t,e,r,i,s){r=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=Je.from(e,r));return e}(e,r,i),Je.isBuffer(r)&&(i="buffer");var n=e.objectMode?1:r.length;e.length+=n;var a=e.length<e.highWaterMark;a||(e.needDrain=!0);if(e.writing||e.corked){var o=e.lastBufferedRequest;e.lastBufferedRequest=new ti(r,i,s),o?o.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else ii(t,e,!1,n,r,i,s);return a}(this,i,t,e,r)),s},ri.prototype.cork=function(){this._writableState.corked++},ri.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||ni(this,t))},ri.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},ri.prototype._write=function(t,e,r){r(new Error("not implemented"))},ri.prototype._writev=null,ri.prototype.end=function(t,e,r){var i=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||function(t,e,r){e.ending=!0,ci(t,e),r&&(e.finished?oe(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,i,r)},le(di,Ur);for(var ui=Object.keys(ri.prototype),hi=0;hi<ui.length;hi++){var fi=ui[hi];di.prototype[fi]||(di.prototype[fi]=ri.prototype[fi])}function di(t){if(!(this instanceof di))return new di(t);Ur.call(this,t),ri.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",pi)}function pi(){this.allowHalfOpen||this._writableState.ended||oe(gi,this)}function gi(t){t.end()}function mi(t){this.afterTransform=function(e,r){return function(t,e,r){var i=t._transformState;i.transforming=!1;var s=i.writecb;if(!s)return t.emit("error",new Error("no writecb in Transform class"));i.writechunk=null,i.writecb=null,null!=r&&t.push(r);s(e);var n=t._readableState;n.reading=!1,(n.needReadable||n.length<n.highWaterMark)&&t._read(n.highWaterMark)}(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function yi(t){if(!(this instanceof yi))return new yi(t);di.call(this,t),this._transformState=new mi(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(t){bi(e,t)}):bi(e)})}function bi(t,e){if(e)return t.emit("error",e);var r=t._writableState,i=t._transformState;if(r.length)throw new Error("Calling transform done when ws.length != 0");if(i.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}function wi(t){if(!(this instanceof wi))return new wi(t);yi.call(this,t)}function vi(){At.call(this)}le(yi,di),yi.prototype.push=function(t,e){return this._transformState.needTransform=!1,di.prototype.push.call(this,t,e)},yi.prototype._transform=function(t,e,r){throw new Error("Not implemented")},yi.prototype._write=function(t,e,r){var i=this._transformState;if(i.writecb=r,i.writechunk=t,i.writeencoding=e,!i.transforming){var s=this._readableState;(i.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},yi.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0},le(wi,yi),wi.prototype._transform=function(t,e,r){r(null,t)},le(vi,At),vi.Readable=Ur,vi.Writable=ri,vi.Duplex=di,vi.Transform=yi,vi.PassThrough=wi,vi.Stream=vi,vi.prototype.pipe=function(t,e){var r=this;function i(e){t.writable&&!1===t.write(e)&&r.pause&&r.pause()}function s(){r.readable&&r.resume&&r.resume()}r.on("data",i),t.on("drain",s),t._isStdio||e&&!1===e.end||(r.on("end",a),r.on("close",o));var n=!1;function a(){n||(n=!0,t.end())}function o(){n||(n=!0,"function"==typeof t.destroy&&t.destroy())}function c(t){if(l(),0===At.listenerCount(this,"error"))throw t}function l(){r.removeListener("data",i),t.removeListener("drain",s),r.removeListener("end",a),r.removeListener("close",o),r.removeListener("error",c),t.removeListener("error",c),r.removeListener("end",l),r.removeListener("close",l),t.removeListener("close",l)}return r.on("error",c),t.on("error",c),r.on("end",l),r.on("close",l),t.on("close",l),t.emit("pipe",r),t};class Si extends At{constructor({resource:t}){super(),this.resource=t,this.client=t.client,this.stream=new s({highWaterMark:3*this.client.parallelism,start:this._start.bind(this),pull:this._pull.bind(this),cancel:this._cancel.bind(this)})}build(){return this.stream.getReader()}async _start(t){this.controller=t,this.continuationToken=null,this.closeNextIteration=!1}async _pull(t){if(this.closeNextIteration)return void t.close();const e=await this.client.listObjects({prefix:`resource=${this.resource.name}`,continuationToken:this.continuationToken}),r=e?.Contents.map(t=>t.Key).map(t=>t.replace(this.client.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t).map(t=>t.replace(`resource=${this.resource.name}/id=`,""));this.continuationToken=e.NextContinuationToken,this.enqueue(r),e.IsTruncated||(this.closeNextIteration=!0)}enqueue(t){t.forEach(t=>{this.controller.enqueue(t),this.emit("id",t)})}_cancel(t){}}var _i=Si;class ki extends _i{enqueue(t){this.controller.enqueue(t),this.emit("page",t)}}class Oi extends At{constructor({resource:t,batchSize:e=10,concurrency:r=5}){if(super(),!t)throw new Error("Resource is required for ResourceReader");this.resource=t,this.client=t.client,this.batchSize=e,this.concurrency=r,this.input=new ki({resource:this.resource}),this.transform=new yi({objectMode:!0,transform:this._transform.bind(this)}),this.input.on("data",t=>{this.transform.write(t)}),this.input.on("end",()=>{this.transform.end()}),this.input.on("error",t=>{this.emit("error",t)}),this.transform.on("data",t=>{this.emit("data",t)}),this.transform.on("end",()=>{this.emit("end")}),this.transform.on("error",t=>{this.emit("error",t)})}build(){return this}async _transform(t,e,r){const[s,n]=await wt(async()=>{await i.for(t).withConcurrency(this.concurrency).handleError(async(t,e)=>{this.emit("error",t,e)}).process(async t=>{const e=await this.resource.get(t);return this.push(e),e})});r(n)}resume(){this.input.resume()}}class Ri extends At{constructor({resource:t,batchSize:e=10,concurrency:r=5}){super(),this.resource=t,this.client=t.client,this.batchSize=e,this.concurrency=r,this.buffer=[],this.writing=!1,this.writable=new ri({objectMode:!0,write:this._write.bind(this)}),this.writable.on("finish",()=>{this.emit("finish")}),this.writable.on("error",t=>{this.emit("error",t)})}build(){return this}write(t){return this.buffer.push(t),this._maybeWrite().catch(t=>{this.emit("error",t)}),!0}end(){this.ended=!0,this._maybeWrite().catch(t=>{this.emit("error",t)})}async _maybeWrite(){if(!this.writing&&(0!==this.buffer.length||this.ended)){for(this.writing=!0;this.buffer.length>0;){const t=this.buffer.splice(0,this.batchSize),[e,r]=await wt(async()=>{await i.for(t).withConcurrency(this.concurrency).handleError(async(t,e)=>{this.emit("error",t,e)}).process(async t=>{const[e,r,i]=await wt(async()=>await this.resource.insert(t));return e?i:(this.emit("error",r,t),null)})});e||this.emit("error",r)}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(t,e,r){r()}}function ji(t){return new Promise((e,r)=>{if(!t)return r(new Error("streamToString: stream is undefined"));const i=[];t.on("data",t=>i.push(t)),t.on("error",r),t.on("end",()=>e(Buffer.concat(i).toString("utf-8")))})}var xi=class extends Yt{constructor({client:t,keyPrefix:e="cache",ttl:r=0,prefix:i}){super({client:t,keyPrefix:e,ttl:r,prefix:i}),this.client=t,this.keyPrefix=e,this.config.ttl=r,this.config.client=t,this.config.prefix=void 0!==i?i:e+(e.endsWith("/")?"":"/")}async _set(t,e){let i=JSON.stringify(e);const s=i.length;return i=r.gzipSync(i).toString("base64"),this.client.putObject({key:Kt(this.keyPrefix,t),body:i,contentEncoding:"gzip",contentType:"application/gzip",metadata:{compressor:"zlib",compressed:"true","client-id":this.client.id,"length-serialized":String(s),"length-compressed":String(i.length),"compression-gain":(i.length/s).toFixed(2)}})}async _get(t){const[e,i,s]=await wt(async()=>{const{Body:e}=await this.client.getObject(Kt(this.keyPrefix,t));let i=await ji(e);return i=Buffer.from(i,"base64"),i=r.unzipSync(i).toString(),JSON.parse(i)});if(e)return s;if("NoSuchKey"===i.name||"NotFound"===i.name)return null;throw i}async _del(t){return await this.client.deleteObject(Kt(this.keyPrefix,t)),!0}async _clear(){const t=await this.client.getAllKeys({prefix:this.keyPrefix});await this.client.deleteObjects(t)}async size(){return(await this.keys()).length}async keys(){const t=await this.client.getAllKeys({prefix:this.keyPrefix}),e=this.keyPrefix.endsWith("/")?this.keyPrefix:this.keyPrefix+"/";return t.map(t=>t.startsWith(e)?t.slice(e.length):t)}};var Ei=class extends Yt{constructor(t={}){super(t),this.cache={},this.meta={},this.maxSize=t.maxSize||0,this.ttl=t.ttl||0}async _set(t,e){if(this.maxSize>0&&Object.keys(this.cache).length>=this.maxSize){const t=Object.entries(this.meta).sort((t,e)=>t[1].ts-e[1].ts)[0]?.[0];t&&(delete this.cache[t],delete this.meta[t])}return this.cache[t]=e,this.meta[t]={ts:Date.now()},e}async _get(t){if(!Object.prototype.hasOwnProperty.call(this.cache,t))return null;if(this.ttl>0){const e=Date.now(),r=this.meta[t];if(r&&e-r.ts>1e3*this.ttl)return delete this.cache[t],delete this.meta[t],null}return this.cache[t]}async _del(t){return delete this.cache[t],delete this.meta[t],!0}async _clear(t){if(!t)return this.cache={},this.meta={},!0;for(const e of Object.keys(this.cache))e.startsWith(t)&&(delete this.cache[e],delete this.meta[e]);return!0}async size(){return Object.keys(this.cache).length}async keys(){return Object.keys(this.cache)}},Di={};class Ai extends Yt{constructor({directory:t,prefix:e="cache",ttl:r=36e5,enableCompression:i=!0,compressionThreshold:s=1024,createDirectory:n=!0,fileExtension:a=".cache",enableMetadata:o=!0,maxFileSize:c=10485760,enableStats:l=!1,enableCleanup:u=!0,cleanupInterval:h=3e5,encoding:f="utf8",fileMode:d=420,enableBackup:p=!1,backupSuffix:g=".bak",enableLocking:m=!1,lockTimeout:y=5e3,enableJournal:b=!1,journalFile:w="cache.journal",...v}){if(super(v),!t)throw new Error("FilesystemCache: directory parameter is required");this.directory=Wt.resolve(t),this.prefix=e,this.ttl=r,this.enableCompression=i,this.compressionThreshold=s,this.createDirectory=n,this.fileExtension=a,this.enableMetadata=o,this.maxFileSize=c,this.enableStats=l,this.enableCleanup=u,this.cleanupInterval=h,this.encoding=f,this.fileMode=d,this.enableBackup=p,this.backupSuffix=g,this.enableLocking=m,this.lockTimeout=y,this.enableJournal=b,this.journalFile=Wt.join(this.directory,w),this.stats={hits:0,misses:0,sets:0,deletes:0,clears:0,errors:0},this.locks=new Map,this.cleanupTimer=null,this._init()}async _init(){this.createDirectory&&await this._ensureDirectory(this.directory),this.enableCleanup&&this.cleanupInterval>0&&(this.cleanupTimer=setInterval(()=>{this._cleanup().catch(t=>{console.warn("FilesystemCache cleanup error:",t.message)})},this.cleanupInterval))}async _ensureDirectory(t){const[e,r]=await wt(async()=>{await n(t,{recursive:!0})});if(!e&&"EEXIST"!==r.code)throw new Error(`Failed to create cache directory: ${r.message}`)}_getFilePath(t){const e=t.replace(/[<>:"/\\|?*]/g,"_"),r=`${this.prefix}_${e}${this.fileExtension}`;return Wt.join(this.directory,r)}_getMetadataPath(t){return t+".meta"}async _set(t,e){const i=this._getFilePath(t);try{let s=JSON.stringify(e);const n=Buffer.byteLength(s,this.encoding);if(n>this.maxFileSize)throw new Error(`Cache data exceeds maximum file size: ${n} > ${this.maxFileSize}`);let o=!1,c=s;if(this.enableCompression&&n>=this.compressionThreshold){c=r.gzipSync(Buffer.from(s,this.encoding)).toString("base64"),o=!0}if(this.enableBackup&&await this._fileExists(i)){const t=i+this.backupSuffix;await this._copyFile(i,t)}this.enableLocking&&await this._acquireLock(i);try{if(await a(i,c,{encoding:o?"utf8":this.encoding,mode:this.fileMode}),this.enableMetadata){const e={key:t,timestamp:Date.now(),ttl:this.ttl,compressed:o,originalSize:n,compressedSize:o?Buffer.byteLength(c,"utf8"):n,compressionRatio:o?(Buffer.byteLength(c,"utf8")/n).toFixed(2):1};await a(this._getMetadataPath(i),JSON.stringify(e),{encoding:this.encoding,mode:this.fileMode})}this.enableStats&&this.stats.sets++,this.enableJournal&&await this._journalOperation("set",t,{size:n,compressed:o})}finally{this.enableLocking&&this._releaseLock(i)}return e}catch(e){throw this.enableStats&&this.stats.errors++,new Error(`Failed to set cache key '${t}': ${e.message}`)}}async _get(t){const e=this._getFilePath(t);try{if(!await this._fileExists(e))return this.enableStats&&this.stats.misses++,null;let i=!1;if(this.enableMetadata){const t=this._getMetadataPath(e);if(await this._fileExists(t)){const[e,r,s]=await wt(async()=>{const e=await o(t,this.encoding);return JSON.parse(e)});if(e&&s.ttl>0){i=Date.now()-s.timestamp>s.ttl}}}else if(this.ttl>0){const t=await c(e);i=Date.now()-t.mtime.getTime()>this.ttl}if(i)return await this._del(t),this.enableStats&&this.stats.misses++,null;this.enableLocking&&await this._acquireLock(e);try{const t=await o(e,this.encoding);let i=!1;if(this.enableMetadata){const t=this._getMetadataPath(e);if(await this._fileExists(t)){const[e,r,s]=await wt(async()=>{const e=await o(t,this.encoding);return JSON.parse(e)});e&&(i=s.compressed)}}let s=t;if(i||this.enableCompression&&t.match(/^[A-Za-z0-9+/=]+$/))try{const e=Buffer.from(t,"base64");s=r.gunzipSync(e).toString(this.encoding)}catch(e){s=t}const n=JSON.parse(s);return this.enableStats&&this.stats.hits++,n}finally{this.enableLocking&&this._releaseLock(e)}}catch(e){return this.enableStats&&this.stats.errors++,await this._del(t),null}}async _del(t){const e=this._getFilePath(t);try{if(await this._fileExists(e)&&await l(e),this.enableMetadata){const t=this._getMetadataPath(e);await this._fileExists(t)&&await l(t)}if(this.enableBackup){const t=e+this.backupSuffix;await this._fileExists(t)&&await l(t)}return this.enableStats&&this.stats.deletes++,this.enableJournal&&await this._journalOperation("delete",t),!0}catch(e){throw this.enableStats&&this.stats.errors++,new Error(`Failed to delete cache key '${t}': ${e.message}`)}}async _clear(t){try{if(!await this._fileExists(this.directory))return this.enableStats&&this.stats.clears++,!0;const e=(await u(this.directory)).filter(e=>{if(!e.startsWith(this.prefix))return!1;if(!e.endsWith(this.fileExtension))return!1;if(t){return e.slice(this.prefix.length+1,-this.fileExtension.length).startsWith(t)}return!0});for(const t of e){const e=Wt.join(this.directory,t);if(await this._fileExists(e)&&await l(e),this.enableMetadata){const t=this._getMetadataPath(e);await this._fileExists(t)&&await l(t)}if(this.enableBackup){const t=e+this.backupSuffix;await this._fileExists(t)&&await l(t)}}return this.enableStats&&this.stats.clears++,this.enableJournal&&await this._journalOperation("clear",t||"all",{count:e.length}),!0}catch(t){throw this.enableStats&&this.stats.errors++,new Error(`Failed to clear cache: ${t.message}`)}}async size(){return(await this.keys()).length}async keys(){try{const t=(await u(this.directory)).filter(t=>t.startsWith(this.prefix)&&t.endsWith(this.fileExtension));return t.map(t=>t.slice(this.prefix.length+1,-this.fileExtension.length))}catch(t){return console.warn("FilesystemCache: Failed to list keys:",t.message),[]}}async _fileExists(t){const[e]=await wt(async()=>{await c(t)});return e}async _copyFile(t,e){const[r,i]=await wt(async()=>{const r=await o(t);await a(e,r)});r||console.warn("FilesystemCache: Failed to create backup:",i.message)}async _cleanup(){if(this.ttl&&!(this.ttl<=0))try{const t=await u(this.directory),e=Date.now();for(const r of t){if(!r.startsWith(this.prefix)||!r.endsWith(this.fileExtension))continue;const t=Wt.join(this.directory,r);let i=!1;if(this.enableMetadata){const r=this._getMetadataPath(t);if(await this._fileExists(r)){const[t,s,n]=await wt(async()=>{const t=await o(r,this.encoding);return JSON.parse(t)});if(t&&n.ttl>0){i=e-n.timestamp>n.ttl}}}else{const[r,s,n]=await wt(async()=>await c(t));if(r){i=e-n.mtime.getTime()>this.ttl}}if(i){const t=r.slice(this.prefix.length+1,-this.fileExtension.length);await this._del(t)}}}catch(t){console.warn("FilesystemCache cleanup error:",t.message)}}async _acquireLock(t){if(!this.enableLocking)return;const e=t,r=Date.now();for(;this.locks.has(e);){if(Date.now()-r>this.lockTimeout)throw new Error(`Lock timeout for file: ${t}`);await new Promise(t=>setTimeout(t,10))}this.locks.set(e,Date.now())}_releaseLock(t){this.enableLocking&&this.locks.delete(t)}async _journalOperation(t,e,r={}){if(!this.enableJournal)return;const i={timestamp:(new Date).toISOString(),operation:t,key:e,metadata:r},[s,n]=await wt(async()=>{const t=JSON.stringify(i)+"\n";await Di.promises.appendFile(this.journalFile,t,this.encoding)});s||console.warn("FilesystemCache journal error:",n.message)}destroy(){this.cleanupTimer&&(clearInterval(this.cleanupTimer),this.cleanupTimer=null)}getStats(){return{...this.stats,directory:this.directory,ttl:this.ttl,compression:this.enableCompression,metadata:this.enableMetadata,cleanup:this.enableCleanup,locking:this.enableLocking,journal:this.enableJournal}}}class Ni extends Ai{constructor({partitionStrategy:t="hierarchical",trackUsage:e=!0,preloadRelated:r=!1,preloadThreshold:i=10,maxCacheSize:s=null,usageStatsFile:n="partition-usage.json",...a}){super(a),this.partitionStrategy=t,this.trackUsage=e,this.preloadRelated=r,this.preloadThreshold=i,this.maxCacheSize=s,this.usageStatsFile=Wt.join(this.directory,n),this.partitionUsage=new Map,this.loadUsageStats()}_getPartitionCacheKey(t,e,r,i={},s={}){const n=[`resource=${t}`,`action=${e}`];if(r&&Object.keys(i).length>0){n.push(`partition=${r}`);const t=Object.entries(i).sort(([t],[e])=>t.localeCompare(e));for(const[e,r]of t)null!=r&&n.push(`${e}=${r}`)}if(Object.keys(s).length>0){const t=Object.entries(s).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>`${t}=${e}`).join("|");n.push(`params=${Buffer.from(t).toString("base64")}`)}return n.join("/")+this.fileExtension}_getPartitionDirectory(t,e,r={}){const i=Wt.join(this.directory,`resource=${t}`);if(!e)return i;if("flat"===this.partitionStrategy)return Wt.join(i,"partitions");if("temporal"===this.partitionStrategy&&this._isTemporalPartition(e,r))return this._getTemporalDirectory(i,e,r);const s=[i,`partition=${e}`],n=Object.entries(r).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of n)null!=e&&s.push(`${t}=${this._sanitizePathValue(e)}`);return Wt.join(...s)}async _set(t,e,r={}){const{resource:i,action:s,partition:n,partitionValues:a,params:o}=r;if(i&&n){const t=this._getPartitionCacheKey(i,s,n,a,o),r=this._getPartitionDirectory(i,n,a);await this._ensureDirectory(r);const c=Wt.join(r,this._sanitizeFileName(t));this.trackUsage&&await this._trackPartitionUsage(i,n,a);const l={data:e,metadata:{resource:i,partition:n,partitionValues:a,timestamp:Date.now(),ttl:this.ttl}};return this._writeFileWithMetadata(c,l)}return super._set(t,e)}async _get(t,e={}){const{resource:r,action:i,partition:s,partitionValues:n,params:a}=e;if(r&&s){const t=this._getPartitionCacheKey(r,i,s,n,a),e=this._getPartitionDirectory(r,s,n),o=Wt.join(e,this._sanitizeFileName(t));if(!await this._fileExists(o))return this.preloadRelated&&await this._preloadRelatedPartitions(r,s,n),null;const c=await this._readFileWithMetadata(o);return c&&this.trackUsage&&await this._trackPartitionUsage(r,s,n),c?.data||null}return super._get(t)}async clearPartition(t,e,r={}){const i=this._getPartitionDirectory(t,e,r),[s,n]=await wt(async()=>{await this._fileExists(i)&&await h(i,{recursive:!0})});s||console.warn(`Failed to clear partition cache: ${n.message}`);const a=this._getUsageKey(t,e,r);return this.partitionUsage.delete(a),await this._saveUsageStats(),s}async clearResourcePartitions(t){const e=Wt.join(this.directory,`resource=${t}`),[r,i]=await wt(async()=>{await this._fileExists(e)&&await h(e,{recursive:!0})});for(const[e]of this.partitionUsage.entries())e.startsWith(`${t}/`)&&this.partitionUsage.delete(e);return await this._saveUsageStats(),r}async getPartitionStats(t,e=null){const r={totalFiles:0,totalSize:0,partitions:{},usage:{}},i=Wt.join(this.directory,`resource=${t}`);if(!await this._fileExists(i))return r;await this._calculateDirectoryStats(i,r);for(const[i,s]of this.partitionUsage.entries())if(i.startsWith(`${t}/`)){const t=i.split("/")[1];e&&t!==e||(r.usage[t]=s)}return r}async getCacheRecommendations(t){const e=[],r=Date.now();for(const[i,s]of this.partitionUsage.entries())if(i.startsWith(`${t}/`)){const[,t]=i.split("/"),n=(r-s.lastAccess)/864e5,a=s.count/Math.max(1,n);let o="keep",c=s.count;n>30?(o="archive",c=0):a<.1?(o="reduce_ttl",c=1):a>10&&(o="preload",c=100),e.push({partition:t,recommendation:o,priority:c,usage:a,lastAccess:new Date(s.lastAccess).toISOString()})}return e.sort((t,e)=>e.priority-t.priority)}async warmPartitionCache(t,e={}){const{partitions:r=[],maxFiles:i=1e3}=e;let s=0;for(const e of r){const r=`${t}/${e}`,n=this.partitionUsage.get(r);if(n&&n.count>=this.preloadThreshold&&(console.log(`🔥 Warming cache for ${t}/${e} (${n.count} accesses)`),s++),s>=i)break}return s}async _trackPartitionUsage(t,e,r){const i=this._getUsageKey(t,e,r),s=this.partitionUsage.get(i)||{count:0,firstAccess:Date.now(),lastAccess:Date.now()};s.count++,s.lastAccess=Date.now(),this.partitionUsage.set(i,s),s.count%10==0&&await this._saveUsageStats()}_getUsageKey(t,e,r){const i=Object.entries(r).sort(([t],[e])=>t.localeCompare(e)).map(([t,e])=>`${t}=${e}`).join("|");return`${t}/${e}/${i}`}async _preloadRelatedPartitions(t,e,r){console.log(`🎯 Preloading related partitions for ${t}/${e}`),r.timestamp||r.date}_isTemporalPartition(t,e){const r=["date","timestamp","createdAt","updatedAt"];return Object.keys(e).some(t=>r.some(e=>t.toLowerCase().includes(e)))}_getTemporalDirectory(t,e,r){const i=Object.values(r)[0];if("string"==typeof i&&i.match(/^\d{4}-\d{2}-\d{2}/)){const[e,r,s]=i.split("-");return Wt.join(t,"temporal",e,r,s)}return Wt.join(t,`partition=${e}`)}_sanitizePathValue(t){return String(t).replace(/[<>:"/\\|?*]/g,"_")}_sanitizeFileName(t){return t.replace(/[<>:"/\\|?*]/g,"_")}async _calculateDirectoryStats(t,e){const[r,i,s]=await wt(()=>u(t));if(r)for(const r of s){const i=Wt.join(t,r),[s,n,a]=await wt(()=>c(i));s&&(a.isDirectory()?await this._calculateDirectoryStats(i,e):(e.totalFiles++,e.totalSize+=a.size))}}async loadUsageStats(){const[t,e,r]=await wt(async()=>{const t=await o(this.usageStatsFile,"utf8");return JSON.parse(t)});t&&r&&(this.partitionUsage=new Map(Object.entries(r)))}async _saveUsageStats(){const t=Object.fromEntries(this.partitionUsage);await wt(async()=>{await a(this.usageStatsFile,JSON.stringify(t,null,2),"utf8")})}async _writeFileWithMetadata(t,e){const r=JSON.stringify(e),[i,s]=await wt(async()=>{await a(t,r,{encoding:this.encoding,mode:this.fileMode})});if(!i)throw new Error(`Failed to write cache file: ${s.message}`);return!0}async _readFileWithMetadata(t){const[e,r,i]=await wt(async()=>await o(t,this.encoding));if(!e||!i)return null;try{return JSON.parse(i)}catch(t){return{data:i}}}}class Ii extends Tt{constructor(t={}){super(t),this.driver=t.driver,this.config={includePartitions:!1!==t.includePartitions,partitionStrategy:t.partitionStrategy||"hierarchical",partitionAware:!1!==t.partitionAware,trackUsage:!1!==t.trackUsage,preloadRelated:!1!==t.preloadRelated,...t}}async setup(t){await super.setup(t)}async onSetup(){this.config.driver?this.driver=this.config.driver:"memory"===this.config.driverType?this.driver=new Ei(this.config.memoryOptions||{}):"filesystem"===this.config.driverType?this.config.partitionAware?this.driver=new Ni({partitionStrategy:this.config.partitionStrategy,trackUsage:this.config.trackUsage,preloadRelated:this.config.preloadRelated,...this.config.filesystemOptions}):this.driver=new Ai(this.config.filesystemOptions||{}):this.driver=new xi({client:this.database.client,...this.config.s3Options||{}}),this.installDatabaseProxy(),this.installResourceHooks()}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._cacheProxyInstalled)return;const t=this.installResourceHooks.bind(this);this.database._originalCreateResourceForCache=this.database.createResource,this.database.createResource=async function(...e){const r=await this._originalCreateResourceForCache(...e);return t(r),r},this.database._cacheProxyInstalled=!0}installResourceHooks(){for(const t of Object.values(this.database.resources))this.installResourceHooksForResource(t)}installResourceHooksForResource(t){if(!this.driver)return;Object.defineProperty(t,"cache",{value:this.driver,writable:!0,configurable:!0,enumerable:!1}),t.cacheKeyFor=async(e={})=>{const{action:r,params:i={},partition:s,partitionValues:n}=e;return this.generateCacheKey(t,r,i,s,n)},this.driver instanceof Ni&&(t.clearPartitionCache=async(e,r={})=>await this.driver.clearPartition(t.name,e,r),t.getPartitionCacheStats=async(e=null)=>await this.driver.getPartitionStats(t.name,e),t.getCacheRecommendations=async()=>await this.driver.getCacheRecommendations(t.name),t.warmPartitionCache=async(e=[],r={})=>await this.driver.warmPartitionCache(t.name,{partitions:e,...r}));const e=["count","listIds","getMany","getAll","page","list","get"];for(const r of e)t.useMiddleware(r,async(e,i)=>{let s;if("getMany"===r)s=await t.cacheKeyFor({action:r,params:{ids:e.args[0]}});else if("page"===r){const{offset:i,size:n,partition:a,partitionValues:o}=e.args[0]||{};s=await t.cacheKeyFor({action:r,params:{offset:i,size:n},partition:a,partitionValues:o})}else if("list"===r||"listIds"===r||"count"===r){const{partition:i,partitionValues:n}=e.args[0]||{};s=await t.cacheKeyFor({action:r,partition:i,partitionValues:n})}else"getAll"===r?s=await t.cacheKeyFor({action:r}):"get"===r&&(s=await t.cacheKeyFor({action:r,params:{id:e.args[0]}}));if(this.driver instanceof Ni){let n,a;if("list"===r||"listIds"===r||"count"===r||"page"===r){const t=e.args[0]||{};n=t.partition,a=t.partitionValues}const[o,c,l]=await wt(()=>t.cache._get(s,{resource:t.name,action:r,partition:n,partitionValues:a}));if(o&&null!=l)return l;if(!o&&"NoSuchKey"!==c.name)throw c;const u=await i();return await t.cache._set(s,u,{resource:t.name,action:r,partition:n,partitionValues:a}),u}{const[e,r,n]=await wt(()=>t.cache.get(s));if(e&&null!=n)return n;if(!e&&"NoSuchKey"!==r.name)throw r;const a=await i();return await t.cache.set(s,a),a}});const r=["insert","update","delete","deleteMany"];for(const e of r)t.useMiddleware(e,async(r,i)=>{const s=await i();if("insert"===e)await this.clearCacheForResource(t,r.args[0]);else if("update"===e)await this.clearCacheForResource(t,{id:r.args[0],...r.args[1]});else if("delete"===e){let e={id:r.args[0]};if("function"==typeof t.get){const[i,s,n]=await wt(()=>t.get(r.args[0]));i&&n&&(e=n)}await this.clearCacheForResource(t,e)}else"deleteMany"===e&&await this.clearCacheForResource(t);return s})}async clearCacheForResource(t,e){if(!t.cache)return;const r=`resource=${t.name}`;if(await t.cache.clear(r),!0===this.config.includePartitions&&t.config?.partitions&&Object.keys(t.config.partitions).length>0)if(e){const i=this.getPartitionValues(e,t);for(const[e,s]of Object.entries(i))if(s&&Object.keys(s).length>0&&Object.values(s).some(t=>null!=t)){const i=Kt(r,`partition=${e}`);await t.cache.clear(i)}}else for(const e of Object.keys(t.config.partitions)){const i=Kt(r,`partition=${e}`);await t.cache.clear(i)}}async generateCacheKey(t,e,r={},i=null,s=null){const n=[`resource=${t.name}`,`action=${e}`];if(i&&s&&Object.keys(s).length>0){n.push(`partition:${i}`);for(const[t,e]of Object.entries(s))null!=e&&n.push(`${t}:${e}`)}if(Object.keys(r).length>0){const t=await this.hashParams(r);n.push(t)}return Kt(...n)+".json.gz"}async hashParams(t){const e=Object.keys(t).sort().map(e=>`${e}:${t[e]}`).join("|")||"empty";return await St(e)}async getCacheStats(){return this.driver?{size:await this.driver.size(),keys:await this.driver.keys(),driver:this.driver.constructor.name}:null}async clearAllCache(){if(this.driver)for(const t of Object.values(this.database.resources))if(t.cache){const e=`resource=${t.name}`;await t.cache.clear(e)}}async warmCache(t,e={}){const r=this.database.resources[t];if(!r)throw new Error(`Resource '${t}' not found`);const{includePartitions:i=!0}=e;if(this.driver instanceof Ni&&r.warmPartitionCache){const t=r.config.partitions?Object.keys(r.config.partitions):[];return await r.warmPartitionCache(t,e)}if(await r.getAll(),i&&r.config.partitions)for(const[t,e]of Object.entries(r.config.partitions))if(e.fields){const e=await r.getAll(),i=Array.isArray(e)?e:[],s=new Set;for(const e of i.slice(0,10)){const i=this.getPartitionValues(e,r);i[t]&&s.add(JSON.stringify(i[t]))}for(const e of s){const i=JSON.parse(e);await r.list({partition:t,partitionValues:i})}}}async getPartitionCacheStats(t,e=null){if(!(this.driver instanceof Ni))throw new Error("Partition cache statistics are only available with PartitionAwareFilesystemCache");return await this.driver.getPartitionStats(t,e)}async getCacheRecommendations(t){if(!(this.driver instanceof Ni))throw new Error("Cache recommendations are only available with PartitionAwareFilesystemCache");return await this.driver.getCacheRecommendations(t)}async clearPartitionCache(t,e,r={}){if(!(this.driver instanceof Ni))throw new Error("Partition cache clearing is only available with PartitionAwareFilesystemCache");return await this.driver.clearPartition(t,e,r)}async analyzeCacheUsage(){if(!(this.driver instanceof Ni))return{message:"Cache usage analysis is only available with PartitionAwareFilesystemCache"};const t={totalResources:Object.keys(this.database.resources).length,resourceStats:{},recommendations:{},summary:{mostUsedPartitions:[],leastUsedPartitions:[],suggestedOptimizations:[]}};for(const[e,r]of Object.entries(this.database.resources))try{t.resourceStats[e]=await this.driver.getPartitionStats(e),t.recommendations[e]=await this.driver.getCacheRecommendations(e)}catch(r){t.resourceStats[e]={error:r.message}}const e=Object.values(t.recommendations).flat();return t.summary.mostUsedPartitions=e.filter(t=>"preload"===t.recommendation).sort((t,e)=>e.priority-t.priority).slice(0,5),t.summary.leastUsedPartitions=e.filter(t=>"archive"===t.recommendation).slice(0,5),t.summary.suggestedOptimizations=[`Consider preloading ${t.summary.mostUsedPartitions.length} high-usage partitions`,`Archive ${t.summary.leastUsedPartitions.length} unused partitions`,"Monitor cache hit rates for partition efficiency"],t}}const $i={async setup(t){t&&t.client&&(this.client=t.client,this.map={PutObjectCommand:"put",GetObjectCommand:"get",HeadObjectCommand:"head",DeleteObjectCommand:"delete",DeleteObjectsCommand:"delete",ListObjectsV2Command:"list"},this.costs={total:0,prices:{put:5e-6,copy:5e-6,list:5e-6,post:5e-6,get:4e-4/1e3,select:4e-4/1e3,delete:4e-4/1e3,head:4e-4/1e3},requests:{total:0,put:0,post:0,copy:0,list:0,get:0,select:0,delete:0,head:0},events:{total:0,PutObjectCommand:0,GetObjectCommand:0,HeadObjectCommand:0,DeleteObjectCommand:0,DeleteObjectsCommand:0,ListObjectsV2Command:0}},this.client.costs=JSON.parse(JSON.stringify(this.costs)))},async start(){this.client&&(this.client.on("command.response",t=>this.addRequest(t,this.map[t])),this.client.on("command.error",t=>this.addRequest(t,this.map[t])))},addRequest(t,e){e&&(this.costs.events[t]++,this.costs.events.total++,this.costs.requests.total++,this.costs.requests[e]++,this.costs.total+=this.costs.prices[e],this.client&&this.client.costs&&(this.client.costs.events[t]++,this.client.costs.events.total++,this.client.costs.requests.total++,this.client.costs.requests[e]++,this.client.costs.total+=this.client.costs.prices[e]))}};class Pi extends Tt{constructor(t={}){super(),this.indexResource=null,this.config={minWordLength:t.minWordLength||3,maxResults:t.maxResults||100,...t},this.indexes=new Map}async setup(t){this.database=t;const[e,r,i]=await wt(()=>t.createResource({name:"fulltext_indexes",attributes:{id:"string|required",resourceName:"string|required",fieldName:"string|required",word:"string|required",recordIds:"json|required",count:"number|required",lastUpdated:"string|required"}}));this.indexResource=e?i:t.resources.fulltext_indexes,await this.loadIndexes(),this.installIndexingHooks()}async start(){}async stop(){await this.saveIndexes()}async loadIndexes(){if(!this.indexResource)return;const[t,e,r]=await wt(()=>this.indexResource.getAll());if(t)for(const t of r){const e=`${t.resourceName}:${t.fieldName}:${t.word}`;this.indexes.set(e,{recordIds:t.recordIds||[],count:t.count||0})}}async saveIndexes(){if(!this.indexResource)return;const[t,e]=await wt(async()=>{const t=await this.indexResource.getAll();for(const e of t)await this.indexResource.delete(e.id);for(const[t,e]of this.indexes.entries()){const[r,i,s]=t.split(":");await this.indexResource.insert({id:`index-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:r,fieldName:i,word:s,recordIds:e.recordIds,count:e.count,lastUpdated:(new Date).toISOString()})}})}installIndexingHooks(){this.database.plugins||(this.database.plugins={}),this.database.plugins.fulltext=this;for(const t of Object.values(this.database.resources))"fulltext_indexes"!==t.name&&this.installResourceHooks(t);this.database._fulltextProxyInstalled||(this.database._previousCreateResourceForFullText=this.database.createResource,this.database.createResource=async function(...t){const e=await this._previousCreateResourceForFullText(...t);return this.plugins?.fulltext&&"fulltext_indexes"!==e.name&&this.plugins.fulltext.installResourceHooks(e),e},this.database._fulltextProxyInstalled=!0);for(const t of Object.values(this.database.resources))"fulltext_indexes"!==t.name&&this.installResourceHooks(t)}installResourceHooks(t){t._insert=t.insert,t._update=t.update,t._delete=t.delete,t._deleteMany=t.deleteMany,this.wrapResourceMethod(t,"insert",async(e,r,i)=>{const[s]=r;return this.indexRecord(t.name,e.id,s).catch(()=>{}),e}),this.wrapResourceMethod(t,"update",async(e,r,i)=>{const[s,n]=r;return this.removeRecordFromIndex(t.name,s).catch(()=>{}),this.indexRecord(t.name,s,e).catch(()=>{}),e}),this.wrapResourceMethod(t,"delete",async(e,r,i)=>{const[s]=r;return this.removeRecordFromIndex(t.name,s).catch(()=>{}),e}),this.wrapResourceMethod(t,"deleteMany",async(e,r,i)=>{const[s]=r;for(const e of s)this.removeRecordFromIndex(t.name,e).catch(()=>{});return e})}async indexRecord(t,e,r){const i=this.getIndexedFields(t);if(i&&0!==i.length)for(const s of i){const i=this.getFieldValue(r,s);if(!i)continue;const n=this.tokenize(i);for(const r of n){if(r.length<this.config.minWordLength)continue;const i=`${t}:${s}:${r.toLowerCase()}`,n=this.indexes.get(i)||{recordIds:[],count:0};n.recordIds.includes(e)||(n.recordIds.push(e),n.count=n.recordIds.length),this.indexes.set(i,n)}}}async removeRecordFromIndex(t,e){for(const[r,i]of this.indexes.entries())if(r.startsWith(`${t}:`)){const t=i.recordIds.indexOf(e);t>-1&&(i.recordIds.splice(t,1),i.count=i.recordIds.length,0===i.recordIds.length?this.indexes.delete(r):this.indexes.set(r,i))}}getFieldValue(t,e){if(!e.includes("."))return t&&void 0!==t[e]?t[e]:null;const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return null;i=i[t]}return i}tokenize(t){if(!t)return[];return String(t).toLowerCase().replace(/[^\w\s\u00C0-\u017F]/g," ").split(/\s+/).filter(t=>t.length>0)}getIndexedFields(t){if(this.config.fields)return this.config.fields;return{users:["name","email"],products:["name","description"],articles:["title","content"]}[t]||[]}async search(t,e,r={}){const{fields:i=null,limit:s=this.config.maxResults,offset:n=0,exactMatch:a=!1}=r;if(!e||0===e.trim().length)return[];const o=this.tokenize(e),c=new Map,l=i||this.getIndexedFields(t);if(0===l.length)return[];for(const e of o)if(!(e.length<this.config.minWordLength))for(const r of l)if(a){const i=`${t}:${r}:${e.toLowerCase()}`,s=this.indexes.get(i);if(s)for(const t of s.recordIds){const e=c.get(t)||0;c.set(t,e+1)}}else for(const[i,s]of this.indexes.entries())if(i.startsWith(`${t}:${r}:${e.toLowerCase()}`))for(const t of s.recordIds){const e=c.get(t)||0;c.set(t,e+1)}return Array.from(c.entries()).map(([t,e])=>({recordId:t,score:e})).sort((t,e)=>e.score-t.score).slice(n,n+s)}async searchRecords(t,e,r={}){const i=await this.search(t,e,r);if(0===i.length)return[];const s=this.database.resources[t];if(!s)throw new Error(`Resource '${t}' not found`);const n=i.map(t=>t.recordId);return(await s.getMany(n)).filter(t=>t&&"object"==typeof t).map(t=>{const e=i.find(e=>e.recordId===t.id);return{...t,_searchScore:e?e.score:0}}).sort((t,e)=>e._searchScore-t._searchScore)}async rebuildIndex(t){const e=this.database.resources[t];if(!e)throw new Error(`Resource '${t}' not found`);for(const[e]of this.indexes.entries())e.startsWith(`${t}:`)&&this.indexes.delete(e);const r=await e.getAll();for(let e=0;e<r.length;e+=100){const i=r.slice(e,e+100);for(const e of i){const[r,i]=await wt(()=>this.indexRecord(t,e.id,e))}}await this.saveIndexes()}async getIndexStats(){const t={totalIndexes:this.indexes.size,resources:{},totalWords:0};for(const[e,r]of this.indexes.entries()){const[i,s]=e.split(":");t.resources[i]||(t.resources[i]={fields:{},totalRecords:new Set,totalWords:0}),t.resources[i].fields[s]||(t.resources[i].fields[s]={words:0,totalOccurrences:0}),t.resources[i].fields[s].words++,t.resources[i].fields[s].totalOccurrences+=r.count,t.resources[i].totalWords++;for(const e of r.recordIds)t.resources[i].totalRecords.add(e);t.totalWords++}for(const e in t.resources)t.resources[e].totalRecords=t.resources[e].totalRecords.size;return t}async rebuildAllIndexes({timeout:t}={}){return t?Promise.race([this._rebuildAllIndexesInternal(),new Promise((e,r)=>setTimeout(()=>r(new Error("Timeout")),t))]):this._rebuildAllIndexesInternal()}async _rebuildAllIndexesInternal(){const t=Object.keys(this.database.resources).filter(t=>"fulltext_indexes"!==t);for(const e of t){const[t,r]=await wt(()=>this.rebuildIndex(e))}}async clearIndex(t){for(const[e]of this.indexes.entries())e.startsWith(`${t}:`)&&this.indexes.delete(e);await this.saveIndexes()}async clearAllIndexes(){this.indexes.clear(),await this.saveIndexes()}}class Ci extends Tt{constructor(t={}){super(),this.config={collectPerformance:!1!==t.collectPerformance,collectErrors:!1!==t.collectErrors,collectUsage:!1!==t.collectUsage,retentionDays:t.retentionDays||30,flushInterval:t.flushInterval||6e4,...t},this.metrics={operations:{insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}},resources:{},errors:[],performance:[],startTime:(new Date).toISOString()},this.flushTimer=null}async setup(t){if(this.database=t,"undefined"!=typeof process&&"test"===process.env.NODE_ENV)return;const[e,r]=await wt(async()=>{const[e,r,i]=await wt(()=>t.createResource({name:"metrics",attributes:{id:"string|required",type:"string|required",resourceName:"string",operation:"string",count:"number|required",totalTime:"number|required",errors:"number|required",avgTime:"number|required",timestamp:"string|required",metadata:"json"}}));this.metricsResource=e?i:t.resources.metrics;const[s,n,a]=await wt(()=>t.createResource({name:"error_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",error:"string|required",timestamp:"string|required",metadata:"json"}}));this.errorsResource=s?a:t.resources.error_logs;const[o,c,l]=await wt(()=>t.createResource({name:"performance_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",duration:"number|required",timestamp:"string|required",metadata:"json"}}));this.performanceResource=o?l:t.resources.performance_logs});e||(this.metricsResource=t.resources.metrics,this.errorsResource=t.resources.error_logs,this.performanceResource=t.resources.performance_logs),this.installMetricsHooks(),"undefined"!=typeof process&&"test"!==process.env.NODE_ENV&&this.startFlushTimer()}async start(){}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"undefined"!=typeof process&&"test"!==process.env.NODE_ENV&&await this.flushMetrics()}installMetricsHooks(){for(const t of Object.values(this.database.resources))["metrics","error_logs","performance_logs"].includes(t.name)||this.installResourceHooks(t);this.database._createResource=this.database.createResource,this.database.createResource=async function(...t){const e=await this._createResource(...t);return this.plugins?.metrics&&!["metrics","error_logs","performance_logs"].includes(e.name)&&this.plugins.metrics.installResourceHooks(e),e}}installResourceHooks(t){t._insert=t.insert,t._update=t.update,t._delete=t.delete,t._deleteMany=t.deleteMany,t._get=t.get,t._getMany=t.getMany,t._getAll=t.getAll,t._list=t.list,t._listIds=t.listIds,t._count=t.count,t._page=t.page,t.insert=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._insert(...e));if(this.recordOperation(t.name,"insert",Date.now()-r,!i),i||this.recordError(t.name,"insert",s),!i)throw s;return n}.bind(this),t.update=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._update(...e));if(this.recordOperation(t.name,"update",Date.now()-r,!i),i||this.recordError(t.name,"update",s),!i)throw s;return n}.bind(this),t.delete=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._delete(...e));if(this.recordOperation(t.name,"delete",Date.now()-r,!i),i||this.recordError(t.name,"delete",s),!i)throw s;return n}.bind(this),t.deleteMany=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._deleteMany(...e));if(this.recordOperation(t.name,"delete",Date.now()-r,!i),i||this.recordError(t.name,"delete",s),!i)throw s;return n}.bind(this),t.get=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._get(...e));if(this.recordOperation(t.name,"get",Date.now()-r,!i),i||this.recordError(t.name,"get",s),!i)throw s;return n}.bind(this),t.getMany=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._getMany(...e));if(this.recordOperation(t.name,"get",Date.now()-r,!i),i||this.recordError(t.name,"get",s),!i)throw s;return n}.bind(this),t.getAll=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._getAll(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this),t.list=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._list(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this),t.listIds=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._listIds(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this),t.count=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._count(...e));if(this.recordOperation(t.name,"count",Date.now()-r,!i),i||this.recordError(t.name,"count",s),!i)throw s;return n}.bind(this),t.page=async function(...e){const r=Date.now(),[i,s,n]=await wt(()=>t._page(...e));if(this.recordOperation(t.name,"list",Date.now()-r,!i),i||this.recordError(t.name,"list",s),!i)throw s;return n}.bind(this)}recordOperation(t,e,r,i){this.metrics.operations[e]&&(this.metrics.operations[e].count++,this.metrics.operations[e].totalTime+=r,i&&this.metrics.operations[e].errors++),this.metrics.resources[t]||(this.metrics.resources[t]={insert:{count:0,totalTime:0,errors:0},update:{count:0,totalTime:0,errors:0},delete:{count:0,totalTime:0,errors:0},get:{count:0,totalTime:0,errors:0},list:{count:0,totalTime:0,errors:0},count:{count:0,totalTime:0,errors:0}}),this.metrics.resources[t][e]&&(this.metrics.resources[t][e].count++,this.metrics.resources[t][e].totalTime+=r,i&&this.metrics.resources[t][e].errors++),this.config.collectPerformance&&this.metrics.performance.push({resourceName:t,operation:e,duration:r,timestamp:(new Date).toISOString()})}recordError(t,e,r){this.config.collectErrors&&this.metrics.errors.push({resourceName:t,operation:e,error:r.message,stack:r.stack,timestamp:(new Date).toISOString()})}startFlushTimer(){this.flushTimer&&clearInterval(this.flushTimer),this.config.flushInterval>0&&(this.flushTimer=setInterval(()=>{this.flushMetrics().catch(()=>{})},this.config.flushInterval))}async flushMetrics(){if(!this.metricsResource)return;const[t,e]=await wt(async()=>{let t,e,r,i;"undefined"!=typeof process&&"test"===process.env.NODE_ENV?(t={},e={},r={},i={}):(t={global:"true"},e={perf:"true"},r={error:"true"},i={resource:"true"});for(const[e,r]of Object.entries(this.metrics.operations))r.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:"global",operation:e,count:r.count,totalTime:r.totalTime,errors:r.errors,avgTime:r.count>0?r.totalTime/r.count:0,timestamp:(new Date).toISOString(),metadata:t});for(const[t,e]of Object.entries(this.metrics.resources))for(const[r,s]of Object.entries(e))s.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:t,operation:r,count:s.count,totalTime:s.totalTime,errors:s.errors,avgTime:s.count>0?s.totalTime/s.count:0,timestamp:(new Date).toISOString(),metadata:i});if(this.config.collectPerformance&&this.metrics.performance.length>0)for(const t of this.metrics.performance)await this.performanceResource.insert({id:`perf-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.resourceName,operation:t.operation,duration:t.duration,timestamp:t.timestamp,metadata:e});if(this.config.collectErrors&&this.metrics.errors.length>0)for(const t of this.metrics.errors)await this.errorsResource.insert({id:`error-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:t.resourceName,operation:t.operation,error:t.error,stack:t.stack,timestamp:t.timestamp,metadata:r});this.resetMetrics()})}resetMetrics(){for(const t of Object.keys(this.metrics.operations))this.metrics.operations[t]={count:0,totalTime:0,errors:0};for(const t of Object.keys(this.metrics.resources))for(const e of Object.keys(this.metrics.resources[t]))this.metrics.resources[t][e]={count:0,totalTime:0,errors:0};this.metrics.performance=[],this.metrics.errors=[]}async getMetrics(t={}){const{type:e="operation",resourceName:r,operation:i,startDate:s,endDate:n,limit:a=100,offset:o=0}=t;if(!this.metricsResource)return[];let c=(await this.metricsResource.getAll()).filter(t=>(!e||t.type===e)&&((!r||t.resourceName===r)&&((!i||t.operation===i)&&(!(s&&new Date(t.timestamp)<new Date(s))&&!(n&&new Date(t.timestamp)>new Date(n))))));return c.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),c.slice(o,o+a)}async getErrorLogs(t={}){if(!this.errorsResource)return[];const{resourceName:e,operation:r,startDate:i,endDate:s,limit:n=100,offset:a=0}=t;let o=(await this.errorsResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(i&&new Date(t.timestamp)<new Date(i))&&!(s&&new Date(t.timestamp)>new Date(s)))));return o.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),o.slice(a,a+n)}async getPerformanceLogs(t={}){if(!this.performanceResource)return[];const{resourceName:e,operation:r,startDate:i,endDate:s,limit:n=100,offset:a=0}=t;let o=(await this.performanceResource.getAll()).filter(t=>(!e||t.resourceName===e)&&((!r||t.operation===r)&&(!(i&&new Date(t.timestamp)<new Date(i))&&!(s&&new Date(t.timestamp)>new Date(s)))));return o.sort((t,e)=>new Date(e.timestamp)-new Date(t.timestamp)),o.slice(a,a+n)}async getStats(){const t=new Date,e=new Date(t.getTime()-864e5),[r,i,s]=await Promise.all([this.getMetrics({startDate:e.toISOString()}),this.getErrorLogs({startDate:e.toISOString()}),this.getPerformanceLogs({startDate:e.toISOString()})]),n={period:"24h",totalOperations:0,totalErrors:i.length,avgResponseTime:0,operationsByType:{},resources:{},uptime:{startTime:this.metrics.startTime,duration:t.getTime()-new Date(this.metrics.startTime).getTime()}};for(const t of r)if("operation"===t.type){n.totalOperations+=t.count,n.operationsByType[t.operation]||(n.operationsByType[t.operation]={count:0,errors:0,avgTime:0}),n.operationsByType[t.operation].count+=t.count,n.operationsByType[t.operation].errors+=t.errors;const e=n.operationsByType[t.operation],r=e.count,i=(e.avgTime*(r-t.count)+t.totalTime)/r;e.avgTime=i}const a=r.reduce((t,e)=>t+e.totalTime,0),o=r.reduce((t,e)=>t+e.count,0);return n.avgResponseTime=o>0?a/o:0,n}async cleanupOldData(){const t=new Date;if(t.setDate(t.getDate()-this.config.retentionDays),this.metricsResource){const e=await this.getMetrics({endDate:t.toISOString()});for(const t of e)await this.metricsResource.delete(t.id)}if(this.errorsResource){const e=await this.getErrorLogs({endDate:t.toISOString()});for(const t of e)await this.errorsResource.delete(t.id)}if(this.performanceResource){const e=await this.getPerformanceLogs({endDate:t.toISOString()});for(const t of e)await this.performanceResource.delete(t.id)}}}var Ti=class extends At{constructor(t={}){super(),this.config=t,this.name=this.constructor.name,this.enabled=!1!==t.enabled}async initialize(t){this.database=t,this.emit("initialized",{replicator:this.name})}async replicate(t,e,r,i){throw new Error(`replicate() method must be implemented by ${this.name}`)}async replicateBatch(t,e){throw new Error(`replicateBatch() method must be implemented by ${this.name}`)}async testConnection(){throw new Error(`testConnection() method must be implemented by ${this.name}`)}async getStatus(){return{name:this.name,config:this.config,connected:!1}}async cleanup(){this.emit("cleanup",{replicator:this.name})}validateConfig(){return{isValid:!0,errors:[]}}};var Mi=class extends Ti{constructor(t={},e={}){super(t),this.projectId=t.projectId,this.datasetId=t.datasetId,this.bigqueryClient=null,this.credentials=t.credentials,this.location=t.location||"US",this.logTable=t.logTable,this.resources=this.parseResourcesConfig(e)}parseResourcesConfig(t){const e={};for(const[r,i]of Object.entries(t))"string"==typeof i?e[r]=[{table:i,actions:["insert"],transform:null}]:Array.isArray(i)?e[r]=i.map(t=>"string"==typeof t?{table:t,actions:["insert"],transform:null}:{table:t.table,actions:t.actions||["insert"],transform:t.transform||null}):"object"==typeof i&&(e[r]=[{table:i.table,actions:i.actions||["insert"],transform:i.transform||null}]);return e}validateConfig(){const t=[];this.projectId||t.push("projectId is required"),this.datasetId||t.push("datasetId is required"),0===Object.keys(this.resources).length&&t.push("At least one resource must be configured");for(const[e,r]of Object.entries(this.resources))for(const i of r){i.table||t.push(`Table name is required for resource '${e}'`),Array.isArray(i.actions)&&0!==i.actions.length||t.push(`Actions array is required for resource '${e}'`);const r=["insert","update","delete"],s=i.actions.filter(t=>!r.includes(t));s.length>0&&t.push(`Invalid actions for resource '${e}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`),i.transform&&"function"!=typeof i.transform&&t.push(`Transform must be a function for resource '${e}'`)}return{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);const[e,r,i]=await wt(()=>import("@google-cloud/bigquery"));if(!e)throw this.config.verbose&&console.warn(`[BigqueryReplicator] Failed to import BigQuery SDK: ${r.message}`),this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{BigQuery:s}=i;this.bigqueryClient=new s({projectId:this.projectId,credentials:this.credentials,location:this.location}),this.emit("initialized",{replicator:this.name,projectId:this.projectId,datasetId:this.datasetId,resources:Object.keys(this.resources)})}shouldReplicateResource(t){return this.resources.hasOwnProperty(t)}shouldReplicateAction(t,e){return!!this.resources[t]&&this.resources[t].some(t=>t.actions.includes(e))}getTablesForResource(t,e){return this.resources[t]?this.resources[t].filter(t=>t.actions.includes(e)).map(t=>({table:t.table,transform:t.transform})):[]}applyTransform(t,e){let r=this._cleanInternalFields(t);return e?e(JSON.parse(JSON.stringify(r))):r}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}async replicate(t,e,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(t,e))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(t,e);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const a=[],o=[],[c,l,u]=await wt(async()=>{const s=this.bigqueryClient.dataset(this.datasetId);for(const t of n){const[n,c]=await wt(async()=>{const n=s.table(t.table);let o;if("insert"===e){const e=this.applyTransform(r,t.transform);try{o=await n.insert([e])}catch(t){const{errors:e,response:r}=t;throw this.config.verbose&&(console.error("[BigqueryReplicator] BigQuery insert error details:"),e&&console.error(JSON.stringify(e,null,2)),r&&console.error(JSON.stringify(r,null,2))),t}}else if("update"===e){const e=this.applyTransform(r,t.transform),s=Object.keys(e).filter(t=>"id"!==t).map(t=>`${t} = @${t}`).join(", "),n={id:i,...e},a=`UPDATE \`${this.projectId}.${this.datasetId}.${t.table}\` SET ${s} WHERE id = @id`,c=2;let l=null;for(let t=1;t<=c;t++){const[e,r]=await wt(async()=>{const[t]=await this.bigqueryClient.createQueryJob({query:a,params:n,location:this.location});return await t.getQueryResults(),[t]});if(e){o=e;break}if(l=r,this.config.verbose&&(console.warn(`[BigqueryReplicator] Update attempt ${t} failed: ${r.message}`),r.errors&&(console.error("[BigqueryReplicator] BigQuery update error details:"),console.error("Errors:",JSON.stringify(r.errors,null,2)))),r?.message?.includes("streaming buffer")&&t<c){const t=30;this.config.verbose&&console.warn(`[BigqueryReplicator] Retrying in ${t} seconds due to streaming buffer issue`),await new Promise(e=>setTimeout(e,1e3*t));continue}throw r}if(!o)throw l}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const e=`DELETE FROM \`${this.projectId}.${this.datasetId}.${t.table}\` WHERE id = @id`;try{const[t]=await this.bigqueryClient.createQueryJob({query:e,params:{id:i},location:this.location});await t.getQueryResults(),o=[t]}catch(t){throw this.config.verbose&&(console.error("[BigqueryReplicator] BigQuery delete error details:"),console.error("Query:",e),t.errors&&console.error("Errors:",JSON.stringify(t.errors,null,2)),t.response&&console.error("Response:",JSON.stringify(t.response,null,2))),t}}}a.push({table:t.table,success:!0,jobId:o[0]?.id})});n||o.push({table:t.table,error:c.message})}if(this.logTable){const[n,a]=await wt(async()=>{const n=s.table(this.logTable);await n.insert([{resource_name:t,operation:e,record_id:i,data:JSON.stringify(r),timestamp:(new Date).toISOString(),source:"s3db-replicator"}])})}const c=0===o.length;return o.length>0&&console.warn(`[BigqueryReplicator] Replication completed with errors for ${t}:`,o),this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:i,tables:n.map(t=>t.table),results:a,errors:o,success:c}),{success:c,results:a,errors:o,tables:n.map(t=>t.table)}});return c?u:(this.config.verbose&&console.warn(`[BigqueryReplicator] Replication failed for ${t}: ${l.message}`),this.emit("replicator_error",{replicator:this.name,resourceName:t,operation:e,id:i,error:l.message}),{success:!1,error:l.message})}async replicateBatch(t,e){const r=[],i=[];for(const s of e){const[e,n,a]=await wt(()=>this.replicate(t,s.operation,s.data,s.id,s.beforeData));e?r.push(a):(this.config.verbose&&console.warn(`[BigqueryReplicator] Batch replication failed for record ${s.id}: ${n.message}`),i.push({id:s.id,error:n.message}))}return i.length>0&&console.warn(`[BigqueryReplicator] Batch replication completed with ${i.length} error(s) for ${t}:`,i),{success:0===i.length,results:r,errors:i}}async testConnection(){const[t,e]=await wt(async()=>{this.bigqueryClient||await this.initialize();const t=this.bigqueryClient.dataset(this.datasetId);return await t.getMetadata(),!0});return!!t||(this.config.verbose&&console.warn(`[BigqueryReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}async cleanup(){}getStatus(){return{...super.getStatus(),projectId:this.projectId,datasetId:this.datasetId,resources:this.resources,logTable:this.logTable}}};var Li=class extends Ti{constructor(t={},e={}){super(t),this.connectionString=t.connectionString,this.host=t.host,this.port=t.port||5432,this.database=t.database,this.user=t.user,this.password=t.password,this.client=null,this.ssl=t.ssl,this.logTable=t.logTable,this.resources=this.parseResourcesConfig(e)}parseResourcesConfig(t){const e={};for(const[r,i]of Object.entries(t))"string"==typeof i?e[r]=[{table:i,actions:["insert"]}]:Array.isArray(i)?e[r]=i.map(t=>"string"==typeof t?{table:t,actions:["insert"]}:{table:t.table,actions:t.actions||["insert"]}):"object"==typeof i&&(e[r]=[{table:i.table,actions:i.actions||["insert"]}]);return e}validateConfig(){const t=[];this.connectionString||this.host&&this.database||t.push("Either connectionString or host+database must be provided"),0===Object.keys(this.resources).length&&t.push("At least one resource must be configured");for(const[e,r]of Object.entries(this.resources))for(const i of r){i.table||t.push(`Table name is required for resource '${e}'`),Array.isArray(i.actions)&&0!==i.actions.length||t.push(`Actions array is required for resource '${e}'`);const r=["insert","update","delete"],s=i.actions.filter(t=>!r.includes(t));s.length>0&&t.push(`Invalid actions for resource '${e}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);const[e,r,i]=await wt(()=>import("pg"));if(!e)throw this.config.verbose&&console.warn(`[PostgresReplicator] Failed to import pg SDK: ${r.message}`),this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{Client:s}=i,n=this.connectionString?{connectionString:this.connectionString,ssl:this.ssl}:{host:this.host,port:this.port,database:this.database,user:this.user,password:this.password,ssl:this.ssl};this.client=new s(n),await this.client.connect(),this.logTable&&await this.createLogTableIfNotExists(),this.emit("initialized",{replicator:this.name,database:this.database||"postgres",resources:Object.keys(this.resources)})}async createLogTableIfNotExists(){const t=`\n CREATE TABLE IF NOT EXISTS ${this.logTable} (\n id SERIAL PRIMARY KEY,\n resource_name VARCHAR(255) NOT NULL,\n operation VARCHAR(50) NOT NULL,\n record_id VARCHAR(255) NOT NULL,\n data JSONB,\n timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),\n source VARCHAR(100) DEFAULT 's3db-replicator',\n created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()\n );\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_resource_name ON ${this.logTable}(resource_name);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_operation ON ${this.logTable}(operation);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_record_id ON ${this.logTable}(record_id);\n CREATE INDEX IF NOT EXISTS idx_${this.logTable}_timestamp ON ${this.logTable}(timestamp);\n `;await this.client.query(t)}shouldReplicateResource(t){return this.resources.hasOwnProperty(t)}shouldReplicateAction(t,e){return!!this.resources[t]&&this.resources[t].some(t=>t.actions.includes(e))}getTablesForResource(t,e){return this.resources[t]?this.resources[t].filter(t=>t.actions.includes(e)).map(t=>t.table):[]}async replicate(t,e,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(t,e))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(t,e);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const a=[],o=[],[c,l,u]=await wt(async()=>{for(const t of n){const[s,n]=await wt(async()=>{let s;if("insert"===e){const e=this._cleanInternalFields(r),i=Object.keys(e),n=i.map(t=>e[t]),a=i.map(t=>`"${t}"`).join(", "),o=i.map((t,e)=>`$${e+1}`).join(", "),c=`INSERT INTO ${t} (${a}) VALUES (${o}) ON CONFLICT (id) DO NOTHING RETURNING *`;s=await this.client.query(c,n)}else if("update"===e){const e=this._cleanInternalFields(r),n=Object.keys(e).filter(t=>"id"!==t),a=n.map((t,e)=>`"${t}"=$${e+1}`).join(", "),o=n.map(t=>e[t]);o.push(i);const c=`UPDATE ${t} SET ${a} WHERE id=$${n.length+1} RETURNING *`;s=await this.client.query(c,o)}else{if("delete"!==e)throw new Error(`Unsupported operation: ${e}`);{const e=`DELETE FROM ${t} WHERE id=$1 RETURNING *`;s=await this.client.query(e,[i])}}a.push({table:t,success:!0,rows:s.rows,rowCount:s.rowCount})});s||o.push({table:t,error:n.message})}if(this.logTable){const[s,n]=await wt(async()=>{await this.client.query(`INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,[t,e,i,JSON.stringify(r),(new Date).toISOString(),"s3db-replicator"])})}const s=0===o.length;return o.length>0&&console.warn(`[PostgresReplicator] Replication completed with errors for ${t}:`,o),this.emit("replicated",{replicator:this.name,resourceName:t,operation:e,id:i,tables:n,results:a,errors:o,success:s}),{success:s,results:a,errors:o,tables:n}});return c?u:(this.config.verbose&&console.warn(`[PostgresReplicator] Replication failed for ${t}: ${l.message}`),this.emit("replicator_error",{replicator:this.name,resourceName:t,operation:e,id:i,error:l.message}),{success:!1,error:l.message})}async replicateBatch(t,e){const r=[],i=[];for(const s of e){const[e,n,a]=await wt(()=>this.replicate(t,s.operation,s.data,s.id,s.beforeData));e?r.push(a):(this.config.verbose&&console.warn(`[PostgresReplicator] Batch replication failed for record ${s.id}: ${n.message}`),i.push({id:s.id,error:n.message}))}return i.length>0&&console.warn(`[PostgresReplicator] Batch replication completed with ${i.length} error(s) for ${t}:`,i),{success:0===i.length,results:r,errors:i}}async testConnection(){const[t,e]=await wt(async()=>(this.client||await this.initialize(),await this.client.query("SELECT 1"),!0));return!!t||(this.config.verbose&&console.warn(`[PostgresReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}async cleanup(){this.client&&await this.client.end()}getStatus(){return{...super.getStatus(),database:this.database||"postgres",resources:this.resources,logTable:this.logTable}}};class Ui{constructor(t){let e;const[r,i,s]=wt(()=>new URL(t));if(!r)throw new ft("Invalid connection string: "+t,{original:i,input:t});e=s,this.region="us-east-1","s3:"===e.protocol?this.defineFromS3(e):this.defineFromCustomUri(e);for(const[t,r]of e.searchParams.entries())this[t]=r}defineFromS3(t){const[e,r,i]=bt(()=>decodeURIComponent(t.hostname));if(!e)throw new ft("Invalid bucket in connection string",{original:r,input:t.hostname});this.bucket=i||"s3db";const[s,n,a]=bt(()=>decodeURIComponent(t.username));if(!s)throw new ft("Invalid accessKeyId in connection string",{original:n,input:t.username});this.accessKeyId=a;const[o,c,l]=bt(()=>decodeURIComponent(t.password));if(!o)throw new ft("Invalid secretAccessKey in connection string",{original:c,input:t.password});if(this.secretAccessKey=l,this.endpoint="https://s3.us-east-1.amazonaws.com",["/","",null].includes(t.pathname))this.keyPrefix="";else{let[,...e]=t.pathname.split("/");this.keyPrefix=[...e||[]].join("/")}}defineFromCustomUri(t){this.forcePathStyle=!0,this.endpoint=t.origin;const[e,r,i]=bt(()=>decodeURIComponent(t.username));if(!e)throw new ft("Invalid accessKeyId in connection string",{original:r,input:t.username});this.accessKeyId=i;const[s,n,a]=bt(()=>decodeURIComponent(t.password));if(!s)throw new ft("Invalid secretAccessKey in connection string",{original:n,input:t.password});if(this.secretAccessKey=a,["/","",null].includes(t.pathname))this.bucket="s3db",this.keyPrefix="";else{let[,e,...r]=t.pathname.split("/");if(e){const[t,r,i]=bt(()=>decodeURIComponent(e));if(!t)throw new ft("Invalid bucket in connection string",{original:r,input:e});this.bucket=i}else this.bucket="s3db";this.keyPrefix=[...r||[]].join("/")}}}class Fi extends At{constructor({verbose:t=!1,id:e=null,AwsS3Client:r,connectionString:i,parallelism:s=10}){super(),this.verbose=t,this.id=e??jt(),this.parallelism=s,this.config=new Ui(i),this.client=r||this.createClient()}createClient(){let t={region:this.config.region,endpoint:this.config.endpoint};this.config.forcePathStyle&&(t.forcePathStyle=!0),this.config.accessKeyId&&(t.credentials={accessKeyId:this.config.accessKeyId,secretAccessKey:this.config.secretAccessKey});const e=new R(t);return e.middlewareStack.add((t,e)=>async r=>{if("DeleteObjectsCommand"===e.commandName){const t=r.request.body;if(t&&"string"==typeof t){const e=await Ot(t);r.request.headers["Content-MD5"]=e}}return t(r)},{step:"build",name:"addContentMd5ForDeleteObjects",priority:"high"}),e}async sendCommand(t){this.emit("command.request",t.constructor.name,t.input);const[e,r,i]=await wt(()=>this.client.send(t));if(!e){throw ht(r,{bucket:this.config.bucket,key:t.input&&t.input.Key,commandName:t.constructor.name,commandInput:t.input})}return this.emit("command.response",t.constructor.name,i,t.input),i}async putObject({key:t,metadata:e,contentType:r,body:i,contentEncoding:s,contentLength:n}){const a="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";a&&Wt.join(a,t);const o={};if(e)for(const[t,r]of Object.entries(e)){o[String(t).replace(/[^a-zA-Z0-9\-_]/g,"_")]=String(r)}const c={Bucket:this.config.bucket,Key:a?Wt.join(a,t):t,Metadata:o,Body:i||Buffer.alloc(0)};let l,u;void 0!==r&&(c.ContentType=r),void 0!==s&&(c.ContentEncoding=s),void 0!==n&&(c.ContentLength=n);try{return l=await this.sendCommand(new j(c)),l}catch(e){throw u=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"PutObjectCommand",commandInput:c})}finally{this.emit("putObject",u||l,{key:t,metadata:e,contentType:r,body:i,contentEncoding:s,contentLength:n})}}async getObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?Wt.join(e,t):t};let i,s;try{return i=await this.sendCommand(new x(r)),i}catch(e){throw s=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"GetObjectCommand",commandInput:r})}finally{this.emit("getObject",s||i,{key:t})}}async headObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:e?Wt.join(e,t):t};let i,s;try{return i=await this.sendCommand(new E(r)),i}catch(e){throw s=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"HeadObjectCommand",commandInput:r})}finally{this.emit("headObject",s||i,{key:t})}}async copyObject({from:t,to:e}){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?Wt.join(this.config.keyPrefix,e):e,CopySource:Wt.join(this.config.bucket,this.config.keyPrefix?Wt.join(this.config.keyPrefix,t):t)};let i,s;try{return i=await this.sendCommand(new D(r)),i}catch(t){throw s=t,ht(t,{bucket:this.config.bucket,key:e,commandName:"CopyObjectCommand",commandInput:r})}finally{this.emit("copyObject",s||i,{from:t,to:e})}}async exists(t){const[e,r]=await wt(()=>this.headObject(t));if(e)return!0;if("NoSuchKey"===r.name||"NotFound"===r.name)return!1;throw r}async deleteObject(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";e&&Wt.join(e,t);const r={Bucket:this.config.bucket,Key:e?Wt.join(e,t):t};let i,s;try{return i=await this.sendCommand(new A(r)),i}catch(e){throw s=e,ht(e,{bucket:this.config.bucket,key:t,commandName:"DeleteObjectCommand",commandInput:r})}finally{this.emit("deleteObject",s||i,{key:t})}}async deleteObjects(t){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r=d(t,1e3),{results:s,errors:n}=await i.for(r).withConcurrency(this.parallelism).process(async t=>{for(const r of t)e&&Wt.join(e,r),this.config.bucket,await this.exists(r);const r={Bucket:this.config.bucket,Delete:{Objects:t.map(t=>({Key:e?Wt.join(e,t):t}))}};let i;const[s,n,a]=await wt(()=>this.sendCommand(new N(r)));if(!s)throw n;return i=a,i&&i.Errors&&i.Errors.length,i&&i.Deleted&&(i.Deleted.length,t.length),i}),a={deleted:s,notFound:n};return this.emit("deleteObjects",a,t),a}async deleteAll({prefix:t}={}){const e="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,i=0;do{const s=new I({Bucket:this.config.bucket,Prefix:e?Wt.join(e,t||""):t||"",ContinuationToken:r}),n=await this.client.send(s);if(n.Contents&&n.Contents.length>0){const e=new N({Bucket:this.config.bucket,Delete:{Objects:n.Contents.map(t=>({Key:t.Key}))}}),r=await this.client.send(e),s=r.Deleted?r.Deleted.length:0;i+=s,this.emit("deleteAll",{prefix:t,batch:s,total:i})}r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:t,totalDeleted:i}),i}async moveObject({from:t,to:e}){const[r,i]=await wt(async()=>{await this.copyObject({from:t,to:e}),await this.deleteObject(t)});if(!r)throw new lt("Unknown error in moveObject",{bucket:this.config.bucket,from:t,to:e,original:i});return!0}async listObjects({prefix:t,maxKeys:e=1e3,continuationToken:r}={}){const i={Bucket:this.config.bucket,MaxKeys:e,ContinuationToken:r,Prefix:this.config.keyPrefix?Wt.join(this.config.keyPrefix,t||""):t||""},[s,n,a]=await wt(()=>this.sendCommand(new I(i)));if(!s)throw new lt("Unknown error in listObjects",{prefix:t,bucket:this.config.bucket,original:n});return this.emit("listObjects",a,i),a}async count({prefix:t}={}){let e,r=0,i=!0;for(;i;){const s={prefix:t,continuationToken:e},n=await this.listObjects(s);r+=n.KeyCount||0,i=n.IsTruncated||!1,e=n.NextContinuationToken}return this.emit("count",r,{prefix:t}),r}async getAllKeys({prefix:t}={}){let e,r=[],i=!0;for(;i;){const s={prefix:t,continuationToken:e},n=await this.listObjects(s);n.Contents&&(r=r.concat(n.Contents.map(t=>t.Key))),i=n.IsTruncated||!1,e=n.NextContinuationToken}return this.config.keyPrefix&&(r=r.map(t=>t.replace(this.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t)),this.emit("getAllKeys",r,{prefix:t}),r}async getContinuationTokenAfterOffset(t={}){const{prefix:e,offset:r=1e3}=t;if(0===r)return null;let i,s=!0,n=0;for(;s;){const t={prefix:e,maxKeys:r<1e3?r:r-n>1e3?1e3:r-n,continuationToken:i},a=await this.listObjects(t);if(a.Contents&&(n+=a.Contents.length),s=a.IsTruncated||!1,i=a.NextContinuationToken,n>=r)break}return this.emit("getContinuationTokenAfterOffset",i||null,t),i||null}async getKeysPage(t={}){const{prefix:e,offset:r=0,amount:i=100}=t;let s,n=[],a=!0;if(r>0&&(s=await this.getContinuationTokenAfterOffset({prefix:e,offset:r}),!s))return this.emit("getKeysPage",[],t),[];for(;a;){const t={prefix:e,continuationToken:s},r=await this.listObjects(t);if(r.Contents&&(n=n.concat(r.Contents.map(t=>t.Key))),a=r.IsTruncated||!1,s=r.NextContinuationToken,n.length>=i){n=n.slice(0,i);break}}return this.config.keyPrefix&&(n=n.map(t=>t.replace(this.config.keyPrefix,"")).map(t=>t.startsWith("/")?t.replace("/",""):t)),this.emit("getKeysPage",n,t),n}async moveAllObjects({prefixFrom:t,prefixTo:e}){const r=await this.getAllKeys({prefix:t}),{results:s,errors:n}=await i.for(r).withConcurrency(this.parallelism).process(async r=>{const i=r.replace(t,e),[s,n]=await wt(async()=>{await this.moveObject({from:r,to:i})});if(!s)throw new lt("Unknown error in moveAllObjects",{bucket:this.config.bucket,from:r,to:i,original:n});return i});if(this.emit("moveAllObjects",{results:s,errors:n},{prefixFrom:t,prefixTo:e}),n.length>0)throw new Error("Some objects could not be moved");return s}}var qi=Fi;async function Bi(t,e,r){if(!this.passphrase)return e.push(new Z("Missing configuration for secrets encryption.",{actual:t,type:"encryptionKeyMissing",suggestion:"Provide a passphrase for secret encryption."})),t;const[i,s,n]=await wt(()=>_t(String(t),this.passphrase));return i?n:(e.push(new Z("Problem encrypting secret.",{actual:t,type:"encryptionProblem",error:s,suggestion:"Check the passphrase and input value."})),t)}async function zi(t,e,r){if(g(t))return t;const[i,s,n]=bt(()=>JSON.stringify(t));if(!i)throw new Z("Failed to stringify JSON",{original:s,input:t});return n}class Vi extends C{constructor({options:t,passphrase:e,autoEncrypt:r=!0}={}){super(p({},{useNewCustomCheckerFunction:!0,messages:{encryptionKeyMissing:"Missing configuration for secrets encryption.",encryptionProblem:"Problem encrypting secret. Actual: {actual}. Error: {error}"},defaults:{string:{trim:!0},object:{strict:"remove"},number:{convert:!0}}},t)),this.passphrase=e,this.autoEncrypt=r,this.alias("secret",{type:"string",custom:this.autoEncrypt?Bi:void 0,messages:{string:"The '{field}' field must be a string.",stringMin:"This secret '{field}' field length must be at least {expected} long."}}),this.alias("secretAny",{type:"any",custom:this.autoEncrypt?Bi:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Bi:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?zi:void 0})}}const Ki=new Proxy(Vi,{instance:null,construct(t,e){return this.instance||(this.instance=new t(...e)),this.instance}});const Wi={trim:t=>null==t?t:t.trim(),encrypt:async(t,{passphrase:e})=>{if(null==t)return t;const[r,i,s]=await yt(()=>_t(t,e));return r?s:t},decrypt:async(t,{passphrase:e})=>{if(null==t)return t;const[r,i,s]=await yt(()=>kt(t,e));return r?"null"===s?null:"undefined"!==s?s:void 0:t},toString:t=>null==t?t:String(t),fromArray:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>"string"==typeof t?t.replace(/\\/g,"\\\\").replace(new RegExp(`\\${e}`,"g"),`\\${e}`):String(t)).join(e)},toArray:(t,{separator:e})=>{if(Array.isArray(t))return t;if(null==t)return t;if(""===t)return[];const r=[];let i="",s=0;const n=String(t);for(;s<n.length;)"\\"===n[s]&&s+1<n.length?(i+=n[s+1],s+=2):n[s]===e?(r.push(i),i="",s++):(i+=n[s],s++);return r.push(i),r},toJSON:t=>{if(null===t)return null;if(void 0===t)return;if("string"==typeof t){const[e,r,i]=bt(()=>JSON.parse(t));return t}const[e,r,i]=bt(()=>JSON.stringify(t));return e?i:t},fromJSON:t=>{if(null===t)return null;if(void 0===t)return;if("string"!=typeof t)return t;if(""===t)return"";const[e,r,i]=bt(()=>JSON.parse(t));return e?i:t},toNumber:t=>g(t)?t.includes(".")?parseFloat(t):parseInt(t):t,toBool:t=>[!0,1,"true","1","yes","y"].includes(t),fromBool:t=>[!0,1,"true","1","yes","y"].includes(t)?"1":"0",fromBase62:t=>{if(null==t||""===t)return t;if("number"==typeof t)return t;if("string"==typeof t){const e=U(t);return isNaN(e)?void 0:e}},toBase62:t=>{if(null==t||""===t)return t;if("number"==typeof t)return L(t);if("string"==typeof t){const e=Number(t);return isNaN(e)?t:L(e)}return t},fromBase62Decimal:t=>{if(null==t||""===t)return t;if("number"==typeof t)return t;if("string"==typeof t){const e=q(t);return isNaN(e)?void 0:e}},toBase62Decimal:t=>{if(null==t||""===t)return t;if("number"==typeof t)return F(t);if("string"==typeof t){const e=Number(t);return isNaN(e)?t:F(e)}return t},fromArrayOfNumbers:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>{if("number"==typeof t&&!isNaN(t))return L(t);const e=Number(t);return isNaN(e)?"":L(e)}).join(e)},toArrayOfNumbers:(t,{separator:e})=>{if(Array.isArray(t))return t.map(t=>"number"==typeof t?t:U(t));if(null==t)return t;if(""===t)return[];const r=String(t),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===e?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(t=>{if("number"==typeof t)return t;if("string"==typeof t&&""!==t){const e=U(t);return isNaN(e)?NaN:e}return NaN})},fromArrayOfDecimals:(t,{separator:e})=>{if(null==t||!Array.isArray(t))return t;if(0===t.length)return"";return t.map(t=>{if("number"==typeof t&&!isNaN(t))return F(t);const e=Number(t);return isNaN(e)?"":F(e)}).join(e)},toArrayOfDecimals:(t,{separator:e})=>{if(Array.isArray(t))return t.map(t=>"number"==typeof t?t:q(t));if(null==t)return t;if(""===t)return[];const r=String(t),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===e?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(t=>{if("number"==typeof t)return t;if("string"==typeof t&&""!==t){const e=q(t);return isNaN(e)?NaN:e}return NaN})}};class Ji{constructor(t){const{map:e,name:r,attributes:i,passphrase:s,version:n=1,options:a={}}=t;this.name=r,this.version=n,this.attributes=i||{},this.passphrase=s??"secret",this.options=p({},this.defaultOptions(),a),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const o=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new Ki({autoEncrypt:!1}).compile(p({$$async:!0},o)),this.options.generateAutoHooks&&this.generateAutoHooks(),m(e)){const t=$(this.attributes,{safe:!0}),e=Object.keys(t).filter(t=>!t.includes("$$")),r=this.extractObjectKeys(this.attributes),i=[...new Set([...e,...r])],{mapping:s,reversedMapping:n}=function(t){const e={},r={};return t.forEach((t,i)=>{const s=L(i);e[t]=s,r[s]=t}),{mapping:e,reversedMapping:r}}(i);this.map=s,this.reversedMap=n}else this.map=e,this.reversedMap=y(e)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(t,e,r){this.options.hooks[t][e]||(this.options.hooks[t][e]=[]),this.options.hooks[t][e]=b([...this.options.hooks[t][e],r])}extractObjectKeys(t,e=""){const r=[];for(const[i,s]of Object.entries(t)){if(i.startsWith("$$"))continue;const t=e?`${e}.${i}`:i;"object"!=typeof s||null===s||Array.isArray(s)||(r.push(t),"object"===s.$$type&&r.push(...this.extractObjectKeys(s,t)))}return r}generateAutoHooks(){const t=$(w(this.attributes),{safe:!0});for(const[e,r]of Object.entries(t))if(r.includes("array")){if(r.includes("items:string"))this.addHook("beforeMap",e,"fromArray"),this.addHook("afterUnmap",e,"toArray");else if(r.includes("items:number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",e,"fromArrayOfNumbers"),this.addHook("afterUnmap",e,"toArrayOfNumbers")):(this.addHook("beforeMap",e,"fromArrayOfDecimals"),this.addHook("afterUnmap",e,"toArrayOfDecimals"))}}else if(r.includes("secret"))this.options.autoEncrypt&&this.addHook("beforeMap",e,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",e,"decrypt");else{if(r.includes("number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",e,"toBase62"),this.addHook("afterUnmap",e,"fromBase62")):(this.addHook("beforeMap",e,"toBase62Decimal"),this.addHook("afterUnmap",e,"fromBase62Decimal"));continue}r.includes("boolean")?(this.addHook("beforeMap",e,"fromBool"),this.addHook("afterUnmap",e,"toBool")):(r.includes("json")||"object"===r||r.includes("object"))&&(this.addHook("beforeMap",e,"toJSON"),this.addHook("afterUnmap",e,"fromJSON"))}}static import(t){let{map:e,name:r,options:i,version:s,attributes:n}=g(t)?JSON.parse(t):t;const[a,o,c]=bt(()=>Ji._importAttributes(n));if(!a)throw new pt("Failed to import schema attributes",{original:o,input:n});n=c;return new Ji({map:e,name:r,options:i,version:s,attributes:n})}static _importAttributes(t){if("string"==typeof t){const[e,r,i]=bt(()=>JSON.parse(t));if(e&&"object"==typeof i&&null!==i){const[e,r,s]=bt(()=>Ji._importAttributes(i));if(!e)throw new pt("Failed to parse nested schema attribute",{original:r,input:t});return s}return t}if(Array.isArray(t)){const[e,r,i]=bt(()=>t.map(t=>Ji._importAttributes(t)));if(!e)throw new pt("Failed to import array schema attributes",{original:r,input:t});return i}if("object"==typeof t&&null!==t){const e={};for(const[r,i]of Object.entries(t)){const[t,s,n]=bt(()=>Ji._importAttributes(i));if(!t)throw new pt("Failed to import object schema attribute",{original:s,key:r,input:i});e[r]=n}return e}return t}export(){return{version:this.version,name:this.name,options:this.options,attributes:this._exportAttributes(this.attributes),map:this.map}}_exportAttributes(t){if("string"==typeof t)return t;if(Array.isArray(t))return t.map(t=>this._exportAttributes(t));if("object"==typeof t&&null!==t){const e={};for(const[r,i]of Object.entries(t))e[r]=this._exportAttributes(i);return e}return t}async applyHooksActions(t,e){const r=w(t);for(const[t,i]of Object.entries(this.options.hooks[e]))for(const e of i){const i=v(r,t);void 0!==i&&"function"==typeof Wi[e]&&S(r,t,await Wi[e](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}return r}async validate(t,{mutateOriginal:e=!1}={}){let r=e?t:w(t);return await this.validator(r)}async mapper(t){let e=w(t);e=await this.applyHooksActions(e,"beforeMap");const r=$(e,{safe:!0}),i={_v:this.version+""};for(const[t,e]of Object.entries(r)){const r=this.map[t]||t,s=this.getAttributeDefinition(t);"number"==typeof e&&"string"==typeof s&&s.includes("number")?i[r]=L(e):"string"==typeof e?"[object Object]"===e?i[r]="{}":(e.startsWith("{")||e.startsWith("["),i[r]=e):Array.isArray(e)||"object"==typeof e&&null!==e?i[r]=JSON.stringify(e):i[r]=e}return await this.applyHooksActions(i,"afterMap"),i}async unmapper(t,e){let r=w(t);delete r._v,r=await this.applyHooksActions(r,"beforeUnmap");const i=e?y(e):this.reversedMap,s={};for(const[t,e]of Object.entries(r)){const r=i&&i[t]?i[t]:t;let n=e;const a=this.getAttributeDefinition(r);if("string"!=typeof a||!a.includes("number")||a.includes("array")||a.includes("decimal")){if("string"==typeof e)if("[object Object]"===e)n={};else if(e.startsWith("{")||e.startsWith("[")){const[t,r,i]=bt(()=>JSON.parse(e));t&&(n=i)}}else"string"==typeof n&&""!==n?n=U(n):"number"==typeof n||(n=void 0);if(this.attributes&&"string"==typeof a&&a.includes("array"))if(Array.isArray(n));else if("string"==typeof n&&n.trim().startsWith("[")){const[t,e,r]=bt(()=>JSON.parse(n));t&&Array.isArray(r)&&(n=r)}else n=Wi.toArray(n,{separator:this.options.arraySeparator});if(this.options.hooks&&this.options.hooks.afterUnmap&&this.options.hooks.afterUnmap[r])for(const t of this.options.hooks.afterUnmap[r])"function"==typeof Wi[t]&&(n=await Wi[t](n,{passphrase:this.passphrase,separator:this.options.arraySeparator}));s[r]=n}await this.applyHooksActions(s,"afterUnmap");const n=P(s);for(const[e,r]of Object.entries(t))e.startsWith("$")&&(n[e]=r);return n}getAttributeDefinition(t){const e=t.split(".");let r=this.attributes;for(const t of e){if(!r)return;r=r[t]}return r}preprocessAttributesForValidation(t){const e={};for(const[r,i]of Object.entries(t))if("object"!=typeof i||null===i||Array.isArray(i))e[r]=i;else{const t=i.$$type&&i.$$type.includes("required"),s=i.$$type&&i.$$type.includes("optional"),n={type:"object",properties:this.preprocessAttributesForValidation(i),strict:!1};t||(s||this.allNestedObjectsOptional)&&(n.optional=!0),e[r]=n}return e}}var Hi=Ji;const Yi=2047;var Gi=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:Yi,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r,originalData:i}){const s=W(r),n=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}});if(s>n)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${s} bytes, effective limit: ${n} bytes, absolute limit: 2047 bytes`);return{mappedData:r,body:JSON.stringify(r)}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){const n=W(i),a=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}});if(n>a)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, effective limit: ${a} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:JSON.stringify(i)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){const s=W(i),n=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}});if(s>n)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${s} bytes, effective limit: ${n} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:""}}});var Qi=Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:async function({resource:t,data:e,mappedData:r,originalData:i}){const s=W(r);return s>Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}})&&t.emit("exceedsLimit",{operation:"insert",totalSize:s,limit:2047,excess:s-2047,data:i||e}),{mappedData:r,body:JSON.stringify(e)}},handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){const n=W(i);return n>Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}})&&t.emit("exceedsLimit",{operation:"update",id:e,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){const n=W(i);return n>Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e}})&&t.emit("exceedsLimit",{operation:"upsert",id:e,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}}});const Xi="$truncated",Zi="true",ts=B(Xi)+B(Zi);async function es({resource:t,data:e,mappedData:r,originalData:i}){const s=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}}),n=K(r),a=Object.entries(n).sort(([,t],[,e])=>t-e),o={};let c=0,l=!1;r._v&&(o._v=r._v,c+=n._v);for(const[t,e]of a){if("_v"===t)continue;const i=r[t];if(!(c+(e+(l?0:ts))<=s)){const e=s-c-(l?0:ts);if(e>0){const r=rs(i,e);o[t]=r,l=!0,c+=B(r)}else o[t]="",l=!0;break}o[t]=i,c+=e}let u=W(o)+(l?ts:0);for(;u>s;){const t=Object.keys(o).filter(t=>"_v"!==t&&"$truncated"!==t);if(0===t.length)break;o[t[t.length-1]]="",u=W(o)+ts,l=!0}return l&&(o[Xi]=Zi),{mappedData:o,body:JSON.stringify(r)}}function rs(t,e){if("string"==typeof t)return is(t,e);if("object"==typeof t&&null!==t){return is(JSON.stringify(t),e)}return is(String(t),e)}function is(t,e){const r=new TextEncoder;let i=r.encode(t);if(i.length<=e)return t;let s=t.length;for(;s>0;){const n=t.substring(0,s);if(i=r.encode(n),i.length<=e)return n;s--}return""}var ss=Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){return{metadata:e,body:r}},handleInsert:es,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){return es({resource:t,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return es({resource:t,data:r,mappedData:i})}});const ns="$overflow",as="true",os=B(ns)+B(as);async function cs({resource:t,data:e,mappedData:r,originalData:i}){const s=Y({s3Limit:Yi,systemConfig:{version:t.version,timestamps:t.config.timestamps,id:e.id}}),n=K(r),a=Object.entries(n).sort(([,t],[,e])=>t-e),o={},c={};let l=0,u=!1;r._v&&(o._v=r._v,l+=n._v);let h=s;for(const[t,e]of a)"_v"!==t&&(!u&&l+e>s&&(h-=os,u=!0),!u&&l+e<=h?(o[t]=r[t],l+=e):(c[t]=r[t],u=!0));u&&(o[ns]=as);const f=Object.keys(c).length>0;let d=f?JSON.stringify(c):"";return f||(d="{}"),{mappedData:o,body:d}}async function ls({resource:t,data:e,mappedData:r}){const i={_v:r._v||String(t.version)};i._map=JSON.stringify(t.schema.map);return{mappedData:i,body:JSON.stringify(r)}}const us={"user-managed":Qi,"enforce-limits":Gi,"truncate-data":ss,"body-overflow":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){let i={};if(r&&""!==r.trim()){const[t,e,s]=bt(()=>JSON.parse(r));i=t?s:{}}const s={...i,...e};return delete s.$overflow,{metadata:s,body:r}},handleInsert:cs,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i,originalData:s}){return cs({resource:t,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return cs({resource:t,data:r,mappedData:i})}}),"body-only":Object.freeze({__proto__:null,handleGet:async function({resource:t,metadata:e,body:r}){let i={};if(r&&""!==r.trim()){const[t,e,s]=bt(()=>JSON.parse(r));i=t?s:{}}return{metadata:{...i,...e},body:r}},handleInsert:ls,handleUpdate:async function({resource:t,id:e,data:r,mappedData:i}){const s={_v:i._v||String(t.version)};return s._map=JSON.stringify(t.schema.map),{mappedData:s,body:JSON.stringify(i)}},handleUpsert:async function({resource:t,id:e,data:r,mappedData:i}){return ls({resource:t,data:r,mappedData:i})}})};function hs(t){const e=us[t];if(!e)throw new Error(`Unknown behavior: ${t}. Available behaviors: ${Object.keys(us).join(", ")}`);return e}const fs=Object.keys(us),ds="user-managed";class ps extends At{constructor(t={}){super(),this._instanceId=Math.random().toString(36).slice(2,8);const e=function(t){const e=[];t.name?"string"!=typeof t.name?e.push("Resource 'name' must be a string"):""===t.name.trim()&&e.push("Resource 'name' cannot be empty"):e.push("Resource 'name' is required");t.client||e.push("S3 'client' is required");t.attributes?"object"!=typeof t.attributes||Array.isArray(t.attributes)?e.push("Resource 'attributes' must be an object"):0===Object.keys(t.attributes).length&&e.push("Resource 'attributes' cannot be empty"):e.push("Resource 'attributes' are required");void 0!==t.version&&"string"!=typeof t.version&&e.push("Resource 'version' must be a string");void 0!==t.behavior&&"string"!=typeof t.behavior&&e.push("Resource 'behavior' must be a string");void 0!==t.passphrase&&"string"!=typeof t.passphrase&&e.push("Resource 'passphrase' must be a string");void 0!==t.parallelism&&("number"==typeof t.parallelism&&Number.isInteger(t.parallelism)?t.parallelism<1&&e.push("Resource 'parallelism' must be greater than 0"):e.push("Resource 'parallelism' must be an integer"));void 0===t.observers||Array.isArray(t.observers)||e.push("Resource 'observers' must be an array");const r=["cache","autoDecrypt","timestamps","paranoid","allNestedObjectsOptional"];for(const i of r)void 0!==t[i]&&"boolean"!=typeof t[i]&&e.push(`Resource '${i}' must be a boolean`);void 0!==t.idGenerator&&("function"!=typeof t.idGenerator&&"number"!=typeof t.idGenerator?e.push("Resource 'idGenerator' must be a function or a number (size)"):"number"==typeof t.idGenerator&&t.idGenerator<=0&&e.push("Resource 'idGenerator' size must be greater than 0"));void 0!==t.idSize&&("number"==typeof t.idSize&&Number.isInteger(t.idSize)?t.idSize<=0&&e.push("Resource 'idSize' must be greater than 0"):e.push("Resource 'idSize' must be an integer"));if(void 0!==t.partitions)if("object"!=typeof t.partitions||Array.isArray(t.partitions))e.push("Resource 'partitions' must be an object");else for(const[r,i]of Object.entries(t.partitions))if("object"!=typeof i||Array.isArray(i))e.push(`Partition '${r}' must be an object`);else if(i.fields)if("object"!=typeof i.fields||Array.isArray(i.fields))e.push(`Partition '${r}.fields' must be an object`);else for(const[t,s]of Object.entries(i.fields))"string"!=typeof s&&e.push(`Partition '${r}.fields.${t}' must be a string`);else e.push(`Partition '${r}' must have a 'fields' property`);if(void 0!==t.hooks)if("object"!=typeof t.hooks||Array.isArray(t.hooks))e.push("Resource 'hooks' must be an object");else{const r=["beforeInsert","afterInsert","beforeUpdate","afterUpdate","beforeDelete","afterDelete"];for(const[i,s]of Object.entries(t.hooks))if(r.includes(i))if(Array.isArray(s))for(let t=0;t<s.length;t++){const e=s[t];if("function"==typeof e);else if("string"==typeof e)continue}else e.push(`Resource 'hooks.${i}' must be an array`);else e.push(`Invalid hook event '${i}'. Valid events: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}(t);if(!e.isValid)throw new gt(`Invalid Resource ${t.name} configuration`,{resourceName:t.name,validation:e.errors,operation:"constructor",suggestion:"Check resource config and attributes."});const{name:r,client:i,version:s="1",attributes:n={},behavior:a=ds,passphrase:o="secret",parallelism:c=10,observers:l=[],cache:u=!1,autoDecrypt:h=!0,timestamps:f=!1,partitions:d={},paranoid:p=!0,allNestedObjectsOptional:g=!0,hooks:m={},idGenerator:y,idSize:b=22,versioningEnabled:w=!1}=t;if(this.name=r,this.client=i,this.version=s,this.behavior=a,this.observers=l,this.parallelism=c,this.passphrase=o??"secret",this.versioningEnabled=w,this.idGenerator=this.configureIdGenerator(y,b),this.config={cache:u,hooks:m,paranoid:p,timestamps:f,partitions:d,autoDecrypt:h,allNestedObjectsOptional:g},this.hooks={beforeInsert:[],afterInsert:[],beforeUpdate:[],afterUpdate:[],beforeDelete:[],afterDelete:[]},this.attributes=n||{},this.map=t.map,this.applyConfiguration({map:this.map}),m)for(const[t,e]of Object.entries(m))if(Array.isArray(e)&&this.hooks[t])for(const r of e)"function"==typeof r&&this.hooks[t].push(r.bind(this));this._initMiddleware()}configureIdGenerator(r,i){return"function"==typeof r?r:"number"==typeof r&&r>0?t(e,r):"number"==typeof i&&i>0&&22!==i?t(e,i):jt}get options(){return{timestamps:this.config.timestamps,partitions:this.config.partitions||{},cache:this.config.cache,autoDecrypt:this.config.autoDecrypt,paranoid:this.config.paranoid,allNestedObjectsOptional:this.config.allNestedObjectsOptional}}export(){const t=this.schema.export();return t.behavior=this.behavior,t.timestamps=this.config.timestamps,t.partitions=this.config.partitions||{},t.paranoid=this.config.paranoid,t.allNestedObjectsOptional=this.config.allNestedObjectsOptional,t.autoDecrypt=this.config.autoDecrypt,t.cache=this.config.cache,t.hooks=this.hooks,t.map=this.map,t}applyConfiguration({map:t}={}){this.config.timestamps&&(this.attributes.createdAt||(this.attributes.createdAt="string|optional"),this.attributes.updatedAt||(this.attributes.updatedAt="string|optional"),this.config.partitions||(this.config.partitions={}),this.config.partitions.byCreatedDate||(this.config.partitions.byCreatedDate={fields:{createdAt:"date|maxlength:10"}}),this.config.partitions.byUpdatedDate||(this.config.partitions.byUpdatedDate={fields:{updatedAt:"date|maxlength:10"}})),this.setupPartitionHooks(),this.versioningEnabled&&(this.config.partitions.byVersion||(this.config.partitions.byVersion={fields:{_v:"string"}})),this.schema=new Hi({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:this.version,options:{autoDecrypt:this.config.autoDecrypt,allNestedObjectsOptional:this.config.allNestedObjectsOptional},map:t||this.map}),this.validatePartitions()}updateAttributes(t){const e=this.attributes;return this.attributes=t,this.applyConfiguration({map:this.schema?.map}),{oldAttributes:e,newAttributes:t}}addHook(t,e){this.hooks[t]&&this.hooks[t].push(e.bind(this))}async executeHooks(t,e){if(!this.hooks[t])return e;let r=e;for(const e of this.hooks[t])r=await e(r);return r}setupPartitionHooks(){if(!this.config.partitions)return;const t=this.config.partitions;0!==Object.keys(t).length&&(this.hooks.afterInsert||(this.hooks.afterInsert=[]),this.hooks.afterInsert.push(async t=>(await this.createPartitionReferences(t),t)),this.hooks.afterDelete||(this.hooks.afterDelete=[]),this.hooks.afterDelete.push(async t=>(await this.deletePartitionReferences(t),t)))}async validate(t){const e={original:w(t),isValid:!1,errors:[]},r=await this.schema.validate(t,{mutateOriginal:!1});return!0===r?e.isValid=!0:e.errors=r,e.data=t,e}validatePartitions(){if(!this.config.partitions)return;const t=this.config.partitions;if(0===Object.keys(t).length)return;const e=Object.keys(this.attributes||{});for(const[r,i]of Object.entries(t))if(i.fields)for(const t of Object.keys(i.fields))if(!this.fieldExistsInAttributes(t))throw new mt(`Partition '${r}' uses field '${t}' which does not exist in resource attributes. Available fields: ${e.join(", ")}.`,{resourceName:this.name,partitionName:r,fieldName:t,availableFields:e,operation:"validatePartitions"})}fieldExistsInAttributes(t){if(t.startsWith("_"))return!0;if(!t.includes("."))return Object.keys(this.attributes||{}).includes(t);const e=t.split(".");let r=this.attributes||{};for(const t of e){if(!r||"object"!=typeof r||!(t in r))return!1;r=r[t]}return!0}applyPartitionRule(t,e){if(null==t)return t;let r=t;if("string"==typeof e&&e.includes("maxlength:")){const t=e.match(/maxlength:(\d+)/);if(t){const e=parseInt(t[1]);"string"==typeof r&&r.length>e&&(r=r.substring(0,e))}}if(e.includes("date"))if(r instanceof Date)r=r.toISOString().split("T")[0];else if("string"==typeof r)if(r.includes("T")&&r.includes("Z"))r=r.split("T")[0];else{const t=new Date(r);isNaN(t.getTime())||(r=t.toISOString().split("T")[0])}return r}getResourceKey(t){return Kt("resource="+this.name,"data",`id=${t}`)}getPartitionKey({partitionName:t,id:e,data:r}){if(!this.config.partitions||!this.config.partitions[t])throw new mt(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"getPartitionKey"});const i=this.config.partitions[t],s=[],n=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of n){const i=this.getNestedFieldValue(r,t),n=this.applyPartitionRule(i,e);if(null==n)return null;s.push(`${t}=${n}`)}if(0===s.length)return null;const a=e||r?.id;return a?Kt(`resource=${this.name}`,`partition=${t}`,...s,`id=${a}`):null}getNestedFieldValue(t,e){if(!e.includes("."))return t[e];const r=e.split(".");let i=t;for(const t of r){if(!i||"object"!=typeof i||!(t in i))return;i=i[t]}return i}calculateContentLength(t){return t?Buffer.isBuffer(t)?t.length:"string"==typeof t?Buffer.byteLength(t,"utf8"):"object"==typeof t?Buffer.byteLength(JSON.stringify(t),"utf8"):Buffer.byteLength(String(t),"utf8"):0}async insert({id:t,...e}){if(await this.exists(t))throw new Error(`Resource with id '${t}' already exists`);this.getResourceKey(t||"(auto)"),this.options.timestamps&&(e.createdAt=(new Date).toISOString(),e.updatedAt=(new Date).toISOString());const r={id:t,...this.applyDefaults(e)},i=await this.executeHooks("beforeInsert",r),s=Object.keys(i).filter(t=>!(t in r)||i[t]!==r[t]),n={};for(const t of s)n[t]=i[t];const{errors:a,isValid:o,data:c}=await this.validate(i);if(!o){const t=a&&a.length&&a[0].message?a[0].message:"Insert failed";throw new ct({bucket:this.client.config.bucket,resourceName:this.name,attributes:i,validation:a,message:t})}const{id:l,...u}=c;Object.assign(u,n);const h=l||t||this.idGenerator(),f=await this.schema.mapper(u);f._v=String(this.version);const d=hs(this.behavior),{mappedData:p,body:g}=await d.handleInsert({resource:this,data:u,mappedData:f,originalData:r}),m=p,y=this.getResourceKey(h);let b;if(g&&""!==g){const[t,e]=await wt(()=>Promise.resolve(JSON.parse(g)));t&&(b="application/json")}if("body-only"===this.behavior&&(!g||""===g))throw new Error(`[Resource.insert] Attempt to save object without body! Data: id=${h}, resource=${this.name}`);const[w,v,S]=await wt(()=>this.client.putObject({key:y,body:g,contentType:b,metadata:m}));if(!w){const t=v&&v.message?v.message:"";if(t.includes("metadata headers exceed")||t.includes("Insert failed")){const t=W(m),e=Y({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:h}}),r=t-e;throw v.totalSize=t,v.limit=2047,v.effectiveLimit=e,v.excess=r,new gt("metadata headers exceed",{resourceName:this.name,operation:"insert",id:h,totalSize:t,effectiveLimit:e,excess:r,suggestion:"Reduce metadata size or number of fields."})}throw ht(v,{bucket:this.client.config.bucket,key:y,resourceName:this.name,operation:"insert",id:h})}let _=await this.composeFullObjectFromWrite({id:h,metadata:m,body:g,behavior:this.behavior});const k=await this.executeHooks("afterInsert",_);return this.emit("insert",{..._,$before:{...r},$after:{...k}}),k}async get(t){if(_(t))throw new Error("id cannot be an object");if(m(t))throw new Error("id cannot be empty");const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.getObject(e));if(!r)throw ht(i,{bucket:this.client.config.bucket,key:e,resourceName:this.name,operation:"get",id:t});if(0===s.ContentLength){const r=new Error(`No such key: ${e} [bucket:${this.client.config.bucket}]`);throw r.name="NoSuchKey",ht(r,{bucket:this.client.config.bucket,key:e,resourceName:this.name,operation:"get",id:t})}const n=s.Metadata?._v||this.version,a="string"==typeof n&&n.startsWith("v")?n.slice(1):n,o=await this.getSchemaForVersion(a);let c=await o.unmapper(s.Metadata);const l=hs(this.behavior);let u="";if(s.ContentLength>0){const[t,r,i]=await wt(()=>this.client.getObject(e));u=t?await ji(i.Body):""}const{metadata:h}=await l.handleGet({resource:this,metadata:c,body:u});let f=await this.composeFullObjectFromWrite({id:t,metadata:h,body:u,behavior:this.behavior});f._contentLength=s.ContentLength,f._lastModified=s.LastModified,f._hasContent=s.ContentLength>0,f._mimeType=s.ContentType||null,f._v=a,s.VersionId&&(f._versionId=s.VersionId),s.Expiration&&(f._expiresAt=s.Expiration),f._definitionHash=this.getDefinitionHash(),a!==this.version&&(f=await this.applyVersionMapping(f,a,this.version)),this.emit("get",f);return f}async exists(t){const e=this.getResourceKey(t),[r,i]=await wt(()=>this.client.headObject(e));return r}async update(t,e){if(m(t))throw new Error("id cannot be empty");if(!await this.exists(t))throw new Error(`Resource with id '${t}' does not exist`);const r=await this.get(t),i=w(e);let s=w(r);for(const[t,e]of Object.entries(i))if(t.includes(".")){let r=s;const i=t.split(".");for(let t=0;t<i.length-1;t++)"object"==typeof r[i[t]]&&null!==r[i[t]]||(r[i[t]]={}),r=r[i[t]];r[i[i.length-1]]=w(e)}else"object"!=typeof e||null===e||Array.isArray(e)?s[t]=w(e):s[t]=p({},s[t],e);if(this.config.timestamps){const t=(new Date).toISOString();s.updatedAt=t,s.metadata||(s.metadata={}),s.metadata.updatedAt=t}const n=await this.executeHooks("beforeUpdate",w(s)),a={...r,...n,id:t},{isValid:o,errors:c,data:l}=await this.validate(w(a));if(!o)throw new ct({bucket:this.client.config.bucket,resourceName:this.name,attributes:n,validation:c,message:"validation: "+(c&&c.length?JSON.stringify(c):"unknown")});await this.schema.mapper(l);const u=hs(this.behavior),h=await this.schema.mapper({...r,...n});h._v=String(this.version),await u.handleUpdate({resource:this,id:t,data:{...r,...n},mappedData:h,originalData:{...i,id:t}});const{id:f,...d}=l,g={...r,id:t},y={...d,id:t};await this.handlePartitionReferenceUpdates(g,y);const b=await this.schema.mapper(d);b._v=String(this.version);const v=hs(this.behavior),{mappedData:S,body:_}=await v.handleUpdate({resource:this,id:t,data:d,mappedData:b,originalData:{...i,id:t}}),k=S,O=this.getResourceKey(t);let R,j=_;if(""===_&&"body-overflow"!==this.behavior){const[t,e,r]=await wt(()=>this.client.getObject(O));if(t&&r.ContentLength>0){const t=Buffer.from(await r.Body.transformToByteArray()),e=t.toString(),[i,s]=await wt(()=>Promise.resolve(JSON.parse(e)));i||(j=t,R=r.ContentType)}}let x=R;if(j&&""!==j&&!x){const[t,e]=await wt(()=>Promise.resolve(JSON.parse(j)));t&&(x="application/json")}this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(t,r);const[E,D]=await wt(()=>this.client.putObject({key:O,body:j,contentType:x,metadata:k}));if(!E&&D&&D.message&&D.message.includes("metadata headers exceed")){const e=W(k),r=Y({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:t}}),i=e-r;throw D.totalSize=e,D.limit=2047,D.effectiveLimit=r,D.excess=i,this.emit("exceedsLimit",{operation:"update",totalSize:e,limit:2047,effectiveLimit:r,excess:i,data:d}),new gt("metadata headers exceed",{resourceName:this.name,operation:"update",id:t,totalSize:e,effectiveLimit:r,excess:i,suggestion:"Reduce metadata size or number of fields."})}if(!E)throw ht(D,{bucket:this.client.config.bucket,key:O,resourceName:this.name,operation:"update",id:t});const A=await this.composeFullObjectFromWrite({id:t,metadata:k,body:j,behavior:this.behavior}),N=await this.executeHooks("afterUpdate",A);return this.emit("update",{...A,$before:{...r},$after:{...N}}),N}async delete(t){if(m(t))throw new Error("id cannot be empty");let e,r=null;const[i,s,n]=await wt(()=>this.get(t));i?e=n:(e={id:t},r=s),await this.executeHooks("beforeDelete",e);const a=this.getResourceKey(t),[o,c,l]=await wt(()=>this.client.deleteObject(a));if(this.emit("delete",{...e,$before:{...e},$after:null}),r)throw ht(r,{bucket:this.client.config.bucket,key:a,resourceName:this.name,operation:"delete",id:t});if(!o)throw ht(c,{key:a,resourceName:this.name,operation:"delete",id:t});return await this.executeHooks("afterDelete",e),l}async upsert({id:t,...e}){return await this.exists(t)?this.update(t,e):this.insert({id:t,...e})}async count({partition:t=null,partitionValues:e={}}={}){let r;if(t&&Object.keys(e).length>0){const i=this.config.partitions[t];if(!i)throw new mt(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"count"});const s=[],n=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,r]of n){const i=e[t];if(null!=i){const e=this.applyPartitionRule(i,r);s.push(`${t}=${e}`)}}r=s.length>0?`resource=${this.name}/partition=${t}/${s.join("/")}`:`resource=${this.name}/partition=${t}`}else r=`resource=${this.name}/data`;const i=await this.client.count({prefix:r});return this.emit("count",i),i}async insertMany(t){const{results:e}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,e),this.observers.map(r=>r.emit("error",this.name,t,e))}).process(async t=>await this.insert(t));return this.emit("insertMany",t.length),e}async deleteMany(t){const e=d(t.map(t=>this.getResourceKey(t)),1e3);t.map(t=>this.getResourceKey(t));const{results:r}=await i.for(e).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,e),this.observers.map(r=>r.emit("error",this.name,t,e))}).process(async t=>{const e=await this.client.deleteObjects(t);return t.forEach(t=>{const e=t.split("/").find(t=>t.startsWith("id=")),r=e?e.replace("id=",""):null;r&&(this.emit("deleted",r),this.observers.map(t=>t.emit("deleted",this.name,r)))}),e});return this.emit("deleteMany",t.length),r}async deleteAll(){if(!1!==this.config.paranoid)throw new gt("deleteAll() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAll",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAll."});const t=`resource=${this.name}/data`,e=await this.client.deleteAll({prefix:t});return this.emit("deleteAll",{version:this.version,prefix:t,deletedCount:e}),{deletedCount:e,version:this.version}}async deleteAllData(){if(!1!==this.config.paranoid)throw new gt("deleteAllData() is a dangerous operation and requires paranoid: false option.",{resourceName:this.name,operation:"deleteAllData",paranoid:this.config.paranoid,suggestion:"Set paranoid: false to allow deleteAllData."});const t=`resource=${this.name}`,e=await this.client.deleteAll({prefix:t});return this.emit("deleteAllData",{resource:this.name,prefix:t,deletedCount:e}),{deletedCount:e,resource:this.name}}async listIds({partition:t=null,partitionValues:e={},limit:r,offset:i=0}={}){let s;if(t&&Object.keys(e).length>0){if(!this.config.partitions||!this.config.partitions[t])throw new mt(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"listIds"});const r=this.config.partitions[t],i=[],n=Object.entries(r.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,r]of n){const s=e[t];if(null!=s){const e=this.applyPartitionRule(s,r);i.push(`${t}=${e}`)}}s=i.length>0?`resource=${this.name}/partition=${t}/${i.join("/")}`:`resource=${this.name}/partition=${t}`}else s=`resource=${this.name}/data`;const n=(await this.client.getKeysPage({prefix:s,offset:i,amount:r||1e3})).map(t=>{const e=t.split("/").find(t=>t.startsWith("id="));return e?e.replace("id=",""):null}).filter(Boolean);return this.emit("listIds",n.length),n}async list({partition:t=null,partitionValues:e={},limit:r,offset:i=0}={}){const[s,n,a]=await wt(async()=>t?await this.listPartition({partition:t,partitionValues:e,limit:r,offset:i}):await this.listMain({limit:r,offset:i}));return s?a:this.handleListError(n,{partition:t,partitionValues:e})}async listMain({limit:t,offset:e=0}){const[r,i,s]=await wt(()=>this.listIds({limit:t,offset:e}));if(!r)throw i;const n=await this.processListResults(s,"main");return this.emit("list",{count:n.length,errors:0}),n}async listPartition({partition:t,partitionValues:e,limit:r,offset:i=0}){if(!this.config.partitions?.[t])return this.emit("list",{partition:t,partitionValues:e,count:0,errors:0}),[];const s=this.config.partitions[t],n=this.buildPartitionPrefix(t,s,e),[a,o,c]=await wt(()=>this.client.getAllKeys({prefix:n}));if(!a)throw o;const l=this.extractIdsFromKeys(c).slice(i),u=r?l.slice(0,r):l,h=await this.processPartitionResults(u,t,s,c);return this.emit("list",{partition:t,partitionValues:e,count:h.length,errors:0}),h}buildPartitionPrefix(t,e,r){const i=[],s=Object.entries(e.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of s){const s=r[t];if(null!=s){const r=this.applyPartitionRule(s,e);i.push(`${t}=${r}`)}}return i.length>0?`resource=${this.name}/partition=${t}/${i.join("/")}`:`resource=${this.name}/partition=${t}`}extractIdsFromKeys(t){return t.map(t=>{const e=t.split("/").find(t=>t.startsWith("id="));return e?e.replace("id=",""):null}).filter(Boolean)}async processListResults(t,e="main"){const{results:r,errors:s}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content))}).process(async t=>{const[r,i,s]=await wt(()=>this.get(t));return r?s:this.handleResourceError(i,t,e)});return this.emit("list",{count:r.length,errors:0}),r}async processPartitionResults(t,e,r,s){const n=Object.entries(r.fields).sort(([t],[e])=>t.localeCompare(e)),{results:a,errors:o}=await i.for(t).withConcurrency(this.parallelism).handleError(async(t,e)=>{this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content))}).process(async t=>{const[r,i,a]=await wt(async()=>{const r=this.extractPartitionValuesFromKey(t,s,n);return await this.getFromPartition({id:t,partitionName:e,partitionValues:r})});return r?a:this.handleResourceError(i,t,"partition")});return a.filter(t=>null!==t)}extractPartitionValuesFromKey(t,e,r){const i=e.find(e=>e.includes(`id=${t}`));if(!i)throw new mt(`Partition key not found for ID ${t}`,{resourceName:this.name,id:t,operation:"extractPartitionValuesFromKey"});const s=i.split("/"),n={};for(const[t]of r){const e=s.find(e=>e.startsWith(`${t}=`));if(e){const r=e.replace(`${t}=`,"");n[t]=r}}return n}handleResourceError(t,e,r){if(t.message.includes("Cipher job failed")||t.message.includes("OperationError"))return{id:e,_decryptionFailed:!0,_error:t.message,..."partition"===r&&{_partition:r}};throw t}handleListError(t,{partition:e,partitionValues:r}){return t.message.includes("Partition '")&&t.message.includes("' not found"),this.emit("list",{partition:e,partitionValues:r,count:0,errors:1}),[]}async getMany(t){const{results:e,errors:r}=await i.for(t).withConcurrency(this.client.parallelism).handleError(async(t,e)=>(this.emit("error",t,content),this.observers.map(e=>e.emit("error",this.name,t,content)),{id:e,_error:t.message,_decryptionFailed:t.message.includes("Cipher job failed")||t.message.includes("OperationError")})).process(async t=>{const[e,r,i]=await wt(()=>this.get(t));if(e)return i;if(r.message.includes("Cipher job failed")||r.message.includes("OperationError"))return{id:t,_decryptionFailed:!0,_error:r.message};throw r});return this.emit("getMany",t.length),e}async getAll(){const[t,e,r]=await wt(()=>this.listIds());if(!t)throw e;const i=[];for(const t of r){const[e,r,s]=await wt(()=>this.get(t));e&&i.push(s)}return i}async page({offset:t=0,size:e=100,partition:r=null,partitionValues:i={},skipCount:s=!1}={}){const[n,a,o]=await wt(async()=>{let n=null,a=null;if(!s){const[t,s,o]=await wt(()=>this.count({partition:r,partitionValues:i}));t?(n=o,a=Math.ceil(n/e)):(n=null,a=null)}const o=Math.floor(t/e);let c=[];if(e<=0)c=[];else{const[s,n,a]=await wt(()=>this.list({partition:r,partitionValues:i,limit:e,offset:t}));c=s?a:[]}const l={items:c,totalItems:n,page:o,pageSize:e,totalPages:a,hasMore:c.length===e&&t+e<(n||1/0),_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:c.length,skipCount:s,hasTotalItems:null!==n}};return this.emit("page",l),l});return n?o:{items:[],totalItems:null,page:Math.floor(t/e),pageSize:e,totalPages:null,_debug:{requestedSize:e,requestedOffset:t,actualItemsReturned:0,skipCount:s,hasTotalItems:!1,error:a.message}}}readable(){return new Oi({resource:this}).build()}writable(){return new Ri({resource:this}).build()}async setContent({id:t,buffer:e,contentType:r="application/octet-stream"}){const[i,s,n]=await wt(()=>this.get(t));if(!i||!n)throw new gt(`Resource with id '${t}' not found`,{resourceName:this.name,id:t,operation:"setContent"});const a={...n,_hasContent:!0,_contentLength:e.length,_mimeType:r},o=await this.schema.mapper(a),[c,l]=await wt(()=>this.client.putObject({key:this.getResourceKey(t),metadata:o,body:e,contentType:r}));if(!c)throw l;return this.emit("setContent",{id:t,contentType:r,contentLength:e.length}),a}async content(t){const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.getObject(e));if(!r){if("NoSuchKey"===i.name)return{buffer:null,contentType:null};throw i}const n=Buffer.from(await s.Body.transformToByteArray()),a=s.ContentType||null;return this.emit("content",t,n.length,a),{buffer:n,contentType:a}}async hasContent(t){const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.headObject(e));return!!r&&s.ContentLength>0}async deleteContent(t){const e=this.getResourceKey(t),[r,i,s]=await wt(()=>this.client.headObject(e));if(!r)throw i;const n=s.Metadata||{},[a,o,c]=await wt(()=>this.client.putObject({key:e,body:"",metadata:n}));if(!a)throw o;return this.emit("deleteContent",t),c}getDefinitionHash(){const t={attributes:this.attributes,behavior:this.behavior},e=O(t);return`sha256:${f("sha256").update(e).digest("hex")}`}extractVersionFromKey(t){const e=t.split("/").find(t=>t.startsWith("v="));return e?e.replace("v=",""):null}async getSchemaForVersion(t){if(t===this.version)return this.schema;const[e,r,i]=await wt(()=>Promise.resolve(new Hi({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:t,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})));return e?i:this.schema}async createPartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,i]of Object.entries(e)){const e=this.getPartitionKey({partitionName:r,id:t.id,data:t});if(e){const t={_v:String(this.version)};await this.client.putObject({key:e,metadata:t,body:"",contentType:void 0})}}}async deletePartitionReferences(t){const e=this.config.partitions;if(!e||0===Object.keys(e).length)return;const r=[];for(const[i,s]of Object.entries(e)){const e=this.getPartitionKey({partitionName:i,id:t.id,data:t});e&&r.push(e)}if(r.length>0){const[t,e]=await wt(()=>this.client.deleteObjects(r))}}async query(t={},{limit:e=100,offset:r=0,partition:i=null,partitionValues:s={}}={}){if(0===Object.keys(t).length)return await this.list({partition:i,partitionValues:s,limit:e,offset:r});const n=[];let a=r;const o=Math.min(e,50);for(;n.length<e;){const e=await this.list({partition:i,partitionValues:s,limit:o,offset:a});if(0===e.length)break;const r=e.filter(e=>Object.entries(t).every(([t,r])=>e[t]===r));if(n.push(...r),a+=o,e.length<o)break}return n.slice(0,e)}async handlePartitionReferenceUpdates(t,e){const r=this.config.partitions;if(!r||0===Object.keys(r).length)return;for(const[i,s]of Object.entries(r)){const[r,n]=await wt(()=>this.handlePartitionReferenceUpdate(i,s,t,e))}const i=e.id||t.id;for(const[t,s]of Object.entries(r)){const r=`resource=${this.name}/partition=${t}`;let s=[];const[n,a,o]=await wt(()=>this.client.getAllKeys({prefix:r}));if(!n)continue;s=o;const c=this.getPartitionKey({partitionName:t,id:i,data:e});for(const t of s)if(t.endsWith(`/id=${i}`)&&t!==c){const[e,r]=await wt(()=>this.client.deleteObject(t))}}}async handlePartitionReferenceUpdate(t,e,r,i){const s=i.id||r.id,n=this.getPartitionKey({partitionName:t,id:s,data:r}),a=this.getPartitionKey({partitionName:t,id:s,data:i});if(n!==a){if(n){const[t,e]=await wt(async()=>{await this.client.deleteObject(n)})}if(a){const[t,e]=await wt(async()=>{const t={_v:String(this.version)};await this.client.putObject({key:a,metadata:t,body:"",contentType:void 0})})}}else if(a){const[t,e]=await wt(async()=>{const t={_v:String(this.version)};await this.client.putObject({key:a,metadata:t,body:"",contentType:void 0})})}}async updatePartitionReferences(t){const e=this.config.partitions;if(e&&0!==Object.keys(e).length)for(const[r,i]of Object.entries(e)){if(!i||!i.fields||"object"!=typeof i.fields)continue;const e=this.getPartitionKey({partitionName:r,id:t.id,data:t});if(e){const t={_v:String(this.version)},[r,i]=await wt(async()=>{await this.client.putObject({key:e,metadata:t,body:"",contentType:void 0})})}}}async getFromPartition({id:t,partitionName:e,partitionValues:r={}}){if(!this.config.partitions||!this.config.partitions[e])throw new mt(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"getFromPartition"});const i=this.config.partitions[e],s=[],n=Object.entries(i.fields).sort(([t],[e])=>t.localeCompare(e));for(const[t,e]of n){const i=r[t];if(null!=i){const r=this.applyPartitionRule(i,e);s.push(`${t}=${r}`)}}if(0===s.length)throw new mt(`No partition values provided for partition '${e}'`,{resourceName:this.name,partitionName:e,operation:"getFromPartition"});const a=Kt(`resource=${this.name}`,`partition=${e}`,...s,`id=${t}`),[o,c]=await wt(async()=>{await this.client.headObject(a)});if(!o)throw new gt(`Resource with id '${t}' not found in partition '${e}'`,{resourceName:this.name,id:t,partitionName:e,operation:"getFromPartition"});const l=await this.get(t);return l._partition=e,l._partitionValues=r,this.emit("getFromPartition",l),l}async createHistoricalVersion(t,e){const r=Kt(`resource=${this.name}`,"historical",`id=${t}`),i={...e,_v:e._v||this.version,_historicalTimestamp:(new Date).toISOString()},s=await this.schema.mapper(i),n=hs(this.behavior),{mappedData:a,body:o}=await n.handleInsert({resource:this,data:i,mappedData:s}),c={...a,_v:e._v||this.version,_historicalTimestamp:i._historicalTimestamp};let l;if(o&&""!==o){const[t,e]=await wt(()=>Promise.resolve(JSON.parse(o)));t&&(l="application/json")}await this.client.putObject({key:r,metadata:c,body:o,contentType:l})}async applyVersionMapping(t,e,r){if(e===r)return t;return{...t,_v:r,_originalVersion:e,_versionMapped:!0}}async composeFullObjectFromWrite({id:t,metadata:e,body:r,behavior:i}){const s={};e&&"true"===e.$truncated&&(s.$truncated="true"),e&&"true"===e.$overflow&&(s.$overflow="true");let n={};const[a,o,c]=await wt(()=>this.schema.unmapper(e));n=a?c:e;const l=t=>{if(!t||"object"!=typeof t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||(e[r]=i);return e},u=t=>{if("object"==typeof t&&null!==t)return t;if("string"==typeof t){if("[object Object]"===t)return{};if(t.startsWith("{")||t.startsWith("[")){const[e,r,i]=bt(()=>JSON.parse(t));return e?i:t}return t}return t};if("body-overflow"===i){const i=e&&"true"===e.$overflow;let s={};if(i&&r){const[t,e,i]=await wt(()=>Promise.resolve(JSON.parse(r)));if(t){const[t,e,r]=await wt(()=>this.schema.unmapper(i));s=t?r:{}}}const a={...n,...s,id:t};Object.keys(a).forEach(t=>{a[t]=u(a[t])});const o=l(a);return i&&(o.$overflow="true"),o}if("body-only"===i){const[i,s,n]=await wt(()=>Promise.resolve(r?JSON.parse(r):{}));let a=this.schema.map;if(e&&e._map){const[t,r,i]=await wt(()=>Promise.resolve("string"==typeof e._map?JSON.parse(e._map):e._map));a=t?i:this.schema.map}const[o,c,l]=await wt(()=>this.schema.unmapper(n,a)),h=o?{...l,id:t}:{id:t};return Object.keys(h).forEach(t=>{h[t]=u(h[t])}),h}const h={...n,id:t};Object.keys(h).forEach(t=>{h[t]=u(h[t])});const f=l(h);return s.$truncated&&(f.$truncated=s.$truncated),s.$overflow&&(f.$overflow=s.$overflow),f}emit(t,...e){return super.emit(t,...e)}async replace(t,e){await this.delete(t),await new Promise(t=>setTimeout(t,100));const r=Date.now();for(;Date.now()-r<5e3;){if(!await this.exists(t))break;await new Promise(t=>setTimeout(t,50))}try{return await this.insert({...e,id:t})}catch(r){if(r&&r.message&&r.message.includes("already exists")){return await this.update(t,e)}throw r}}_initMiddleware(){this._middlewares=new Map,this._middlewareMethods=["get","list","listIds","getAll","count","page","insert","update","delete","deleteMany","exists","getMany"];for(const t of this._middlewareMethods)this._middlewares.set(t,[]),this[`_original_${t}`]||(this[`_original_${t}`]=this[t].bind(this),this[t]=async(...e)=>{const r={resource:this,args:e,method:t};let i=-1;const s=this._middlewares.get(t),n=async e=>{if(e<=i)throw new Error("next() called multiple times");return i=e,e<s.length?await s[e](r,()=>n(e+1)):await this[`_original_${t}`](...r.args)};return await n(0)})}useMiddleware(t,e){if(this._middlewares||this._initMiddleware(),!this._middlewares.has(t))throw new gt(`No such method for middleware: ${t}`,{operation:"useMiddleware",method:t});this._middlewares.get(t).push(e)}applyDefaults(t){const e={...t};for(const[t,r]of Object.entries(this.attributes))if(void 0===e[t]&&"string"==typeof r&&r.includes("default:")){const i=r.match(/default:([^|]+)/);if(i){let s=i[1];r.includes("boolean")?s="true"===s:r.includes("number")&&(s=Number(s)),e[t]=s}}return e}}var gs=ps;class ms extends At{constructor(t){super(),this.version="1",this.s3dbVersion=(()=>{const[t,e,r]=wt(()=>"7.3.10");return t?r:"latest"})(),this.resources={},this.savedMetadata=null,this.options=t,this.verbose=t.verbose||!1,this.parallelism=parseInt(t.parallelism+"")||10,this.plugins=t.plugins||[],this.pluginList=t.plugins||[],this.cache=t.cache,this.passphrase=t.passphrase||"secret",this.versioningEnabled=t.versioningEnabled||!1;let e=t.connectionString;if(!e&&(t.bucket||t.accessKeyId||t.secretAccessKey)){const{bucket:r,region:i,accessKeyId:s,secretAccessKey:n,endpoint:a,forcePathStyle:o}=t;if(a){const t=new URL(a);s&&(t.username=encodeURIComponent(s)),n&&(t.password=encodeURIComponent(n)),t.pathname=`/${r||"s3db"}`,o&&t.searchParams.set("forcePathStyle","true"),e=t.toString()}else if(s&&n){const t=new URLSearchParams;t.set("region",i||"us-east-1"),o&&t.set("forcePathStyle","true"),e=`s3://${encodeURIComponent(s)}:${encodeURIComponent(n)}@${r||"s3db"}?${t.toString()}`}}this.client=t.client||new qi({verbose:this.verbose,parallelism:this.parallelism,connectionString:e}),this.bucket=this.client.bucket,this.keyPrefix=this.client.keyPrefix,this._exitListenerRegistered||(this._exitListenerRegistered=!0,"undefined"!=typeof process&&process.on("exit",async()=>{if(this.isConnected())try{await this.disconnect()}catch(t){}}))}async connect(){await this.startPlugins();let t=null;if(await this.client.exists("s3db.json")){const e=await this.client.getObject("s3db.json");t=JSON.parse(await ji(e?.Body))}else t=this.blankMetadataStructure(),await this.uploadMetadataFile();this.savedMetadata=t;const e=this.detectDefinitionChanges(t);for(const[e,r]of Object.entries(t.resources||{})){const t=r.currentVersion||"v0",i=r.versions?.[t];i&&(this.resources[e]=new gs({name:e,client:this.client,database:this,version:t,attributes:i.attributes,behavior:i.behavior||"user-managed",parallelism:this.parallelism,passphrase:this.passphrase,observers:[this],cache:this.cache,timestamps:void 0!==i.timestamps&&i.timestamps,partitions:r.partitions||i.partitions||{},paranoid:void 0===i.paranoid||i.paranoid,allNestedObjectsOptional:void 0===i.allNestedObjectsOptional||i.allNestedObjectsOptional,autoDecrypt:void 0===i.autoDecrypt||i.autoDecrypt,hooks:i.hooks||{},versioningEnabled:this.versioningEnabled,map:i.map}))}e.length>0&&this.emit("resourceDefinitionsChanged",{changes:e,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(t){const e=[];for(const[r,i]of Object.entries(this.resources)){const s=this.generateDefinitionHash(i.export()),n=t.resources?.[r];if(n){const t=n.currentVersion||"v0",i=n.versions?.[t],a=i?.hash;a!==s&&e.push({type:"changed",resourceName:r,currentHash:s,savedHash:a,fromVersion:t,toVersion:this.getNextVersion(n.versions)})}else e.push({type:"new",resourceName:r,currentHash:s,savedHash:null})}for(const[r,i]of Object.entries(t.resources||{}))if(!this.resources[r]){const t=i.currentVersion||"v0",s=i.versions?.[t];e.push({type:"deleted",resourceName:r,currentHash:null,savedHash:s?.hash,deletedVersion:t})}return e}generateDefinitionHash(t,e=void 0){const r={...t.attributes};t.timestamps&&(delete r.createdAt,delete r.updatedAt);const i={attributes:r,behavior:e||t.behavior||"user-managed",partitions:t.partitions||{}},s=O(i);return`sha256:${f("sha256").update(s).digest("hex")}`}getNextVersion(t={}){const e=Object.keys(t).filter(t=>t.startsWith("v")).map(t=>parseInt(t.substring(1))).filter(t=>!isNaN(t));return`v${(e.length>0?Math.max(...e):-1)+1}`}async startPlugins(){const t=this;if(!m(this.pluginList)){const e=this.pluginList.map(t=>k(t)?new t(this):t),r=e.map(async e=>{e.beforeSetup&&await e.beforeSetup(),await e.setup(t),e.afterSetup&&await e.afterSetup()});await Promise.all(r);const i=e.map(async t=>{t.beforeStart&&await t.beforeStart(),await t.start(),t.afterStart&&await t.afterStart()});await Promise.all(i)}}async usePlugin(t,e=null){const r=e||t.constructor.name.replace("Plugin","").toLowerCase();return this.plugins[r]=t,this.isConnected()&&(await t.setup(this),await t.start()),t}async uploadMetadataFile(){const t={version:this.version,s3dbVersion:this.s3dbVersion,lastUpdated:(new Date).toISOString(),resources:{}};Object.entries(this.resources).forEach(([e,r])=>{const i=r.export(),s=this.generateDefinitionHash(i),n=this.savedMetadata?.resources?.[e],a=n?.currentVersion||"v0",o=n?.versions?.[a];let c,l;o&&o.hash===s?(c=a,l=!1):(c=this.getNextVersion(n?.versions),l=!0),t.resources[e]={currentVersion:c,partitions:r.config.partitions||{},versions:{...n?.versions,[c]:{hash:s,attributes:i.attributes,behavior:i.behavior||"user-managed",timestamps:r.config.timestamps,partitions:r.config.partitions,paranoid:r.config.paranoid,allNestedObjectsOptional:r.config.allNestedObjectsOptional,autoDecrypt:r.config.autoDecrypt,cache:r.config.cache,hooks:r.config.hooks,createdAt:l?(new Date).toISOString():o?.createdAt}}},r.version!==c&&(r.version=c,r.emit("versionUpdated",{oldVersion:a,newVersion:c}))}),await this.client.putObject({key:"s3db.json",body:JSON.stringify(t,null,2),contentType:"application/json"}),this.savedMetadata=t,this.emit("metadataUploaded",t)}blankMetadataStructure(){return{version:"1",s3dbVersion:this.s3dbVersion,resources:{}}}resourceExists(t){return!!this.resources[t]}resourceExistsWithSameHash({name:t,attributes:e,behavior:r="user-managed",partitions:i={},options:s={}}){if(!this.resources[t])return{exists:!1,sameHash:!1,hash:null};const n=this.resources[t],a=this.generateDefinitionHash(n.export()),o=new gs({name:t,attributes:e,behavior:r,partitions:i,client:this.client,version:n.version,passphrase:this.passphrase,versioningEnabled:this.versioningEnabled,...s}),c=this.generateDefinitionHash(o.export());return{exists:!0,sameHash:a===c,hash:c,existingHash:a}}async createResource({name:t,attributes:e,behavior:r="user-managed",hooks:i,...s}){if(this.resources[t]){const n=this.resources[t];if(Object.assign(n.config,{cache:this.cache,...s}),r&&(n.behavior=r),n.versioningEnabled=this.versioningEnabled,n.updateAttributes(e),i)for(const[t,e]of Object.entries(i))if(Array.isArray(e)&&n.hooks[t])for(const r of e)"function"==typeof r&&n.hooks[t].push(r.bind(n));const a=this.generateDefinitionHash(n.export(),n.behavior),o=this.savedMetadata?.resources?.[t],c=o?.currentVersion||"v0",l=o?.versions?.[c];return l&&l.hash===a||await this.uploadMetadataFile(),this.emit("s3db.resourceUpdated",t),n}const n=this.savedMetadata?.resources?.[t],a=n?.currentVersion||"v0",o=new gs({name:t,client:this.client,version:void 0!==s.version?s.version:a,attributes:e,behavior:r,parallelism:this.parallelism,passphrase:void 0!==s.passphrase?s.passphrase:this.passphrase,observers:[this],cache:void 0!==s.cache?s.cache:this.cache,timestamps:void 0!==s.timestamps&&s.timestamps,partitions:s.partitions||{},paranoid:void 0===s.paranoid||s.paranoid,allNestedObjectsOptional:void 0===s.allNestedObjectsOptional||s.allNestedObjectsOptional,autoDecrypt:void 0===s.autoDecrypt||s.autoDecrypt,hooks:i||{},versioningEnabled:this.versioningEnabled,map:s.map,idGenerator:s.idGenerator,idSize:s.idSize});return o.database=this,this.resources[t]=o,await this.uploadMetadataFile(),this.emit("s3db.resourceCreated",t),o}resource(t){return this.resources[t]?this.resources[t]:Promise.reject(`resource ${t} does not exist`)}async listResources(){return Object.keys(this.resources).map(t=>({name:t}))}async getResource(t){if(!this.resources[t])throw new it({bucket:this.client.config.bucket,resourceName:t,id:t});return this.resources[t]}get config(){return{version:this.version,s3dbVersion:this.s3dbVersion,bucket:this.bucket,keyPrefix:this.keyPrefix,parallelism:this.parallelism,verbose:this.verbose}}isConnected(){return!!this.savedMetadata}async disconnect(){try{if(this.pluginList&&this.pluginList.length>0){for(const t of this.pluginList)t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners();const t=this.pluginList.map(async t=>{try{t&&"function"==typeof t.stop&&await t.stop()}catch(t){}});await Promise.all(t)}if(this.resources&&Object.keys(this.resources).length>0){for(const[t,e]of Object.entries(this.resources))try{e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners(),e._pluginWrappers&&e._pluginWrappers.clear(),e._pluginMiddlewares&&(e._pluginMiddlewares={}),e.observers&&Array.isArray(e.observers)&&(e.observers=[])}catch(t){}Object.keys(this.resources).forEach(t=>delete this.resources[t])}this.client&&"function"==typeof this.client.removeAllListeners&&this.client.removeAllListeners(),this.removeAllListeners(),this.savedMetadata=null,this.plugins={},this.pluginList=[],this.emit("disconnected",new Date)}catch(t){}}}class ys extends ms{}function bs(t){return"string"==typeof t?t.trim().toLowerCase():t}var ws=class extends Ti{constructor(t={},e=[],r=null){super(t),this.instanceId=Math.random().toString(36).slice(2,10),this.client=r,this.connectionString=t.connectionString;let i=e;if(e)if(Array.isArray(e)){i={};for(const t of e)"string"==typeof t&&(i[bs(t)]=t)}else"string"==typeof e&&(i[bs(e)]=e);else i={};this.resourcesMap=this._normalizeResources(i)}_normalizeResources(t){if(!t)return{};if(Array.isArray(t)){const e={};for(const r of t)"string"==typeof r?e[bs(r)]=r:"object"==typeof r&&r.resource&&(e[bs(r.resource)]=r);return e}if("object"==typeof t){const e={};for(const[r,i]of Object.entries(t)){const t=bs(r);"string"==typeof i?e[t]=i:Array.isArray(i)?e[t]=i.map(t=>("string"==typeof t||"object"==typeof t&&t.resource,t)):("function"==typeof i||"object"==typeof i&&i.resource)&&(e[t]=i)}return e}return"function"==typeof t?t:{}}validateConfig(){const t=[];return this.client||this.connectionString||t.push("You must provide a client or a connectionString"),(!this.resourcesMap||"object"==typeof this.resourcesMap&&0===Object.keys(this.resourcesMap).length)&&t.push("You must provide a resources map or array"),{isValid:0===t.length,errors:t}}async initialize(t){await super.initialize(t);const[e,r]=await wt(async()=>{if(this.client)this.targetDatabase=this.client;else{if(!this.connectionString)throw new Error("S3dbReplicator: No client or connectionString provided");{const t={connectionString:this.connectionString,region:this.region,keyPrefix:this.keyPrefix,verbose:this.config.verbose||!1};this.targetDatabase=new ys(t),await this.targetDatabase.connect()}}this.emit("connected",{replicator:this.name,target:this.connectionString||"client-provided"})});if(!e)throw this.config.verbose&&console.warn(`[S3dbReplicator] Initialization failed: ${r.message}`),r}async replicate(t,e,r,i,s){let n,a,o,c;"object"==typeof t&&t.resource?(n=t.resource,a=t.operation,o=t.data,c=t.id):(n=t,a=e,o=r,c=i);const l=bs(n),u=this.resourcesMap[l];if(!u)throw new Error(`[S3dbReplicator] Resource not configured: ${n}`);if(Array.isArray(u)){const t=[];for(const e of u){const[r,i,s]=await wt(async()=>await this._replicateToSingleDestination(e,l,a,o,c));if(!r)throw this.config&&this.config.verbose&&console.warn(`[S3dbReplicator] Failed to replicate to destination ${JSON.stringify(e)}: ${i.message}`),i;t.push(s)}return t}{const[t,e,r]=await wt(async()=>await this._replicateToSingleDestination(u,l,a,o,c));if(!t)throw this.config&&this.config.verbose&&console.warn(`[S3dbReplicator] Failed to replicate to destination ${JSON.stringify(u)}: ${e.message}`),e;return r}}async _replicateToSingleDestination(t,e,r,i,s){let n;if(n="string"==typeof t?t:"object"==typeof t&&t.resource?t.resource:e,"object"==typeof t&&t.actions&&Array.isArray(t.actions)&&!t.actions.includes(r))return{skipped:!0,reason:"action_not_supported",action:r,destination:n};const a=this._getDestResourceObj(n);let o,c;if("object"==typeof t&&t.transform&&"function"==typeof t.transform?(o=t.transform(i),o&&i&&i.id&&!o.id&&(o.id=i.id)):"object"==typeof t&&t.transformer&&"function"==typeof t.transformer?(o=t.transformer(i),o&&i&&i.id&&!o.id&&(o.id=i.id)):o=i,!o&&i&&(o=i),"insert"===r)c=await a.insert(o);else if("update"===r)c=await a.update(s,o);else{if("delete"!==r)throw new Error(`Invalid operation: ${r}. Supported operations are: insert, update, delete`);c=await a.delete(s)}return c}_applyTransformer(t,e){let r=this._cleanInternalFields(e);const i=bs(t),s=this.resourcesMap[i];let n;if(!s)return r;if(Array.isArray(s)){for(const t of s){if("object"==typeof t&&t.transform&&"function"==typeof t.transform){n=t.transform(r);break}if("object"==typeof t&&t.transformer&&"function"==typeof t.transformer){n=t.transformer(r);break}}n||(n=r)}else"object"==typeof s?"function"==typeof s.transform?n=s.transform(r):"function"==typeof s.transformer&&(n=s.transformer(r)):n="function"==typeof s?s(r):r;return n&&r&&r.id&&!n.id&&(n.id=r.id),!n&&r&&(n=r),n}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}_resolveDestResource(t,e){const r=bs(t),i=this.resourcesMap[r];if(!i)return t;if(Array.isArray(i)){for(const t of i){if("string"==typeof t)return t;if("object"==typeof t&&t.resource)return t.resource}return t}return"string"==typeof i?i:"function"==typeof i?t:"object"==typeof i&&i.resource?i.resource:t}_getDestResourceObj(t){const e=Object.keys(this.client.resources||{}),r=bs(t),i=e.find(t=>bs(t)===r);if(!i)throw new Error(`[S3dbReplicator] Destination resource not found: ${t}. Available: ${e.join(", ")}`);return this.client.resources[i]}async replicateBatch(t,e){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};const r=[],i=[];for(const s of e){const[e,n,a]=await wt(()=>this.replicate({resource:t,operation:s.operation,id:s.id,data:s.data,beforeData:s.beforeData}));e?r.push(a):(this.config.verbose&&console.warn(`[S3dbReplicator] Batch replication failed for record ${s.id}: ${n.message}`),i.push({id:s.id,error:n.message}))}return i.length>0&&console.warn(`[S3dbReplicator] Batch replication completed with ${i.length} error(s) for ${t}:`,i),this.emit("batch_replicated",{replicator:this.name,resourceName:t,total:e.length,successful:r.length,errors:i.length}),{success:0===i.length,results:r,errors:i,total:e.length}}async testConnection(){const[t,e]=await wt(async()=>{if(!this.targetDatabase)throw new Error("No target database configured");return"function"==typeof this.targetDatabase.connect&&await this.targetDatabase.connect(),!0});return!!t||(this.config.verbose&&console.warn(`[S3dbReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.targetDatabase,targetDatabase:this.connectionString||"client-provided",resources:Object.keys(this.resourcesMap||{}),totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.targetDatabase&&this.targetDatabase.removeAllListeners(),await super.cleanup()}shouldReplicateResource(t,e){const r=bs(t),i=this.resourcesMap[r];if(!i)return!1;if(!e)return!0;if(Array.isArray(i)){for(const t of i)if("object"==typeof t&&t.resource){if(!t.actions||!Array.isArray(t.actions))return!0;if(t.actions.includes(e))return!0}else if("string"==typeof t)return!0;return!1}return"object"==typeof i&&i.resource?!i.actions||!Array.isArray(i.actions)||i.actions.includes(e):"string"==typeof i||"function"==typeof i}};const vs={s3db:ws,sqs:class extends Ti{constructor(t={},e=[],r=null){if(super(t),this.client=r,this.queueUrl=t.queueUrl,this.queues=t.queues||{},this.defaultQueue=t.defaultQueue||t.defaultQueueUrl||t.queueUrlDefault,this.region=t.region||"us-east-1",this.sqsClient=r||null,this.messageGroupId=t.messageGroupId,this.deduplicationId=t.deduplicationId,Array.isArray(e)){this.resources={};for(const t of e)"string"==typeof t?this.resources[t]=!0:"object"==typeof t&&t.name&&(this.resources[t.name]=t)}else if("object"==typeof e){this.resources=e;for(const[t,r]of Object.entries(e))r&&r.queueUrl&&(this.queues[t]=r.queueUrl)}else this.resources={}}validateConfig(){const t=[];return this.queueUrl||0!==Object.keys(this.queues).length||this.defaultQueue||this.resourceQueueMap||t.push("Either queueUrl, queues object, defaultQueue, or resourceQueueMap must be provided"),{isValid:0===t.length,errors:t}}getQueueUrlsForResource(t){if(this.resourceQueueMap&&this.resourceQueueMap[t])return this.resourceQueueMap[t];if(this.queues[t])return[this.queues[t]];if(this.queueUrl)return[this.queueUrl];if(this.defaultQueue)return[this.defaultQueue];throw new Error(`No queue URL found for resource '${t}'`)}_applyTransformer(t,e){let r=this._cleanInternalFields(e);const i=this.resources[t];let s=r;return i?("function"==typeof i.transform?s=i.transform(r):"function"==typeof i.transformer&&(s=i.transformer(r)),s||r):r}_cleanInternalFields(t){if(!t||"object"!=typeof t)return t;const e={...t};return Object.keys(e).forEach(t=>{(t.startsWith("$")||t.startsWith("_"))&&delete e[t]}),e}createMessage(t,e,r,i,s=null){const n={resource:t,action:e,timestamp:(new Date).toISOString(),source:"s3db-replicator"};switch(e){case"insert":case"delete":default:return{...n,data:r};case"update":return{...n,before:s,data:r}}}async initialize(t,e){if(await super.initialize(t),!this.sqsClient){const[t,r,i]=await wt(()=>import("@aws-sdk/client-sqs"));if(!t)throw this.config.verbose&&console.warn(`[SqsReplicator] Failed to import SQS SDK: ${r.message}`),this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{SQSClient:s}=i;this.sqsClient=e||new s({region:this.region,credentials:this.config.credentials}),this.emit("initialized",{replicator:this.name,queueUrl:this.queueUrl,queues:this.queues,defaultQueue:this.defaultQueue})}}async replicate(t,e,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};const[n,a,o]=await wt(async()=>{const{SendMessageCommand:n}=await import("@aws-sdk/client-sqs"),a=this.getQueueUrlsForResource(t),o=this._applyTransformer(t,r),c=this.createMessage(t,e,o,i,s),l=[];for(const r of a){const s=new n({QueueUrl:r,MessageBody:JSON.stringify(c),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${t}:${e}:${i}`:void 0}),a=await this.sqsClient.send(s);l.push({queueUrl:r,messageId:a.MessageId}),this.emit("replicated",{replicator:this.name,resource:t,operation:e,id:i,queueUrl:r,messageId:a.MessageId,success:!0})}return{success:!0,results:l}});return n?o:(this.config.verbose&&console.warn(`[SqsReplicator] Replication failed for ${t}: ${a.message}`),this.emit("replicator_error",{replicator:this.name,resource:t,operation:e,id:i,error:a.message}),{success:!1,error:a.message})}async replicateBatch(t,e){if(!this.enabled||!this.shouldReplicateResource(t))return{skipped:!0,reason:"resource_not_included"};const[r,i,s]=await wt(async()=>{const{SendMessageBatchCommand:r}=await import("@aws-sdk/client-sqs"),i=this.getQueueUrlsForResource(t),s=[];for(let t=0;t<e.length;t+=10)s.push(e.slice(t,t+10));const n=[],a=[];for(const e of s){const[s,o]=await wt(async()=>{const s=e.map((e,r)=>({Id:`${e.id}-${r}`,MessageBody:JSON.stringify(this.createMessage(t,e.operation,e.data,e.id,e.beforeData)),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${t}:${e.operation}:${e.id}`:void 0})),a=new r({QueueUrl:i[0],Entries:s}),o=await this.sqsClient.send(a);n.push(o)});if(!s&&(a.push({batch:e.length,error:o.message}),o.message&&(o.message.includes("Batch error")||o.message.includes("Connection")||o.message.includes("Network"))))throw o}return a.length>0&&console.warn(`[SqsReplicator] Batch replication completed with ${a.length} error(s) for ${t}:`,a),this.emit("batch_replicated",{replicator:this.name,resource:t,queueUrl:i[0],total:e.length,successful:n.length,errors:a.length}),{success:0===a.length,results:n,errors:a,total:e.length,queueUrl:i[0]}});if(r)return s;const n=i?.message||i||"Unknown error";return this.config.verbose&&console.warn(`[SqsReplicator] Batch replication failed for ${t}: ${n}`),this.emit("batch_replicator_error",{replicator:this.name,resource:t,error:n}),{success:!1,error:n}}async testConnection(){const[t,e]=await wt(async()=>{this.sqsClient||await this.initialize(this.database);const{GetQueueAttributesCommand:t}=await import("@aws-sdk/client-sqs"),e=new t({QueueUrl:this.queueUrl,AttributeNames:["QueueArn"]});return await this.sqsClient.send(e),!0});return!!t||(this.config.verbose&&console.warn(`[SqsReplicator] Connection test failed: ${e.message}`),this.emit("connection_error",{replicator:this.name,error:e.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.sqsClient,queueUrl:this.queueUrl,region:this.region,resources:Object.keys(this.resources||{}),totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.sqsClient&&this.sqsClient.destroy(),await super.cleanup()}shouldReplicateResource(t){return this.resourceQueueMap&&Object.keys(this.resourceQueueMap).includes(t)||this.queues&&Object.keys(this.queues).includes(t)||!(!this.defaultQueue&&!this.queueUrl)||this.resources&&Object.keys(this.resources).includes(t)||!1}},bigquery:Mi,postgres:Li};function Ss(t){return"string"==typeof t?t.trim().toLowerCase():t}class _s extends Tt{constructor(t={}){if(super(),!t.replicators||!Array.isArray(t.replicators))throw new Error("ReplicatorPlugin: replicators array is required");for(const e of t.replicators){if(!e.driver)throw new Error("ReplicatorPlugin: each replicator must have a driver");if(!e.resources||"object"!=typeof e.resources)throw new Error("ReplicatorPlugin: each replicator must have resources config");if(0===Object.keys(e.resources).length)throw new Error("ReplicatorPlugin: each replicator must have at least one resource configured")}this.config={replicators:t.replicators||[],logErrors:!1!==t.logErrors,replicatorLogResource:t.replicatorLogResource||"replicator_log",enabled:!1!==t.enabled,batchSize:t.batchSize||100,maxRetries:t.maxRetries||3,timeout:t.timeout||3e4,verbose:t.verbose||!1,...t},this.replicators=[],this.database=null,this.eventListenersInstalled=new Set}async decompressData(t){return t}filterInternalFields(t){if(!t||"object"!=typeof t)return t;const e={};for(const[r,i]of Object.entries(t))r.startsWith("_")||"$overflow"===r||"$before"===r||"$after"===r||(e[r]=i);return e}installEventListeners(t,e,r){t&&!this.eventListenersInstalled.has(t.name)&&t.name!==this.config.replicatorLogResource&&(t.on("insert",async e=>{const[i,s]=await wt(async()=>{const i={...e,createdAt:(new Date).toISOString()};await r.processReplicatorEvent("insert",t.name,i.id,i)});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Insert event failed for resource ${t.name}: ${s.message}`),this.emit("error",{operation:"insert",error:s.message,resource:t.name}))}),t.on("update",async(e,i)=>{const[s,n]=await wt(async()=>{const s={...e,updatedAt:(new Date).toISOString()};await r.processReplicatorEvent("update",t.name,s.id,s,i)});s||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Update event failed for resource ${t.name}: ${n.message}`),this.emit("error",{operation:"update",error:n.message,resource:t.name}))}),t.on("delete",async e=>{const[i,s]=await wt(async()=>{await r.processReplicatorEvent("delete",t.name,e.id,e)});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Delete event failed for resource ${t.name}: ${s.message}`),this.emit("error",{operation:"delete",error:s.message,resource:t.name}))}),this.eventListenersInstalled.add(t.name))}async getCompleteData(t,e){const[r,i,s]=await wt(()=>t.get(e.id));return r?s:e}async setup(t){this.database=t;const[e,r]=await wt(async()=>{await this.initializeReplicators(t)});if(!e)throw this.config.verbose&&console.warn(`[ReplicatorPlugin] Replicator initialization failed: ${r.message}`),this.emit("error",{operation:"setup",error:r.message}),r;const[i,s]=await wt(async()=>{if(this.config.replicatorLogResource){await t.createResource({name:this.config.replicatorLogResource,behavior:"body-overflow",attributes:{operation:"string",resourceName:"string",recordId:"string",data:"string",error:"string|optional",replicator:"string",timestamp:"string",status:"string"}})}});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to create log resource ${this.config.replicatorLogResource}: ${s.message}`),this.emit("replicator_log_resource_creation_error",{resourceName:this.config.replicatorLogResource,error:s.message})),await this.uploadMetadataFile(t);const n=t.createResource.bind(t);t.createResource=async e=>{const r=await n(e);return r&&this.installEventListeners(r,t,this),r};for(const e in t.resources){const r=t.resources[e];this.installEventListeners(r,t,this)}}createReplicator(t,e,r,i){return function(t,e={},r=[],i=null){const s=vs[t];if(!s)throw new Error(`Unknown replicator driver: ${t}. Available drivers: ${Object.keys(vs).join(", ")}`);return new s(e,r,i)}(t,e,r,i)}async initializeReplicators(t){for(const e of this.config.replicators){const{driver:r,config:i={},resources:s,client:n,...a}=e,o=s||i.resources||{},c={...i,...a},l=this.createReplicator(r,c,o,n);l&&(await l.initialize(t),this.replicators.push(l))}}async start(){}async stop(){}async uploadMetadataFile(t){"function"==typeof t.uploadMetadataFile&&await t.uploadMetadataFile()}async retryWithBackoff(t,e=3){let r;for(let i=1;i<=e;i++){const[s,n]=await wt(t);if(s)return s;{if(r=n,this.config.verbose&&console.warn(`[ReplicatorPlugin] Retry attempt ${i}/${e} failed: ${n.message}`),i===e)throw n;const t=1e3*Math.pow(2,i-1);this.config.verbose&&console.warn(`[ReplicatorPlugin] Waiting ${t}ms before retry...`),await new Promise(e=>setTimeout(e,t))}}throw r}async logError(t,e,r,i,s,n){const[a,o]=await wt(async()=>{const a=this.config.replicatorLogResource;if(this.database&&this.database.resources&&this.database.resources[a]){const o=this.database.resources[a];await o.insert({replicator:t.name||t.id,resourceName:e,operation:r,recordId:i,data:JSON.stringify(s),error:n.message,timestamp:(new Date).toISOString(),status:"error"})}});a||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to log error for ${e}: ${o.message}`),this.emit("replicator_log_error",{replicator:t.name||t.id,resourceName:e,operation:r,recordId:i,originalError:n.message,logError:o.message}))}async processReplicatorEvent(t,e,r,i,s=null){if(!this.config.enabled)return;const n=this.replicators.filter(r=>r.shouldReplicateResource&&r.shouldReplicateResource(e,t));if(0===n.length)return;const a=n.map(async n=>{const[a,o,c]=await wt(async()=>{const a=await this.retryWithBackoff(()=>n.replicate(e,t,i,r,s),this.config.maxRetries);return this.emit("replicated",{replicator:n.name||n.id,resourceName:e,operation:t,recordId:r,result:a,success:!0}),a});if(a)return c;throw this.config.verbose&&console.warn(`[ReplicatorPlugin] Replication failed for ${n.name||n.id} on ${e}: ${o.message}`),this.emit("replicator_error",{replicator:n.name||n.id,resourceName:e,operation:t,recordId:r,error:o.message}),this.config.logErrors&&this.database&&await this.logError(n,e,t,r,i,o),o});return Promise.allSettled(a)}async processreplicatorItem(t){const e=this.replicators.filter(e=>e.shouldReplicateResource&&e.shouldReplicateResource(t.resourceName,t.operation));if(0===e.length)return;const r=e.map(async e=>{const[r,i]=await wt(async()=>{const[r,i,s]=await wt(()=>e.replicate(t.resourceName,t.operation,t.data,t.recordId,t.beforeData));return r?(this.emit("replicated",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,result:s,success:!0}),{success:!0,result:s}):(this.config.verbose&&console.warn(`[ReplicatorPlugin] Replicator item processing failed for ${e.name||e.id} on ${t.resourceName}: ${i.message}`),this.emit("replicator_error",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,error:i.message}),this.config.logErrors&&this.database&&await this.logError(e,t.resourceName,t.operation,t.recordId,t.data,i),{success:!1,error:i.message})});return r||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Wrapper processing failed for ${e.name||e.id} on ${t.resourceName}: ${i.message}`),this.emit("replicator_error",{replicator:e.name||e.id,resourceName:t.resourceName,operation:t.operation,recordId:t.recordId,error:i.message}),this.config.logErrors&&this.database&&await this.logError(e,t.resourceName,t.operation,t.recordId,t.data,i),{success:!1,error:i.message})});return Promise.allSettled(r)}async logreplicator(t){const e=this.replicatorLog||this.database.resources[Ss(this.config.replicatorLogResource)];if(!e)return this.database&&this.database.options&&this.database.options.connectionString,void this.emit("replicator.log.failed",{error:"replicator log resource not found",item:t});const r={id:t.id||`repl-${Date.now()}-${Math.random().toString(36).slice(2)}`,resource:t.resource||t.resourceName||"",action:t.operation||t.action||"",data:t.data||{},timestamp:"number"==typeof t.timestamp?t.timestamp:Date.now(),createdAt:t.createdAt||(new Date).toISOString().slice(0,10)},[i,s]=await wt(async()=>{await e.insert(r)});i||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to log replicator item: ${s.message}`),this.emit("replicator.log.failed",{error:s,item:t}))}async updatereplicatorLog(t,e){if(!this.replicatorLog)return;const[r,i]=await wt(async()=>{await this.replicatorLog.update(t,{...e,lastAttempt:(new Date).toISOString()})});r||this.emit("replicator.updateLog.failed",{error:i.message,logId:t,updates:e})}async getreplicatorStats(){return{replicators:await Promise.all(this.replicators.map(async t=>{const e=await t.getStatus();return{id:t.id,driver:t.driver,config:t.config,status:e}})),queue:{length:this.queue.length,isProcessing:this.isProcessing},stats:this.stats,lastSync:this.stats.lastSync}}async getreplicatorLogs(t={}){if(!this.replicatorLog)return[];const{resourceName:e,operation:r,status:i,limit:s=100,offset:n=0}=t;let a={};e&&(a.resourceName=e),r&&(a.operation=r),i&&(a.status=i);return(await this.replicatorLog.list(a)).slice(n,n+s)}async retryFailedreplicators(){if(!this.replicatorLog)return{retried:0};const t=await this.replicatorLog.list({status:"failed"});let e=0;for(const r of t){const[t,i]=await wt(async()=>{await this.processReplicatorEvent(r.resourceName,r.operation,r.recordId,r.data)});t&&e++}return{retried:e}}async syncAllData(t){const e=this.replicators.find(e=>e.id===t);if(!e)throw new Error(`Replicator not found: ${t}`);this.stats.lastSync=(new Date).toISOString();for(const r in this.database.resources)if(Ss(r)!==Ss("replicator_logs")&&e.shouldReplicateResource(r)){this.emit("replicator.sync.resource",{resourceName:r,replicatorId:t});const i=this.database.resources[r],s=await i.getAll();for(const t of s)await e.replicate(r,"insert",t,t.id)}this.emit("replicator.sync.completed",{replicatorId:t,stats:this.stats})}async cleanup(){const[t,e]=await wt(async()=>{if(this.replicators&&this.replicators.length>0){const t=this.replicators.map(async t=>{const[e,r]=await wt(async()=>{t&&"function"==typeof t.cleanup&&await t.cleanup()});e||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to cleanup replicator ${t.name||t.id}: ${r.message}`),this.emit("replicator_cleanup_error",{replicator:t.name||t.id||"unknown",driver:t.driver||"unknown",error:r.message}))});await Promise.allSettled(t)}this.replicators=[],this.database=null,this.eventListenersInstalled.clear(),this.removeAllListeners()});t||(this.config.verbose&&console.warn(`[ReplicatorPlugin] Failed to cleanup plugin: ${e.message}`),this.emit("replicator_plugin_cleanup_error",{error:e.message}))}}export{fs as AVAILABLE_BEHAVIORS,Lt as AuditPlugin,tt as AuthenticationError,G as BaseError,Ii as CachePlugin,Fi as Client,Ui as ConnectionString,ft as ConnectionStringError,$i as CostsPlugin,dt as CryptoError,ds as DEFAULT_BEHAVIOR,ms as Database,X as DatabaseError,rt as EncryptionError,ut as ErrorMap,Pi as FullTextPlugin,ct as InvalidResourceItem,Ci as MetricsPlugin,ot as MissingMetadata,st as NoSuchBucket,nt as NoSuchKey,at as NotFound,mt as PartitionError,et as PermissionError,Tt as Plugin,Mt as PluginObject,_s as ReplicatorPlugin,ps as Resource,gt as ResourceError,ki as ResourceIdsPageReader,Si as ResourceIdsReader,it as ResourceNotFound,Oi as ResourceReader,Ri as ResourceWriter,ms as S3db,Q as S3dbError,Ji as Schema,pt as SchemaError,lt as UnknownError,Z as ValidationError,Vi as Validator,us as behaviors,z as calculateAttributeNamesSize,K as calculateAttributeSizes,Y as calculateEffectiveLimit,H as calculateSystemOverhead,W as calculateTotalSize,B as calculateUTF8Bytes,U as decode,q as decodeDecimal,kt as decrypt,ys as default,L as encode,F as encodeDecimal,_t as encrypt,hs as getBehavior,J as getSizeBreakdown,jt as idGenerator,ht as mapAwsError,Ot as md5,xt as passwordGenerator,St as sha256,ji as streamToString,V as transformValue,yt as tryFn,bt as tryFnSync};