s3db.js 7.0.0 → 7.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/s3db.cjs.js +1730 -20692
- package/dist/s3db.cjs.min.js +1 -1
- package/dist/s3db.es.js +1732 -20695
- package/dist/s3db.es.min.js +1 -1
- package/dist/s3db.iife.js +1730 -20694
- package/dist/s3db.iife.min.js +1 -1
- package/package.json +38 -7
- package/src/client.class.js +2 -2
- package/src/concerns/crypto.js +17 -0
- package/src/plugins/cache/s3-cache.class.js +1 -1
package/dist/s3db.es.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{customAlphabet as e,urlAlphabet as t}from"nanoid";import{streamToString as r}from"#src/stream/index.js";import{chunk as n,merge as i,isString as o,isEmpty as s,invert as a,uniq as c,cloneDeep as u,get as l,set as h,isObject as f,isFunction as d,isPlainObject as p}from"lodash-es";import{createHash as g}from"crypto";import{PromisePool as m}from"@supercharge/promise-pool";import{S3Client as y,PutObjectCommand as w,GetObjectCommand as b,HeadObjectCommand as v,CopyObjectCommand as E,DeleteObjectCommand as I,DeleteObjectsCommand as _,ListObjectsV2Command as A}from"@aws-sdk/client-s3";import{flatten as k,unflatten as B}from"flat";import x from"fastest-validator";import{ReadableStream as S}from"node:stream/web";function O(e){"string"!=typeof e&&(e=String(e));let t=0;for(let r=0;r<e.length;r++){const n=e.codePointAt(r);n<=127?t+=1:n<=2047?t+=2:n<=65535?t+=3:n<=1114111&&(t+=4,n>65535&&r++)}return t}function U(e){let t=0;for(const r of Object.keys(e))t+=O(r);return t}function C(e){return null==e?"":"boolean"==typeof e?e?"1":"0":"number"==typeof e?String(e):"string"==typeof e?e:Array.isArray(e)?0===e.length?"[]":e.map(e=>String(e)).join("|"):"object"==typeof e?JSON.stringify(e):String(e)}function N(e){const t={};for(const[r,n]of Object.entries(e)){const e=O(C(n));t[r]=e}return t}function R(e){const t=N(e);return Object.values(t).reduce((e,t)=>e+t,0)+U(e)}function T(e){const t=N(e),r=U(e),n=Object.values(t).reduce((e,t)=>e+t,0),i=n+r,o=Object.entries(t).sort(([,e],[,t])=>t-e).map(([e,t])=>({attribute:e,size:t,percentage:(t/i*100).toFixed(2)+"%"}));return{total:i,valueSizes:t,namesSize:r,valueTotal:n,breakdown:o,detailedBreakdown:{values:n,names:r,total:i}}}function L(e={}){const{version:t="1",timestamps:r=!1,id:n=""}=e,i={_v:String(t)};r&&(i.createdAt="2024-01-01T00:00:00.000Z",i.updatedAt="2024-01-01T00:00:00.000Z"),n&&(i.id=n);const o={};for(const[e,t]of Object.entries(i))o[e]=t;return R(o)}function D(e={}){const{s3Limit:t=2048,systemConfig:r={}}=e;return t-L(r)}const j=2047;var M=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:j,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:async function({resource:e,data:t,mappedData:r,originalData:n}){const i=R(r),o=D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}});if(i>o)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${i} bytes, effective limit: ${o} bytes, absolute limit: 2047 bytes`);return{mappedData:r,body:JSON.stringify(r)}},handleUpdate:async function({resource:e,id:t,data:r,mappedData:n,originalData:i}){const o=R(n),s=D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}});if(o>s)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${o} bytes, effective limit: ${s} bytes, absolute limit: 2047 bytes`);return{mappedData:n,body:JSON.stringify(n)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:n}){const i=R(n),o=D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}});if(i>o)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${i} bytes, effective limit: ${o} bytes, absolute limit: 2047 bytes`);return{mappedData:n,body:""}}});var P=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:async function({resource:e,data:t,mappedData:r,originalData:n}){const i=R(r);return i>D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}})&&e.emit("exceedsLimit",{operation:"insert",totalSize:i,limit:2047,excess:i-2047,data:n||t}),{mappedData:r,body:JSON.stringify(t)}},handleUpdate:async function({resource:e,id:t,data:r,mappedData:n,originalData:i}){const o=R(n);return o>D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}})&&e.emit("exceedsLimit",{operation:"update",id:t,totalSize:o,limit:2047,excess:o-2047,data:i||r}),{mappedData:n,body:JSON.stringify(r)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:n,originalData:i}){const o=R(n);return o>D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}})&&e.emit("exceedsLimit",{operation:"upsert",id:t,totalSize:o,limit:2047,excess:o-2047,data:i||r}),{mappedData:n,body:JSON.stringify(r)}}});const F="$truncated",q="true",Q=O(F)+O(q);async function z({resource:e,data:t,mappedData:r,originalData:n}){const i=D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),o=N(r),s=Object.entries(o).sort(([,e],[,t])=>e-t),a={};let c=0,u=!1;r._v&&(a._v=r._v,c+=o._v);for(const[e,t]of s){if("_v"===e)continue;const n=r[e];if(!(c+(t+(u?0:Q))<=i)){const t=i-c-(u?0:Q);if(t>0){const r=$(n,t);a[e]=r,u=!0,c+=O(r)}else a[e]="",u=!0;break}a[e]=n,c+=t}let l=R(a)+(u?Q:0);for(;l>i;){const e=Object.keys(a).filter(e=>"_v"!==e&&"$truncated"!==e);if(0===e.length)break;a[e[e.length-1]]="",l=R(a)+Q,u=!0}return u&&(a[F]=q),{mappedData:a,body:JSON.stringify(r)}}function $(e,t){if("string"==typeof e)return H(e,t);if("object"==typeof e&&null!==e){return H(JSON.stringify(e),t)}return H(String(e),t)}function H(e,t){const r=new TextEncoder;let n=r.encode(e);if(n.length<=t)return e;let i=e.length;for(;i>0;){const o=e.substring(0,i);if(n=r.encode(o),n.length<=t)return o;i--}return""}var V=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:z,handleUpdate:async function({resource:e,id:t,data:r,mappedData:n,originalData:i}){return z({resource:e,data:r,mappedData:n,originalData:i})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:n}){return z({resource:e,data:r,mappedData:n})}});function G(e){if(null==e){const e=new Error("fnOrPromise cannot be null or undefined");return e.stack=(new Error).stack,[!1,e,void 0]}if("function"==typeof e)try{const t=e();return null==t?[!0,null,t]:"function"==typeof t.then?t.then(e=>[!0,null,e]).catch(e=>{if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}):[!0,null,t]}catch(e){if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}return"function"==typeof e.then?Promise.resolve(e).then(e=>[!0,null,e]).catch(e=>{if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}):[!0,null,e]}function K(e){try{return[!0,null,e()]}catch(e){return[!1,e,null]}}const W="$overflow",J="true",Z=O(W)+O(J);async function Y({resource:e,data:t,mappedData:r,originalData:n}){const i=D({s3Limit:j,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),o=N(r),s=Object.entries(o).sort(([,e],[,t])=>e-t),a={},c={};let u=0,l=!1;r._v&&(a._v=r._v,u+=o._v);let h=i;for(const[e,t]of s)"_v"!==e&&(!l&&u+t>i&&(h-=Z,l=!0),!l&&u+t<=h?(a[e]=r[e],u+=t):(c[e]=r[e],l=!0));l&&(a[W]=J);const f=Object.keys(c).length>0;let d=f?JSON.stringify(c):"";return f||(d="{}"),{mappedData:a,body:d}}var X=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){let n={};if(r&&""!==r.trim()){const[e,t,i]=K(()=>JSON.parse(r));n=e?i:{}}const i={...n,...t};return delete i.$overflow,{metadata:i,body:r}},handleInsert:Y,handleUpdate:async function({resource:e,id:t,data:r,mappedData:n,originalData:i}){return Y({resource:e,data:r,mappedData:n,originalData:i})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:n}){return Y({resource:e,data:r,mappedData:n})}});async function ee({resource:e,data:t,mappedData:r}){const n={_v:r._v||String(e.version)};n._map=JSON.stringify(e.schema.map);return{mappedData:n,body:JSON.stringify(r)}}var te=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){let n={};if(r&&""!==r.trim()){const[e,t,i]=K(()=>JSON.parse(r));n=e?i:{}}return{metadata:{...n,...t},body:r}},handleInsert:ee,handleUpdate:async function({resource:e,id:t,data:r,mappedData:n}){const i={_v:n._v||String(e.version)};return i._map=JSON.stringify(e.schema.map),{mappedData:i,body:JSON.stringify(n)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:n}){return ee({resource:e,data:r,mappedData:n})}});const re={"user-managed":P,"enforce-limits":M,"truncate-data":V,"body-overflow":X,"body-only":te};function ne(e){const t=re[e];if(!t)throw new Error(`Unknown behavior: ${e}. Available behaviors: ${Object.keys(re).join(", ")}`);return t}const ie=Object.keys(re),oe="user-managed",se="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",ae=Object.fromEntries([...se].map((e,t)=>[e,t])),ce=e=>{if("number"!=typeof e||isNaN(e))return"undefined";if(!isFinite(e))return"undefined";if(0===e)return se[0];if(e<0)return"-"+ce(-Math.floor(e));e=Math.floor(e);let t="";for(;e;)t=se[e%62]+t,e=Math.floor(e/62);return t},ue=e=>{if("string"!=typeof e)return NaN;if(""===e)return 0;let t=!1;"-"===e[0]&&(t=!0,e=e.slice(1));let r=0;for(let t=0;t<e.length;t++){const n=ae[e[t]];if(void 0===n)return NaN;r=62*r+n}return t?-r:r},le=e=>{if("number"!=typeof e||isNaN(e))return"undefined";if(!isFinite(e))return"undefined";const t=e<0;e=Math.abs(e);const[r,n]=e.toString().split("."),i=ce(Number(r));return n?(t?"-":"")+i+"."+n:(t?"-":"")+i},he=e=>{if("string"!=typeof e)return NaN;let t=!1;"-"===e[0]&&(t=!0,e=e.slice(1));const[r,n]=e.split("."),i=ue(r);if(isNaN(i))return NaN;const o=n?Number(i+"."+n):i;return t?-o:o};class fe extends Error{constructor({verbose:e,bucket:t,key:r,message:n,code:i,statusCode:o,requestId:s,awsMessage:a,original:c,commandName:u,commandInput:l,metadata:h,suggestion:f,...d}){e&&(n+=`\n\nVerbose:\n\n${JSON.stringify(d,null,2)}`),super(n),"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error(n).stack,super.name=this.constructor.name,this.name=this.constructor.name,this.bucket=t,this.key=r,this.thrownAt=new Date,this.code=i,this.statusCode=o,this.requestId=s,this.awsMessage=a,this.original=c,this.commandName=u,this.commandInput=l,this.metadata=h,this.suggestion=f,this.data={bucket:t,key:r,...d,verbose:e,message:n}}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 de extends fe{constructor(e,t={}){let r,n,i,o,s,a;t.original&&(s=t.original,r=s.code||s.Code||s.name,n=s.statusCode||s.$metadata&&s.$metadata.httpStatusCode,i=s.requestId||s.$metadata&&s.$metadata.requestId,o=s.message,a=s.$metadata?{...s.$metadata}:void 0),super({message:e,...t,code:r,statusCode:n,requestId:i,awsMessage:o,original:s,metadata:a})}}class pe extends de{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class ge extends de{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class me extends de{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class ye extends de{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class we extends de{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class be extends de{constructor({bucket:e,resourceName:t,id:r,original:n,...i}){if("string"!=typeof r)throw new Error("id must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");if("string"!=typeof t)throw new Error("resourceName must be a string");super(`Resource not found: ${t}/${r} [bucket:${e}]`,{bucket:e,resourceName:t,id:r,original:n,...i})}}class ve extends de{constructor({bucket:e,original:t,...r}){if("string"!=typeof e)throw new Error("bucket must be a string");super(`Bucket does not exists [bucket:${e}]`,{bucket:e,original:t,...r})}}class Ee extends de{constructor({bucket:e,key:t,resourceName:r,id:n,original:i,...o}){if("string"!=typeof t)throw new Error("key must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");if(void 0!==n&&"string"!=typeof n)throw new Error("id must be a string");super(`No such key: ${t} [bucket:${e}]`,{bucket:e,key:t,resourceName:r,id:n,original:i,...o}),this.resourceName=r,this.id=n}}class Ie extends de{constructor({bucket:e,key:t,resourceName:r,id:n,original:i,...o}){if("string"!=typeof t)throw new Error("key must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");super(`Not found: ${t} [bucket:${e}]`,{bucket:e,key:t,resourceName:r,id:n,original:i,...o}),this.resourceName=r,this.id=n}}class _e extends de{constructor({bucket:e,original:t,...r}){if("string"!=typeof e)throw new Error("bucket must be a string");super(`Missing metadata for bucket [bucket:${e}]`,{bucket:e,original:t,...r})}}class Ae extends de{constructor({bucket:e,resourceName:t,attributes:r,validation:n,message:i,original:o,...s}){if("string"!=typeof e)throw new Error("bucket must be a string");if("string"!=typeof t)throw new Error("resourceName must be a string");super(i||`Validation error: This item is not valid. Resource=${t} [bucket:${e}].\n${JSON.stringify(n,null,2)}`,{bucket:e,resourceName:t,attributes:r,validation:n,original:o,...s})}}class ke extends de{}const Be={NotFound:Ie,NoSuchKey:Ee,UnknownError:ke,NoSuchBucket:ve,MissingMetadata:_e,InvalidResourceItem:Ae};function xe(e,t={}){const r=e.code||e.Code||e.name,n=e.$metadata?{...e.$metadata}:void 0,i=t.commandName,o=t.commandInput;let s;return"NoSuchKey"===r||"NotFound"===r?(s="Check if the key exists in the specified bucket and if your credentials have permission.",new Ee({...t,original:e,metadata:n,commandName:i,commandInput:o,suggestion:s})):"NoSuchBucket"===r?(s="Check if the bucket exists and if your credentials have permission.",new ve({...t,original:e,metadata:n,commandName:i,commandInput:o,suggestion:s})):"AccessDenied"===r||403===e.statusCode||"Forbidden"===r?(s="Check your credentials and bucket policy.",new ye("Access denied",{...t,original:e,metadata:n,commandName:i,commandInput:o,suggestion:s})):"ValidationError"===r||400===e.statusCode?(s="Check the request parameters and payload.",new ge("Validation error",{...t,original:e,metadata:n,commandName:i,commandInput:o,suggestion:s})):"MissingMetadata"===r?(s="Check if the object metadata is present and valid.",new _e({...t,original:e,metadata:n,commandName:i,commandInput:o,suggestion:s})):(s="Check the error details and AWS documentation.",new ke("Unknown error",{...t,original:e,metadata:n,commandName:i,commandInput:o,suggestion:s}))}class Se extends de{constructor(e,t={}){super(e,{...t,suggestion:"Check the connection string format and credentials."})}}class Oe extends de{constructor(e,t={}){super(e,{...t,suggestion:"Check if the crypto library is available and input is valid."})}}class Ue extends de{constructor(e,t={}){super(e,{...t,suggestion:"Check schema definition and input data."})}}class Ce extends de{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check resource configuration, attributes, and operation context."}),Object.assign(this,t)}}class Ne extends de{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check partition definition, fields, and input values."})}}async function Re(){let e;if("undefined"!=typeof process){const[t,r,n]=await G(async()=>{const{webcrypto:e}=await import("crypto");return e});if(!t)throw new Oe("Crypto API not available",{original:r,context:"dynamicCrypto"});e=n}else"undefined"!=typeof window&&(e=window.crypto);if(!e)throw new Oe("Could not load any crypto library",{context:"dynamicCrypto"});return e}async function Te(e){const[t,r,n]=await G(Re);if(!t)throw new Oe("Crypto API not available",{original:r});const i=(new TextEncoder).encode(e),[o,s,a]=await G(()=>n.subtle.digest("SHA-256",i));if(!o)throw new Oe("SHA-256 digest failed",{original:s,input:e});return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function Le(e,t){const[r,n,i]=await G(Re);if(!r)throw new Oe("Crypto API not available",{original:n});const o=i.getRandomValues(new Uint8Array(16)),[s,a,c]=await G(()=>je(t,o));if(!s)throw new Oe("Key derivation failed",{original:a,passphrase:t,salt:o});const u=i.getRandomValues(new Uint8Array(12)),l=(new TextEncoder).encode(e),[h,f,d]=await G(()=>i.subtle.encrypt({name:"AES-GCM",iv:u},c,l));if(!h)throw new Oe("Encryption failed",{original:f,content:e});const p=new Uint8Array(o.length+u.length+d.byteLength);return p.set(o),p.set(u,o.length),p.set(new Uint8Array(d),o.length+u.length),function(e){if("undefined"!=typeof process)return Buffer.from(e).toString("base64");{const[t,r,n]=K(()=>String.fromCharCode.apply(null,new Uint8Array(e)));if(!t)throw new Oe("Failed to convert ArrayBuffer to base64 (browser)",{original:r});return window.btoa(n)}}(p)}async function De(e,t){const[r,n,i]=await G(Re);if(!r)throw new Oe("Crypto API not available",{original:n});const o=function(e){if("undefined"!=typeof process)return new Uint8Array(Buffer.from(e,"base64"));{const[t,r,n]=K(()=>window.atob(e));if(!t)throw new Oe("Failed to decode base64 (browser)",{original:r});const i=n.length,o=new Uint8Array(i);for(let e=0;e<i;e++)o[e]=n.charCodeAt(e);return o}}(e),s=o.slice(0,16),a=o.slice(16,28),c=o.slice(28),[u,l,h]=await G(()=>je(t,s));if(!u)throw new Oe("Key derivation failed (decrypt)",{original:l,passphrase:t,salt:s});const[f,d,p]=await G(()=>i.subtle.decrypt({name:"AES-GCM",iv:a},h,c));if(!f)throw new Oe("Decryption failed",{original:d,encryptedBase64:e});return(new TextDecoder).decode(p)}async function je(e,t){const[r,n,i]=await G(Re);if(!r)throw new Oe("Crypto API not available",{original:n});const o=(new TextEncoder).encode(e),[s,a,c]=await G(()=>i.subtle.importKey("raw",o,{name:"PBKDF2"},!1,["deriveKey"]));if(!s)throw new Oe("importKey failed",{original:a,passphrase:e});const[u,l,h]=await G(()=>i.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:1e5,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]));if(!u)throw new Oe("deriveKey failed",{original:l,passphrase:e,salt:t});return h}const Me=e(t,22),Pe=e("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",16);var Fe;function qe(){}function Qe(){Qe.init.call(this)}function ze(e){return void 0===e._maxListeners?Qe.defaultMaxListeners:e._maxListeners}function $e(e,t,r,n){var i,o,s,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((o=e._events)?(o.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),o=e._events),s=o[t]):(o=e._events=new qe,e._eventsCount=0),s){if("function"==typeof s?s=o[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),!s.warned&&(i=ze(e))&&i>0&&s.length>i){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=s.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else s=o[t]=r,++e._eventsCount;return e}function He(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Ve(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Ge(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}qe.prototype=Object.create(null),Qe.EventEmitter=Qe,Qe.usingDomains=!1,Qe.prototype.domain=void 0,Qe.prototype._events=void 0,Qe.prototype._maxListeners=void 0,Qe.defaultMaxListeners=10,Qe.init=function(){this.domain=null,Qe.usingDomains&&(!Fe.active||this instanceof Fe.Domain||(this.domain=Fe.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new qe,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Qe.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Qe.prototype.getMaxListeners=function(){return ze(this)},Qe.prototype.emit=function(e){var t,r,n,i,o,s,a,c="error"===e;if(s=this._events)c=c&&null==s.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=s[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Ge(e,n),o=0;o<n;++o)i[o].call(r)}(r,l,this);break;case 2:!function(e,t,r,n){if(t)e.call(r,n);else for(var i=e.length,o=Ge(e,i),s=0;s<i;++s)o[s].call(r,n)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,n,i){if(t)e.call(r,n,i);else for(var o=e.length,s=Ge(e,o),a=0;a<o;++a)s[a].call(r,n,i)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,n,i,o){if(t)e.call(r,n,i,o);else for(var s=e.length,a=Ge(e,s),c=0;c<s;++c)a[c].call(r,n,i,o)}(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o<n;o++)i[o-1]=arguments[o];!function(e,t,r,n){if(t)e.apply(r,n);else for(var i=e.length,o=Ge(e,i),s=0;s<i;++s)o[s].apply(r,n)}(r,l,this,i)}return!0},Qe.prototype.addListener=function(e,t){return $e(this,e,t,!1)},Qe.prototype.on=Qe.prototype.addListener,Qe.prototype.prependListener=function(e,t){return $e(this,e,t,!0)},Qe.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,He(this,e,t)),this},Qe.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,He(this,e,t)),this},Qe.prototype.removeListener=function(e,t){var r,n,i,o,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener&&r.listener===t)0===--this._eventsCount?this._events=new qe:(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(i=-1,o=r.length;o-- >0;)if(r[o]===t||r[o].listener&&r[o].listener===t){s=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0===--this._eventsCount)return this._events=new qe,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n<i;r+=1,n+=1)e[r]=e[n];e.pop()}(r,i);n.removeListener&&this.emit("removeListener",e,s||t)}return this},Qe.prototype.off=function(e,t){return this.removeListener(e,t)},Qe.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new qe,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new qe:delete r[e]),this;if(0===arguments.length){for(var n,i=Object.keys(r),o=0;o<i.length;++o)"removeListener"!==(n=i[o])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=new qe,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Qe.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},Qe.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Ve.call(e,t)},Qe.prototype.listenerCount=Ve,Qe.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var Ke=Object.freeze({__proto__:null,EventEmitter:Qe,default:Qe});class We extends Qe{constructor(e={}){super(),this.name=this.constructor.name,this.options=e,this.hooks=new Map}async setup(e){this.database=e,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(e,t,r){this.hooks.has(e)||this.hooks.set(e,new Map);const n=this.hooks.get(e);n.has(t)||n.set(t,[]),n.get(t).push(r)}removeHook(e,t,r){const n=this.hooks.get(e);if(n&&n.has(t)){const e=n.get(t),i=e.indexOf(r);i>-1&&e.splice(i,1)}}wrapResourceMethod(e,t,r){const n=e[t];if(e._pluginWrappers||(e._pluginWrappers=new Map),e._pluginWrappers.has(t)||e._pluginWrappers.set(t,[]),e._pluginWrappers.get(t).push(r),!e[`_wrapped_${t}`]){e[`_wrapped_${t}`]=n;const r=n&&n._isMockFunction;e[t]=async function(...r){let n=await e[`_wrapped_${t}`](...r);for(const i of e._pluginWrappers.get(t))n=await i.call(this,n,r,t);return n},r&&(Object.setPrototypeOf(e[t],Object.getPrototypeOf(n)),Object.assign(e[t],n))}}addMiddleware(e,t,r){if(e._pluginMiddlewares||(e._pluginMiddlewares={}),!e._pluginMiddlewares[t]){e._pluginMiddlewares[t]=[];const r=e[t].bind(e);e[t]=async function(...n){let i=-1;const o=async(...n)=>(i++,i<e._pluginMiddlewares[t].length?await e._pluginMiddlewares[t][i].call(this,o,...n):await r(...n));return await o(...n)}}e._pluginMiddlewares[t].push(r)}getPartitionValues(e,t){if(!t.config?.partitions)return{};const r={};for(const[n,i]of Object.entries(t.config.partitions))if(i.fields){r[n]={};for(const[o,s]of Object.entries(i.fields)){const i=this.getNestedFieldValue(e,o);null!=i&&(r[n][o]=t.applyPartitionRule(i,s))}}else r[n]={};return r}getNestedFieldValue(e,t){if(!t.includes("."))return e[t]??null;const r=t.split(".");let n=e;for(const e of r){if(!n||"object"!=typeof n||!(e in n))return null;n=n[e]}return n??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 Je={setup(e){},start(){},stop(){}};class Ze extends We{constructor(e={}){super(e),this.auditResource=null,this.config={includeData:!1!==e.includeData,includePartitions:!1!==e.includePartitions,maxDataSize:e.maxDataSize||1e4,...e}}async onSetup(){const[e,t,r]=await G(()=>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=e?r:this.database.resources.audits||null,(e||this.auditResource)&&(this.installDatabaseProxy(),this.installEventListeners())}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._auditProxyInstalled)return;const e=this.installEventListenersForResource.bind(this);this.database._originalCreateResource=this.database.createResource,this.database.createResource=async function(...t){const r=await this._originalCreateResource(...t);return"audits"!==r.name&&e(r),r},this.database._auditProxyInstalled=!0}installEventListeners(){for(const e of Object.values(this.database.resources))"audits"!==e.name&&this.installEventListenersForResource(e)}installEventListenersForResource(e){e.on("insert",async t=>{const r=t.id||"auto-generated",n=this.config.includePartitions?this.getPartitionValues(t,e):null,i={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.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(t)),partition:this.config.includePartitions?this.getPrimaryPartition(n):null,partitionValues:this.config.includePartitions&&n&&Object.keys(n).length>0?JSON.stringify(n):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0"})};this.logAudit(i).catch(console.error)}),e.on("update",async t=>{const r=t.id;let n=t.$before;if(this.config.includeData&&!n){const[t,i,o]=await G(()=>e.get(r));t&&(n=o)}const i=this.config.includePartitions?this.getPartitionValues(t,e):null,o={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"update",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:n&&!1===this.config.includeData?null:n?JSON.stringify(this.truncateData(n)):null,newData:!1===this.config.includeData?null:JSON.stringify(this.truncateData(t)),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(o).catch(console.error)}),e.on("delete",async t=>{const r=t.id;let n=t;if(this.config.includeData&&!n){const[t,i,o]=await G(()=>e.get(r));t&&(n=o)}const i=n&&this.config.includePartitions?this.getPartitionValues(n,e):null,o={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"delete",recordId:r,userId:this.getCurrentUserId?.()||"system",timestamp:(new Date).toISOString(),oldData:n&&!1===this.config.includeData?null:n?JSON.stringify(this.truncateData(n)):null,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"})};this.logAudit(o).catch(console.error)}),e.useMiddleware("deleteMany",async(t,r)=>{const n=t.args[0],i={};if(this.config.includeData)for(const t of n){const[r,n,o]=await G(()=>e.get(t));i[t]=r?o:null}const o=await r();if(o&&o.length>0&&this.config.includeData)for(const t of n){const r=i[t],n=r&&this.config.includePartitions?this.getPartitionValues(r,e):null,o={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"delete",recordId:t,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(n):null,partitionValues:this.config.includePartitions&&n&&Object.keys(n).length>0?JSON.stringify(n):null,metadata:JSON.stringify({source:"audit-plugin",version:"2.0",batchOperation:!0})};this.logAudit(o).catch(console.error)}return o})}getPartitionValues(e,t){if(!e)return null;const r=t.config?.partitions||{},n={};for(const[t,i]of Object.entries(r))if(i.fields){const r={};for(const[t,n]of Object.entries(i.fields)){const n=this.getNestedFieldValue(e,t);null!=n&&(r[t]=n)}Object.keys(r).length>0&&(n[t]=r)}return n}getNestedFieldValue(e,t){if(!t.includes("."))return e[t];const r=t.split(".");let n=e;for(const e of r){if(!n||"object"!=typeof n||!(e in n))return;n=n[e]}return n}getPrimaryPartition(e){if(!e)return null;const t=Object.keys(e);return t.length>0?t[0]:null}async logAudit(e){e.id||(e.id=`audit-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return await this.auditResource.insert(e)}truncateData(e){if(!e)return e;const t={};for(const[r,n]of Object.entries(e))r.startsWith("_")||"$overflow"===r||(t[r]=n);const r=JSON.stringify(t);if(r.length<=this.config.maxDataSize)return t;let n={...t},i=JSON.stringify(n).length;const o=JSON.stringify({_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}).length,s=this.config.maxDataSize-o;for(const[e,t]of Object.entries(n))if("string"==typeof t&&i>s){const r=i-s,o=Math.max(0,t.length-r-3);o<t.length&&(n[e]=t.substring(0,o)+"...",i=JSON.stringify(n).length)}return{...n,_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}}async getAuditLogs(e={}){if(!this.auditResource)return[];const[t,r,n]=await G(async()=>{const{resourceName:t,operation:r,recordId:n,userId:i,partition:o,startDate:s,endDate:a,limit:c=100,offset:u=0}=e;let l=(await this.auditResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&((!n||e.recordId===n)&&((!i||e.userId===i)&&((!o||e.partition===o)&&(!(s&&new Date(e.timestamp)<new Date(s))&&!(a&&new Date(e.timestamp)>new Date(a))))))));l.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp));return l.slice(u,u+c).map(e=>{const[t,,r]="string"==typeof e.oldData?K(()=>JSON.parse(e.oldData)):[!0,null,e.oldData],[n,,i]="string"==typeof e.newData?K(()=>JSON.parse(e.newData)):[!0,null,e.newData],[o,,s]=e.partitionValues&&"string"==typeof e.partitionValues?K(()=>JSON.parse(e.partitionValues)):[!0,null,e.partitionValues],[a,,c]=e.metadata&&"string"==typeof e.metadata?K(()=>JSON.parse(e.metadata)):[!0,null,e.metadata];return{...e,oldData:null===e.oldData||void 0===e.oldData||"null"===e.oldData?null:t?r:null,newData:null===e.newData||void 0===e.newData||"null"===e.newData?null:n?i:null,partitionValues:o?s:e.partitionValues,metadata:a?c:e.metadata}})});return t?n:[]}async getRecordHistory(e,t){return this.getAuditLogs({resourceName:e,recordId:t,limit:1e3})}async getPartitionHistory(e,t,r){return this.getAuditLogs({resourceName:e,partition:t,limit:1e3})}async getAuditStats(e={}){const{resourceName:t,startDate:r,endDate:n}=e,i=await this.getAuditLogs({resourceName:t,startDate:r,endDate:n,limit:1e4}),o={total:i.length,byOperation:{},byResource:{},byPartition:{},byUser:{},timeline:{}};for(const e of i)if(o.byOperation[e.operation]=(o.byOperation[e.operation]||0)+1,o.byResource[e.resourceName]=(o.byResource[e.resourceName]||0)+1,e.partition&&(o.byPartition[e.partition]=(o.byPartition[e.partition]||0)+1),o.byUser[e.userId]=(o.byUser[e.userId]||0)+1,e.timestamp){const t=e.timestamp.split("T")[0];o.timeline[t]=(o.timeline[t]||0)+1}return o}}function Ye(e,t){for(var r=0,n=e.length-1;n>=0;n--){var i=e[n];"."===i?e.splice(n,1):".."===i?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}var Xe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,et=function(e){return Xe.exec(e).slice(1)};function tt(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:"/";if("string"!=typeof n)throw new TypeError("Arguments to path.resolve must be strings");n&&(e=n+"/"+e,t="/"===n.charAt(0))}return(t?"/":"")+(e=Ye(st(e.split("/"),function(e){return!!e}),!t).join("/"))||"."}function rt(e){var t=nt(e),r="/"===at(e,-1);return(e=Ye(st(e.split("/"),function(e){return!!e}),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e}function nt(e){return"/"===e.charAt(0)}function it(){return rt(st(Array.prototype.slice.call(arguments,0),function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))}var ot={extname:function(e){return et(e)[3]},basename:function(e,t){var r=et(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r},dirname:function(e){var t=et(e),r=t[0],n=t[1];return r||n?(n&&(n=n.substr(0,n.length-1)),r+n):"."},sep:"/",delimiter:":",relative:function(e,t){function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var r=e.length-1;r>=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=tt(e).substr(1),t=tt(t).substr(1);for(var n=r(e.split("/")),i=r(t.split("/")),o=Math.min(n.length,i.length),s=o,a=0;a<o;a++)if(n[a]!==i[a]){s=a;break}var c=[];for(a=s;a<n.length;a++)c.push("..");return(c=c.concat(i.slice(s))).join("/")},join:it,isAbsolute:nt,normalize:rt,resolve:tt};function st(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n<e.length;n++)t(e[n],n,e)&&r.push(e[n]);return r}var at="b"==="ab".substr(-1)?function(e,t,r){return e.substr(t,r)}:function(e,t,r){return t<0&&(t=e.length+t),e.substr(t,r)},ct="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},ut=[],lt=[],ht="undefined"!=typeof Uint8Array?Uint8Array:Array,ft=!1;function dt(){ft=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)ut[t]=e[t],lt[e.charCodeAt(t)]=t;lt["-".charCodeAt(0)]=62,lt["_".charCodeAt(0)]=63}function pt(e){return ut[e>>18&63]+ut[e>>12&63]+ut[e>>6&63]+ut[63&e]}function gt(e,t,r){for(var n,i=[],o=t;o<r;o+=3)n=(e[o]<<16)+(e[o+1]<<8)+e[o+2],i.push(pt(n));return i.join("")}function mt(e){var t;ft||dt();for(var r=e.length,n=r%3,i="",o=[],s=16383,a=0,c=r-n;a<c;a+=s)o.push(gt(e,a,a+s>c?c:a+s));return 1===n?(t=e[r-1],i+=ut[t>>2],i+=ut[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=ut[t>>10],i+=ut[t>>4&63],i+=ut[t<<2&63],i+="="),o.push(i),o.join("")}function yt(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?i-1:0,f=r?-1:1,d=e[t+h];for(h+=f,o=d&(1<<-l)-1,d>>=-l,l+=a;l>0;o=256*o+e[t+h],h+=f,l-=8);for(s=o&(1<<-l)-1,o>>=-l,l+=n;l>0;s=256*s+e[t+h],h+=f,l-=8);if(0===o)o=1-u;else{if(o===c)return s?NaN:1/0*(d?-1:1);s+=Math.pow(2,n),o-=u}return(d?-1:1)*s*Math.pow(2,o-n)}function wt(e,t,r,n,i,o){var s,a,c,u=8*o-i-1,l=(1<<u)-1,h=l>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=l):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(s++,c/=2),s+h>=l?(a=0,s=l):s+h>=1?(a=(t*c-1)*Math.pow(2,i),s+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,i),s=0));i>=8;e[r+d]=255&a,d+=p,a/=256,i-=8);for(s=s<<i|a,u+=i;u>0;e[r+d]=255&s,d+=p,s/=256,u-=8);e[r+d-p]|=128*g}var bt={}.toString,vt=Array.isArray||function(e){return"[object Array]"==bt.call(e)};function Et(){return _t.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function It(e,t){if(Et()<t)throw new RangeError("Invalid typed array length");return _t.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=_t.prototype:(null===e&&(e=new _t(t)),e.length=t),e}function _t(e,t,r){if(!(_t.TYPED_ARRAY_SUPPORT||this instanceof _t))return new _t(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return Bt(this,e)}return At(this,e,t,r)}function At(e,t,r,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,n){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");t=void 0===r&&void 0===n?new Uint8Array(t):void 0===n?new Uint8Array(t,r):new Uint8Array(t,r,n);_t.TYPED_ARRAY_SUPPORT?(e=t).__proto__=_t.prototype:e=xt(e,t);return e}(e,t,r,n):"string"==typeof t?function(e,t,r){"string"==typeof r&&""!==r||(r="utf8");if(!_t.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|Ut(t,r);e=It(e,n);var i=e.write(t,r);i!==n&&(e=e.slice(0,i));return e}(e,t,r):function(e,t){if(Ot(t)){var r=0|St(t.length);return 0===(e=It(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(n=t.length)!=n?It(e,0):xt(e,t);if("Buffer"===t.type&&vt(t.data))return xt(e,t.data)}var n;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function kt(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function Bt(e,t){if(kt(t),e=It(e,t<0?0:0|St(t)),!_t.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function xt(e,t){var r=t.length<0?0:0|St(t.length);e=It(e,r);for(var n=0;n<r;n+=1)e[n]=255&t[n];return e}function St(e){if(e>=Et())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Et().toString(16)+" bytes");return 0|e}function Ot(e){return!(null==e||!e._isBuffer)}function Ut(e,t){if(Ot(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return nr(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ir(e).length;default:if(n)return nr(e).length;t=(""+t).toLowerCase(),n=!0}}function Ct(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Vt(this,t,r);case"utf8":case"utf-8":return Qt(this,t,r);case"ascii":return $t(this,t,r);case"latin1":case"binary":return Ht(this,t,r);case"base64":return qt(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Gt(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function Nt(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function Rt(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=_t.from(t,n)),Ot(t))return 0===t.length?-1:Tt(e,t,r,n,i);if("number"==typeof t)return t&=255,_t.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):Tt(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function Tt(e,t,r,n,i){var o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var l=-1;for(o=r;o<a;o++)if(u(e,o)===u(t,-1===l?0:o-l)){if(-1===l&&(l=o),o-l+1===c)return l*s}else-1!==l&&(o-=o-l),l=-1}else for(r+c>a&&(r=a-c),o=r;o>=0;o--){for(var h=!0,f=0;f<c;f++)if(u(e,o+f)!==u(t,f)){h=!1;break}if(h)return o}return-1}function Lt(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s<n;++s){var a=parseInt(t.substr(2*s,2),16);if(isNaN(a))return s;e[r+s]=a}return s}function Dt(e,t,r,n){return or(nr(t,e.length-r),e,r,n)}function jt(e,t,r,n){return or(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function Mt(e,t,r,n){return jt(e,t,r,n)}function Pt(e,t,r,n){return or(ir(t),e,r,n)}function Ft(e,t,r,n){return or(function(e,t){for(var r,n,i,o=[],s=0;s<e.length&&!((t-=2)<0);++s)n=(r=e.charCodeAt(s))>>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function qt(e,t,r){return 0===t&&r===e.length?mt(e):mt(e.slice(t,r))}function Qt(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i<r;){var o,s,a,c,u=e[i],l=null,h=u>239?4:u>223?3:u>191?2:1;if(i+h<=r)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(o=e[i+1]))&&(c=(31&u)<<6|63&o)>127&&(l=c);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(c=(15&u)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&u)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=h}return function(e){var t=e.length;if(t<=zt)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=zt));return r}(n)}_t.TYPED_ARRAY_SUPPORT=void 0===ct.TYPED_ARRAY_SUPPORT||ct.TYPED_ARRAY_SUPPORT,Et(),_t.poolSize=8192,_t._augment=function(e){return e.__proto__=_t.prototype,e},_t.from=function(e,t,r){return At(null,e,t,r)},_t.TYPED_ARRAY_SUPPORT&&(_t.prototype.__proto__=Uint8Array.prototype,_t.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&_t[Symbol.species]),_t.alloc=function(e,t,r){return function(e,t,r,n){return kt(t),t<=0?It(e,t):void 0!==r?"string"==typeof n?It(e,t).fill(r,n):It(e,t).fill(r):It(e,t)}(null,e,t,r)},_t.allocUnsafe=function(e){return Bt(null,e)},_t.allocUnsafeSlow=function(e){return Bt(null,e)},_t.isBuffer=sr,_t.compare=function(e,t){if(!Ot(e)||!Ot(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},_t.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},_t.concat=function(e,t){if(!vt(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return _t.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=_t.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){var o=e[r];if(!Ot(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(n,i),i+=o.length}return n},_t.byteLength=Ut,_t.prototype._isBuffer=!0,_t.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)Nt(this,t,t+1);return this},_t.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)Nt(this,t,t+3),Nt(this,t+1,t+2);return this},_t.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)Nt(this,t,t+7),Nt(this,t+1,t+6),Nt(this,t+2,t+5),Nt(this,t+3,t+4);return this},_t.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Qt(this,0,e):Ct.apply(this,arguments)},_t.prototype.equals=function(e){if(!Ot(e))throw new TypeError("Argument must be a Buffer");return this===e||0===_t.compare(this,e)},_t.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},_t.prototype.compare=function(e,t,r,n,i){if(!Ot(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),c=this.slice(n,i),u=e.slice(t,r),l=0;l<a;++l)if(c[l]!==u[l]){o=c[l],s=u[l];break}return o<s?-1:s<o?1:0},_t.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},_t.prototype.indexOf=function(e,t,r){return Rt(this,e,t,r,!0)},_t.prototype.lastIndexOf=function(e,t,r){return Rt(this,e,t,r,!1)},_t.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return Lt(this,e,t,r);case"utf8":case"utf-8":return Dt(this,e,t,r);case"ascii":return jt(this,e,t,r);case"latin1":case"binary":return Mt(this,e,t,r);case"base64":return Pt(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ft(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},_t.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var zt=4096;function $t(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function Ht(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function Vt(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var i="",o=t;o<r;++o)i+=rr(e[o]);return i}function Gt(e,t,r){for(var n=e.slice(t,r),i="",o=0;o<n.length;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function Kt(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function Wt(e,t,r,n,i,o){if(!Ot(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function Jt(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i<o;++i)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function Zt(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i<o;++i)e[r+i]=t>>>8*(n?i:3-i)&255}function Yt(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Xt(e,t,r,n,i){return i||Yt(e,0,r,4),wt(e,t,r,n,23,4),r+4}function er(e,t,r,n,i){return i||Yt(e,0,r,8),wt(e,t,r,n,52,8),r+8}_t.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e),_t.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=_t.prototype;else{var i=t-e;r=new _t(i,void 0);for(var o=0;o<i;++o)r[o]=this[o+e]}return r},_t.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||Kt(e,t,this.length);for(var n=this[e],i=1,o=0;++o<t&&(i*=256);)n+=this[e+o]*i;return n},_t.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||Kt(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},_t.prototype.readUInt8=function(e,t){return t||Kt(e,1,this.length),this[e]},_t.prototype.readUInt16LE=function(e,t){return t||Kt(e,2,this.length),this[e]|this[e+1]<<8},_t.prototype.readUInt16BE=function(e,t){return t||Kt(e,2,this.length),this[e]<<8|this[e+1]},_t.prototype.readUInt32LE=function(e,t){return t||Kt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},_t.prototype.readUInt32BE=function(e,t){return t||Kt(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},_t.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Kt(e,t,this.length);for(var n=this[e],i=1,o=0;++o<t&&(i*=256);)n+=this[e+o]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},_t.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Kt(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},_t.prototype.readInt8=function(e,t){return t||Kt(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},_t.prototype.readInt16LE=function(e,t){t||Kt(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},_t.prototype.readInt16BE=function(e,t){t||Kt(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},_t.prototype.readInt32LE=function(e,t){return t||Kt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},_t.prototype.readInt32BE=function(e,t){return t||Kt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},_t.prototype.readFloatLE=function(e,t){return t||Kt(e,4,this.length),yt(this,e,!0,23,4)},_t.prototype.readFloatBE=function(e,t){return t||Kt(e,4,this.length),yt(this,e,!1,23,4)},_t.prototype.readDoubleLE=function(e,t){return t||Kt(e,8,this.length),yt(this,e,!0,52,8)},_t.prototype.readDoubleBE=function(e,t){return t||Kt(e,8,this.length),yt(this,e,!1,52,8)},_t.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||Wt(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r},_t.prototype.writeUIntBE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||Wt(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},_t.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,1,255,0),_t.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},_t.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,2,65535,0),_t.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Jt(this,e,t,!0),t+2},_t.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,2,65535,0),_t.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Jt(this,e,t,!1),t+2},_t.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,4,4294967295,0),_t.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Zt(this,e,t,!0),t+4},_t.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,4,4294967295,0),_t.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Zt(this,e,t,!1),t+4},_t.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);Wt(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o<r&&(s*=256);)e<0&&0===a&&0!==this[t+o-1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},_t.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);Wt(this,e,t,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s|0)-a&255;return t+r},_t.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,1,127,-128),_t.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},_t.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,2,32767,-32768),_t.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Jt(this,e,t,!0),t+2},_t.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,2,32767,-32768),_t.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Jt(this,e,t,!1),t+2},_t.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,4,2147483647,-2147483648),_t.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Zt(this,e,t,!0),t+4},_t.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Wt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),_t.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Zt(this,e,t,!1),t+4},_t.prototype.writeFloatLE=function(e,t,r){return Xt(this,e,t,!0,r)},_t.prototype.writeFloatBE=function(e,t,r){return Xt(this,e,t,!1,r)},_t.prototype.writeDoubleLE=function(e,t,r){return er(this,e,t,!0,r)},_t.prototype.writeDoubleBE=function(e,t,r){return er(this,e,t,!1,r)},_t.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);var i,o=n-r;if(this===e&&r<t&&t<n)for(i=o-1;i>=0;--i)e[i+t]=this[i+r];else if(o<1e3||!_t.TYPED_ARRAY_SUPPORT)for(i=0;i<o;++i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+o),t);return o},_t.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===e.length){var i=e.charCodeAt(0);i<256&&(e=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!_t.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{var s=Ot(e)?e:nr(new _t(e,n).toString()),a=s.length;for(o=0;o<r-t;++o)this[o+t]=s[o%a]}return this};var tr=/[^+\/0-9A-Za-z-_]/g;function rr(e){return e<16?"0"+e.toString(16):e.toString(16)}function nr(e,t){var r;t=t||1/0;for(var n=e.length,i=null,o=[],s=0;s<n;++s){if((r=e.charCodeAt(s))>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ir(e){return function(e){var t,r,n,i,o,s;ft||dt();var a=e.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[a-2]?2:"="===e[a-1]?1:0,s=new ht(3*a/4-o),n=o>0?a-4:a;var c=0;for(t=0,r=0;t<n;t+=4,r+=3)i=lt[e.charCodeAt(t)]<<18|lt[e.charCodeAt(t+1)]<<12|lt[e.charCodeAt(t+2)]<<6|lt[e.charCodeAt(t+3)],s[c++]=i>>16&255,s[c++]=i>>8&255,s[c++]=255&i;return 2===o?(i=lt[e.charCodeAt(t)]<<2|lt[e.charCodeAt(t+1)]>>4,s[c++]=255&i):1===o&&(i=lt[e.charCodeAt(t)]<<10|lt[e.charCodeAt(t+1)]<<4|lt[e.charCodeAt(t+2)]>>2,s[c++]=i>>8&255,s[c++]=255&i),s}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(tr,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function or(e,t,r,n){for(var i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function sr(e){return null!=e&&(!!e._isBuffer||ar(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&ar(e.slice(0,0))}(e))}function ar(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function cr(){throw new Error("setTimeout has not been defined")}function ur(){throw new Error("clearTimeout has not been defined")}var lr=cr,hr=ur;function fr(e){if(lr===setTimeout)return setTimeout(e,0);if((lr===cr||!lr)&&setTimeout)return lr=setTimeout,setTimeout(e,0);try{return lr(e,0)}catch(t){try{return lr.call(null,e,0)}catch(t){return lr.call(this,e,0)}}}"function"==typeof ct.setTimeout&&(lr=setTimeout),"function"==typeof ct.clearTimeout&&(hr=clearTimeout);var dr,pr=[],gr=!1,mr=-1;function yr(){gr&&dr&&(gr=!1,dr.length?pr=dr.concat(pr):mr=-1,pr.length&&wr())}function wr(){if(!gr){var e=fr(yr);gr=!0;for(var t=pr.length;t;){for(dr=pr,pr=[];++mr<t;)dr&&dr[mr].run();mr=-1,t=pr.length}dr=null,gr=!1,function(e){if(hr===clearTimeout)return clearTimeout(e);if((hr===ur||!hr)&&clearTimeout)return hr=clearTimeout,clearTimeout(e);try{return hr(e)}catch(t){try{return hr.call(null,e)}catch(t){return hr.call(this,e)}}}(e)}}function br(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];pr.push(new vr(e,t)),1!==pr.length||gr||fr(wr)}function vr(e,t){this.fun=e,this.array=t}vr.prototype.run=function(){this.fun.apply(null,this.array)};function Er(){}var Ir=Er,_r=Er,Ar=Er,kr=Er,Br=Er,xr=Er,Sr=Er;var Or=ct.performance||{},Ur=Or.now||Or.mozNow||Or.msNow||Or.oNow||Or.webkitNow||function(){return(new Date).getTime()};var Cr=new Date;var Nr,Rr={nextTick:br,title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:Ir,addListener:_r,once:Ar,off:kr,removeListener:Br,removeAllListeners:xr,emit:Sr,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*Ur.call(Or),r=Math.floor(t),n=Math.floor(t%1*1e9);return e&&(r-=e[0],(n-=e[1])<0&&(r--,n+=1e9)),[r,n]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-Cr)/1e3}};Nr="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e};var Tr=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n<t.length;n++)r[t[n]]=Object.getOwnPropertyDescriptor(e,t[n]);return r},Lr=/%[sdj%]/g;function Dr(e){if(!Yr(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(qr(arguments[r]));return t.join(" ")}r=1;for(var n=arguments,i=n.length,o=String(e).replace(Lr,function(e){if("%%"===e)return"%";if(r>=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),s=n[r];r<i;s=n[++r])Wr(s)||!rn(s)?o+=" "+s:o+=" "+qr(s);return o}function jr(e,t){if(en(ct.process))return function(){return jr(e,t).apply(this,arguments)};if(!0===Rr.noDeprecation)return e;var r=!1;return function(){if(!r){if(Rr.throwDeprecation)throw new Error(t);Rr.traceDeprecation?console.trace(t):console.error(t),r=!0}return e.apply(this,arguments)}}var Mr,Pr={};function Fr(e){if(en(Mr)&&(Mr=Rr.env.NODE_DEBUG||""),e=e.toUpperCase(),!Pr[e])if(new RegExp("\\b"+e+"\\b","i").test(Mr)){Pr[e]=function(){var t=Dr.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else Pr[e]=function(){};return Pr[e]}function qr(e,t){var r={seen:[],stylize:zr};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),Kr(t)?r.showHidden=t:t&&dn(r,t),en(r.showHidden)&&(r.showHidden=!1),en(r.depth)&&(r.depth=2),en(r.colors)&&(r.colors=!1),en(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Qr),$r(r,e,r.depth)}function Qr(e,t){var r=qr.styles[t];return r?"["+qr.colors[r][0]+"m"+e+"["+qr.colors[r][1]+"m":e}function zr(e,t){return e}function $r(e,t,r){if(e.customInspect&&t&&sn(t.inspect)&&t.inspect!==qr&&(!t.constructor||t.constructor.prototype!==t)){var n=t.inspect(r,e);return Yr(n)||(n=$r(e,n,r)),n}var i=function(e,t){if(en(t))return e.stylize("undefined","undefined");if(Yr(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(Zr(t))return e.stylize(""+t,"number");if(Kr(t))return e.stylize(""+t,"boolean");if(Wr(t))return e.stylize("null","null")}(e,t);if(i)return i;var o=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),on(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Hr(t);if(0===o.length){if(sn(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(tn(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(nn(t))return e.stylize(Date.prototype.toString.call(t),"date");if(on(t))return Hr(t)}var c,u="",l=!1,h=["{","}"];(Gr(t)&&(l=!0,h=["[","]"]),sn(t))&&(u=" [Function"+(t.name?": "+t.name:"")+"]");return tn(t)&&(u=" "+RegExp.prototype.toString.call(t)),nn(t)&&(u=" "+Date.prototype.toUTCString.call(t)),on(t)&&(u=" "+Hr(t)),0!==o.length||l&&0!=t.length?r<0?tn(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=l?function(e,t,r,n,i){for(var o=[],s=0,a=t.length;s<a;++s)pn(t,String(s))?o.push(Vr(e,t,r,n,String(s),!0)):o.push("");return i.forEach(function(i){i.match(/^\d+$/)||o.push(Vr(e,t,r,n,i,!0))}),o}(e,t,r,s,o):o.map(function(n){return Vr(e,t,r,s,n,l)}),e.seen.pop(),function(e,t,r){var n=e.reduce(function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(n>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,u,h)):h[0]+u+h[1]}function Hr(e){return"["+Error.prototype.toString.call(e)+"]"}function Vr(e,t,r,n,i,o){var s,a,c;if((c=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),pn(n,i)||(s="["+i+"]"),a||(e.seen.indexOf(c.value)<0?(a=Wr(r)?$r(e,c.value,null):$r(e,c.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n")):a=e.stylize("[Circular]","special")),en(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function Gr(e){return Array.isArray(e)}function Kr(e){return"boolean"==typeof e}function Wr(e){return null===e}function Jr(e){return null==e}function Zr(e){return"number"==typeof e}function Yr(e){return"string"==typeof e}function Xr(e){return"symbol"==typeof e}function en(e){return void 0===e}function tn(e){return rn(e)&&"[object RegExp]"===un(e)}function rn(e){return"object"==typeof e&&null!==e}function nn(e){return rn(e)&&"[object Date]"===un(e)}function on(e){return rn(e)&&("[object Error]"===un(e)||e instanceof Error)}function sn(e){return"function"==typeof e}function an(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e}function cn(e){return _t.isBuffer(e)}function un(e){return Object.prototype.toString.call(e)}function ln(e){return e<10?"0"+e.toString(10):e.toString(10)}qr.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]},qr.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};var hn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function fn(){var e,t;console.log("%s - %s",(e=new Date,t=[ln(e.getHours()),ln(e.getMinutes()),ln(e.getSeconds())].join(":"),[e.getDate(),hn[e.getMonth()],t].join(" ")),Dr.apply(null,arguments))}function dn(e,t){if(!t||!rn(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}function pn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var gn="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function mn(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(gn&&e[gn]){var t;if("function"!=typeof(t=e[gn]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,gn,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,r,n=new Promise(function(e,n){t=e,r=n}),i=[],o=0;o<arguments.length;o++)i.push(arguments[o]);i.push(function(e,n){e?r(e):t(n)});try{e.apply(this,i)}catch(e){r(e)}return n}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),gn&&Object.defineProperty(t,gn,{value:t,enumerable:!1,writable:!1,configurable:!0}),Object.defineProperties(t,Tr(e))}function yn(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}function wn(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');function t(){for(var t=[],r=0;r<arguments.length;r++)t.push(arguments[r]);var n=t.pop();if("function"!=typeof n)throw new TypeError("The last argument must be of type Function");var i=this,o=function(){return n.apply(i,arguments)};e.apply(this,t).then(function(e){Rr.nextTick(o.bind(null,null,e))},function(e){Rr.nextTick(yn.bind(null,e,o))})}return Object.setPrototypeOf(t,Object.getPrototypeOf(e)),Object.defineProperties(t,Tr(e)),t}mn.custom=gn;var bn={inherits:Nr,_extend:dn,log:fn,isBuffer:cn,isPrimitive:an,isFunction:sn,isError:on,isDate:nn,isObject:rn,isRegExp:tn,isUndefined:en,isSymbol:Xr,isString:Yr,isNumber:Zr,isNullOrUndefined:Jr,isNull:Wr,isBoolean:Kr,isArray:Gr,inspect:qr,deprecate:jr,format:Dr,debuglog:Fr,promisify:mn,callbackify:wn},vn=Object.freeze({__proto__:null,_extend:dn,callbackify:wn,debuglog:Fr,default:bn,deprecate:jr,format:Dr,inherits:Nr,inspect:qr,isArray:Gr,isBoolean:Kr,isBuffer:cn,isDate:nn,isError:on,isFunction:sn,isNull:Wr,isNullOrUndefined:Jr,isNumber:Zr,isObject:rn,isPrimitive:an,isRegExp:tn,isString:Yr,isSymbol:Xr,isUndefined:en,log:fn,promisify:mn});function En(){this.head=null,this.tail=null,this.length=0}En.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},En.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},En.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},En.prototype.clear=function(){this.head=this.tail=null,this.length=0},En.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},En.prototype.concat=function(e){if(0===this.length)return _t.alloc(0);if(1===this.length)return this.head.data;for(var t=_t.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var In=_t.isEncoding||function(e){switch(e&&e.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 _n(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!In(e))throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=kn;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Bn;break;default:return void(this.write=An)}this.charBuffer=new _t(6),this.charReceived=0,this.charLength=0}function An(e){return e.toString(this.encoding)}function kn(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Bn(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}_n.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";if(e=e.slice(r,e.length),!((i=(t=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(t.length-1))>=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var n=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,n),n-=this.charReceived);var i;n=(t+=e.toString(this.encoding,0,n)).length-1;if((i=t.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,n)}return t},_n.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},_n.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t},On.ReadableState=Sn;var xn=Fr("stream");function Sn(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof ni&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new En,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=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new _n(e.encoding),this.encoding=e.encoding)}function On(e){if(!(this instanceof On))return new On(e);this._readableState=new Sn(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Qe.call(this)}function Un(e,t,r,n,i){var o=function(e,t){var r=null;_t.isBuffer(t)||"string"==typeof t||null==t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(t,r);if(o)e.emit("error",o);else if(null===r)t.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,Rn(e)}(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var s=new Error("stream.push() after EOF");e.emit("error",s)}else if(t.endEmitted&&i){var a=new Error("stream.unshift() after end event");e.emit("error",a)}else{var c;!t.decoder||i||n||(r=t.decoder.write(r),c=!t.objectMode&&0===r.length),i||(t.reading=!1),c||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&Rn(e))),function(e,t){t.readingMore||(t.readingMore=!0,br(Ln,e,t))}(e,t)}else i||(t.reading=!1);return function(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}(t)}Nr(On,Qe),On.prototype.push=function(e,t){var r=this._readableState;return r.objectMode||"string"!=typeof e||(t=t||r.defaultEncoding)!==r.encoding&&(e=_t.from(e,t),t=""),Un(this,r,e,t,!1)},On.prototype.unshift=function(e){return Un(this,this._readableState,e,"",!0)},On.prototype.isPaused=function(){return!1===this._readableState.flowing},On.prototype.setEncoding=function(e){return this._readableState.decoder=new _n(e),this._readableState.encoding=e,this};var Cn=8388608;function Nn(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=Cn?e=Cn:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function Rn(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(xn("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?br(Tn,e):Tn(e))}function Tn(e){xn("emit readable"),e.emit("readable"),Mn(e)}function Ln(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(xn("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=!1}function Dn(e){xn("readable nexttick read 0"),e.read(0)}function jn(e,t){t.reading||(xn("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),Mn(e),t.flowing&&!t.reading&&e.read(0)}function Mn(e){var t=e._readableState;for(xn("flow",t.flowing);t.flowing&&null!==e.read(););}function Pn(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;e<t.head.data.length?(n=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):n=e===t.head.data.length?t.shift():r?function(e,t){var r=t.head,n=1,i=r.data;e-=i.length;for(;r=r.next;){var o=r.data,s=e>o.length?o.length:e;if(s===o.length?i+=o:i+=o.slice(0,e),0===(e-=s)){s===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(s));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=_t.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,s=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,s),0===(e-=s)){s===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(s));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function Fn(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,br(qn,t,e))}function qn(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function Qn(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return-1}function zn(){}function $n(e,t,r){this.chunk=e,this.encoding=t,this.callback=r,this.next=null}function Hn(e,t){Object.defineProperty(this,"buffer",{get:jr(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),e=e||{},this.objectMode=!!e.objectMode,t instanceof ni&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var i=!1===e.decodeStrings;this.decodeStrings=!i,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,i){--t.pendingcb,r?br(i,n):i(n);e._writableState.errorEmitted=!0,e.emit("error",n)}(e,r,n,t,i);else{var o=Jn(r);o||r.corked||r.bufferProcessing||!r.bufferedRequest||Wn(e,r),n?br(Kn,e,r,o,i):Kn(e,r,o,i)}}(t,e)},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 Xn(this)}function Vn(e){if(!(this instanceof Vn||this instanceof ni))return new Vn(e);this._writableState=new Hn(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev)),Qe.call(this)}function Gn(e,t,r,n,i,o,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function Kn(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),Yn(e,t)}function Wn(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var s=0;r;)i[s]=r,r=r.next,s+=1;Gn(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new Xn(t)}else{for(;r;){var a=r.chunk,c=r.encoding,u=r.callback;if(Gn(e,t,!1,t.objectMode?1:a.length,a,c,u),r=r.next,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequestCount=0,t.bufferedRequest=r,t.bufferProcessing=!1}function Jn(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function Zn(e,t){t.prefinished||(t.prefinished=!0,e.emit("prefinish"))}function Yn(e,t){var r=Jn(t);return r&&(0===t.pendingcb?(Zn(e,t),t.finished=!0,e.emit("finish")):Zn(e,t)),r}function Xn(e){var t=this;this.next=null,this.entry=null,this.finish=function(r){var n=t.entry;for(t.entry=null;n;){var i=n.callback;e.pendingcb--,i(r),n=n.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}}On.prototype.read=function(e){xn("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return xn("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?Fn(this):Rn(this),null;if(0===(e=Nn(e,t))&&t.ended)return 0===t.length&&Fn(this),null;var n,i=t.needReadable;return xn("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&xn("length less than watermark",i=!0),t.ended||t.reading?xn("reading or ended",i=!1):i&&(xn("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=Nn(r,t))),null===(n=e>0?Pn(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&Fn(this)),null!==n&&this.emit("data",n),n},On.prototype._read=function(e){this.emit("error",new Error("not implemented"))},On.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,xn("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||!1!==t.end?s:u;function o(e){xn("onunpipe"),e===r&&u()}function s(){xn("onend"),e.end()}n.endEmitted?br(i):r.once("end",i),e.on("unpipe",o);var a=function(e){return function(){var t=e._readableState;xn("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,Mn(e))}}(r);e.on("drain",a);var c=!1;function u(){xn("cleanup"),e.removeListener("close",d),e.removeListener("finish",p),e.removeListener("drain",a),e.removeListener("error",f),e.removeListener("unpipe",o),r.removeListener("end",s),r.removeListener("end",u),r.removeListener("data",h),c=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||a()}var l=!1;function h(t){xn("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==Qn(n.pipes,e))&&!c&&(xn("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function f(t){xn("onerror",t),g(),e.removeListener("error",f),0===function(e,t){return e.listeners(t).length}(e,"error")&&e.emit("error",t)}function d(){e.removeListener("finish",p),g()}function p(){xn("onfinish"),e.removeListener("close",d),g()}function g(){xn("unpipe"),r.unpipe(e)}return r.on("data",h),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",f),e.once("close",d),e.once("finish",p),e.emit("pipe",r),n.flowing||(xn("pipe resume"),r.resume()),e},On.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this)),this;if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i<n;i++)r[i].emit("unpipe",this);return this}var o=Qn(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this)),this},On.prototype.on=function(e,t){var r=Qe.prototype.on.call(this,e,t);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var n=this._readableState;n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.emittedReadable=!1,n.reading?n.length&&Rn(this):br(Dn,this))}return r},On.prototype.addListener=On.prototype.on,On.prototype.resume=function(){var e=this._readableState;return e.flowing||(xn("resume"),e.flowing=!0,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,br(jn,e,t))}(this,e)),this},On.prototype.pause=function(){return xn("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(xn("pause"),this._readableState.flowing=!1,this.emit("pause")),this},On.prototype.wrap=function(e){var t=this._readableState,r=!1,n=this;for(var i in e.on("end",function(){if(xn("wrapped end"),t.decoder&&!t.ended){var e=t.decoder.end();e&&e.length&&n.push(e)}n.push(null)}),e.on("data",function(i){(xn("wrapped data"),t.decoder&&(i=t.decoder.write(i)),t.objectMode&&null==i)||(t.objectMode||i&&i.length)&&(n.push(i)||(r=!0,e.pause()))}),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));return function(e,t){for(var r=0,n=e.length;r<n;r++)t(e[r],r)}(["error","close","destroy","pause","resume"],function(t){e.on(t,n.emit.bind(n,t))}),n._read=function(t){xn("wrapped _read",t),r&&(r=!1,e.resume())},n},On._fromList=Pn,Vn.WritableState=Hn,Nr(Vn,Qe),Hn.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},Vn.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},Vn.prototype.write=function(e,t,r){var n=this._writableState,i=!1;return"function"==typeof t&&(r=t,t=null),_t.isBuffer(e)?t="buffer":t||(t=n.defaultEncoding),"function"!=typeof r&&(r=zn),n.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),br(t,r)}(this,r):function(e,t,r,n){var i=!0,o=!1;return null===r?o=new TypeError("May not write null values to stream"):_t.isBuffer(r)||"string"==typeof r||void 0===r||t.objectMode||(o=new TypeError("Invalid non-string/buffer chunk")),o&&(e.emit("error",o),br(n,o),i=!1),i}(this,n,e,r)&&(n.pendingcb++,i=function(e,t,r,n,i){r=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=_t.from(t,r));return t}(t,r,n),_t.isBuffer(r)&&(n="buffer");var o=t.objectMode?1:r.length;t.length+=o;var s=t.length<t.highWaterMark;s||(t.needDrain=!0);if(t.writing||t.corked){var a=t.lastBufferedRequest;t.lastBufferedRequest=new $n(r,n,i),a?a.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else Gn(e,t,!1,o,r,n,i);return s}(this,n,e,t,r)),i},Vn.prototype.cork=function(){this._writableState.corked++},Vn.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||Wn(this,e))},Vn.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Vn.prototype._write=function(e,t,r){r(new Error("not implemented"))},Vn.prototype._writev=null,Vn.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,Yn(e,t),r&&(t.finished?br(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Nr(ni,On);for(var ei=Object.keys(Vn.prototype),ti=0;ti<ei.length;ti++){var ri=ei[ti];ni.prototype[ri]||(ni.prototype[ri]=Vn.prototype[ri])}function ni(e){if(!(this instanceof ni))return new ni(e);On.call(this,e),Vn.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",ii)}function ii(){this.allowHalfOpen||this._writableState.ended||br(oi,this)}function oi(e){e.end()}function si(e){this.afterTransform=function(t,r){return function(e,t,r){var n=e._transformState;n.transforming=!1;var i=n.writecb;if(!i)return e.emit("error",new Error("no writecb in Transform class"));n.writechunk=null,n.writecb=null,null!=r&&e.push(r);i(t);var o=e._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&e._read(o.highWaterMark)}(e,t,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function ai(e){if(!(this instanceof ai))return new ai(e);ni.call(this,e),this._transformState=new si(this);var t=this;this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(e){ci(t,e)}):ci(t)})}function ci(e,t){if(t)return e.emit("error",t);var r=e._writableState,n=e._transformState;if(r.length)throw new Error("Calling transform done when ws.length != 0");if(n.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}function ui(e){if(!(this instanceof ui))return new ui(e);ai.call(this,e)}function li(){Qe.call(this)}Nr(ai,ni),ai.prototype.push=function(e,t){return this._transformState.needTransform=!1,ni.prototype.push.call(this,e,t)},ai.prototype._transform=function(e,t,r){throw new Error("Not implemented")},ai.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},ai.prototype._read=function(e){var t=this._transformState;null!==t.writechunk&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},Nr(ui,ai),ui.prototype._transform=function(e,t,r){r(null,e)},Nr(li,Qe),li.Readable=On,li.Writable=Vn,li.Duplex=ni,li.Transform=ai,li.PassThrough=ui,li.Stream=li,li.prototype.pipe=function(e,t){var r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",a));var o=!1;function s(){o||(o=!0,e.end())}function a(){o||(o=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(u(),0===Qe.listenerCount(this,"error"))throw e}function u(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",s),r.removeListener("close",a),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",u),r.removeListener("close",u),e.removeListener("close",u)}return r.on("error",c),e.on("error",c),r.on("end",u),r.on("close",u),e.on("close",u),e.emit("pipe",r),e};var hi=Object.freeze({__proto__:null,Duplex:ni,PassThrough:ui,Readable:On,Stream:li,Transform:ai,Writable:Vn,default:li}),fi={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};function di(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}function pi(e,t,r,n,i){if(t.subarray&&e.subarray)e.set(t.subarray(r,r+n),i);else for(var o=0;o<n;o++)e[i+o]=t[r+o]}var gi=Uint8Array,mi=Uint16Array,yi=Int32Array;function wi(e){for(var t=e.length;--t>=0;)e[t]=0}var bi=256,vi=286,Ei=30,Ii=15,_i=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Ai=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],ki=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],Bi=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],xi=new Array(576);wi(xi);var Si=new Array(60);wi(Si);var Oi=new Array(512);wi(Oi);var Ui=new Array(256);wi(Ui);var Ci=new Array(29);wi(Ci);var Ni,Ri,Ti,Li=new Array(Ei);function Di(e,t,r,n,i){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=e&&e.length}function ji(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Mi(e){return e<256?Oi[e]:Oi[256+(e>>>7)]}function Pi(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function Fi(e,t,r){e.bi_valid>16-r?(e.bi_buf|=t<<e.bi_valid&65535,Pi(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=r-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r)}function qi(e,t,r){Fi(e,r[2*t],r[2*t+1])}function Qi(e,t){var r=0;do{r|=1&e,e>>>=1,r<<=1}while(--t>0);return r>>>1}function zi(e,t,r){var n,i,o=new Array(16),s=0;for(n=1;n<=Ii;n++)o[n]=s=s+r[n-1]<<1;for(i=0;i<=t;i++){var a=e[2*i+1];0!==a&&(e[2*i]=Qi(o[a]++,a))}}function $i(e){var t;for(t=0;t<vi;t++)e.dyn_ltree[2*t]=0;for(t=0;t<Ei;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function Hi(e){e.bi_valid>8?Pi(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function Vi(e,t,r,n){var i=2*t,o=2*r;return e[i]<e[o]||e[i]===e[o]&&n[t]<=n[r]}function Gi(e,t,r){for(var n=e.heap[r],i=r<<1;i<=e.heap_len&&(i<e.heap_len&&Vi(t,e.heap[i+1],e.heap[i],e.depth)&&i++,!Vi(t,n,e.heap[i],e.depth));)e.heap[r]=e.heap[i],r=i,i<<=1;e.heap[r]=n}function Ki(e,t,r){var n,i,o,s,a=0;if(0!==e.last_lit)do{n=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],i=e.pending_buf[e.l_buf+a],a++,0===n?qi(e,i,t):(qi(e,(o=Ui[i])+bi+1,t),0!==(s=_i[o])&&Fi(e,i-=Ci[o],s),qi(e,o=Mi(--n),r),0!==(s=Ai[o])&&Fi(e,n-=Li[o],s))}while(a<e.last_lit);qi(e,256,t)}function Wi(e,t){var r,n,i,o=t.dyn_tree,s=t.stat_desc.static_tree,a=t.stat_desc.has_stree,c=t.stat_desc.elems,u=-1;for(e.heap_len=0,e.heap_max=573,r=0;r<c;r++)0!==o[2*r]?(e.heap[++e.heap_len]=u=r,e.depth[r]=0):o[2*r+1]=0;for(;e.heap_len<2;)o[2*(i=e.heap[++e.heap_len]=u<2?++u:0)]=1,e.depth[i]=0,e.opt_len--,a&&(e.static_len-=s[2*i+1]);for(t.max_code=u,r=e.heap_len>>1;r>=1;r--)Gi(e,o,r);i=c;do{r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Gi(e,o,1),n=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=n,o[2*i]=o[2*r]+o[2*n],e.depth[i]=(e.depth[r]>=e.depth[n]?e.depth[r]:e.depth[n])+1,o[2*r+1]=o[2*n+1]=i,e.heap[1]=i++,Gi(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,n,i,o,s,a,c=t.dyn_tree,u=t.max_code,l=t.stat_desc.static_tree,h=t.stat_desc.has_stree,f=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,p=t.stat_desc.max_length,g=0;for(o=0;o<=Ii;o++)e.bl_count[o]=0;for(c[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r<573;r++)(o=c[2*c[2*(n=e.heap[r])+1]+1]+1)>p&&(o=p,g++),c[2*n+1]=o,n>u||(e.bl_count[o]++,s=0,n>=d&&(s=f[n-d]),a=c[2*n],e.opt_len+=a*(o+s),h&&(e.static_len+=a*(l[2*n+1]+s)));if(0!==g){do{for(o=p-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[p]--,g-=2}while(g>0);for(o=p;0!==o;o--)for(n=e.bl_count[o];0!==n;)(i=e.heap[--r])>u||(c[2*i+1]!==o&&(e.opt_len+=(o-c[2*i+1])*c[2*i],c[2*i+1]=o),n--)}}(e,t),zi(o,u,e.bl_count)}function Ji(e,t,r){var n,i,o=-1,s=t[1],a=0,c=7,u=4;for(0===s&&(c=138,u=3),t[2*(r+1)+1]=65535,n=0;n<=r;n++)i=s,s=t[2*(n+1)+1],++a<c&&i===s||(a<u?e.bl_tree[2*i]+=a:0!==i?(i!==o&&e.bl_tree[2*i]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,o=i,0===s?(c=138,u=3):i===s?(c=6,u=3):(c=7,u=4))}function Zi(e,t,r){var n,i,o=-1,s=t[1],a=0,c=7,u=4;for(0===s&&(c=138,u=3),n=0;n<=r;n++)if(i=s,s=t[2*(n+1)+1],!(++a<c&&i===s)){if(a<u)do{qi(e,i,e.bl_tree)}while(0!==--a);else 0!==i?(i!==o&&(qi(e,i,e.bl_tree),a--),qi(e,16,e.bl_tree),Fi(e,a-3,2)):a<=10?(qi(e,17,e.bl_tree),Fi(e,a-3,3)):(qi(e,18,e.bl_tree),Fi(e,a-11,7));a=0,o=i,0===s?(c=138,u=3):i===s?(c=6,u=3):(c=7,u=4)}}wi(Li);var Yi=!1;function Xi(e){Yi||(!function(){var e,t,r,n,i,o=new Array(16);for(r=0,n=0;n<28;n++)for(Ci[n]=r,e=0;e<1<<_i[n];e++)Ui[r++]=n;for(Ui[r-1]=n,i=0,n=0;n<16;n++)for(Li[n]=i,e=0;e<1<<Ai[n];e++)Oi[i++]=n;for(i>>=7;n<Ei;n++)for(Li[n]=i<<7,e=0;e<1<<Ai[n]-7;e++)Oi[256+i++]=n;for(t=0;t<=Ii;t++)o[t]=0;for(e=0;e<=143;)xi[2*e+1]=8,e++,o[8]++;for(;e<=255;)xi[2*e+1]=9,e++,o[9]++;for(;e<=279;)xi[2*e+1]=7,e++,o[7]++;for(;e<=287;)xi[2*e+1]=8,e++,o[8]++;for(zi(xi,287,o),e=0;e<Ei;e++)Si[2*e+1]=5,Si[2*e]=Qi(e,5);Ni=new Di(xi,_i,257,vi,Ii),Ri=new Di(Si,Ai,0,Ei,Ii),Ti=new Di(new Array(0),ki,0,19,7)}(),Yi=!0),e.l_desc=new ji(e.dyn_ltree,Ni),e.d_desc=new ji(e.dyn_dtree,Ri),e.bl_desc=new ji(e.bl_tree,Ti),e.bi_buf=0,e.bi_valid=0,$i(e)}function eo(e,t,r,n){Fi(e,0+(n?1:0),3),function(e,t,r){Hi(e),Pi(e,r),Pi(e,~r),pi(e.pending_buf,e.window,t,r,e.pending),e.pending+=r}(e,t,r)}function to(e){Fi(e,2,3),qi(e,256,xi),function(e){16===e.bi_valid?(Pi(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}function ro(e,t,r,n){var i,o,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<bi;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),Wi(e,e.l_desc),Wi(e,e.d_desc),s=function(e){var t;for(Ji(e,e.dyn_ltree,e.l_desc.max_code),Ji(e,e.dyn_dtree,e.d_desc.max_code),Wi(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*Bi[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),i=e.opt_len+3+7>>>3,(o=e.static_len+3+7>>>3)<=i&&(i=o)):i=o=r+5,r+4<=i&&-1!==t?eo(e,t,r,n):4===e.strategy||o===i?(Fi(e,2+(n?1:0),3),Ki(e,xi,Si)):(Fi(e,4+(n?1:0),3),function(e,t,r,n){var i;for(Fi(e,t-257,5),Fi(e,r-1,5),Fi(e,n-4,4),i=0;i<n;i++)Fi(e,e.bl_tree[2*Bi[i]+1],3);Zi(e,e.dyn_ltree,t-1),Zi(e,e.dyn_dtree,r-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),Ki(e,e.dyn_ltree,e.dyn_dtree)),$i(e),n&&Hi(e)}function no(e,t,r){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(Ui[r]+bi+1)]++,e.dyn_dtree[2*Mi(t)]++),e.last_lit===e.lit_bufsize-1}function io(e,t,r,n){for(var i=65535&e,o=e>>>16&65535,s=0;0!==r;){r-=s=r>2e3?2e3:r;do{o=o+(i=i+t[n++]|0)|0}while(--s);i%=65521,o%=65521}return i|o<<16}var oo=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();function so(e,t,r,n){var i=oo,o=n+r;e^=-1;for(var s=n;s<o;s++)e=e>>>8^i[255&(e^t[s])];return-1^e}var ao,co=-2,uo=258,lo=262,ho=103,fo=113,po=666;function go(e,t){return e.msg=fi[t],t}function mo(e){return(e<<1)-(e>4?9:0)}function yo(e){for(var t=e.length;--t>=0;)e[t]=0}function wo(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(pi(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function bo(e,t){ro(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,wo(e.strm)}function vo(e,t){e.pending_buf[e.pending++]=t}function Eo(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function Io(e,t,r,n){var i=e.avail_in;return i>n&&(i=n),0===i?0:(e.avail_in-=i,pi(t,e.input,e.next_in,i,r),1===e.state.wrap?e.adler=io(e.adler,t,i,r):2===e.state.wrap&&(e.adler=so(e.adler,t,i,r)),e.next_in+=i,e.total_in+=i,i)}function _o(e,t){var r,n,i=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match,c=e.strstart>e.w_size-lo?e.strstart-(e.w_size-lo):0,u=e.window,l=e.w_mask,h=e.prev,f=e.strstart+uo,d=u[o+s-1],p=u[o+s];e.prev_length>=e.good_match&&(i>>=2),a>e.lookahead&&(a=e.lookahead);do{if(u[(r=t)+s]===p&&u[r+s-1]===d&&u[r]===u[o]&&u[++r]===u[o+1]){o+=2,r++;do{}while(u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&u[++o]===u[++r]&&o<f);if(n=uo-(f-o),o=f-uo,n>s){if(e.match_start=t,s=n,n>=a)break;d=u[o+s-1],p=u[o+s]}}}while((t=h[t&l])>c&&0!==--i);return s<=e.lookahead?s:e.lookahead}function Ao(e){var t,r,n,i,o,s=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=s+(s-lo)){pi(e.window,e.window,s,s,0),e.match_start-=s,e.strstart-=s,e.block_start-=s,t=r=e.hash_size;do{n=e.head[--t],e.head[t]=n>=s?n-s:0}while(--r);t=r=s;do{n=e.prev[--t],e.prev[t]=n>=s?n-s:0}while(--r);i+=s}if(0===e.strm.avail_in)break;if(r=Io(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=r,e.lookahead+e.insert>=3)for(o=e.strstart-e.insert,e.ins_h=e.window[o],e.ins_h=(e.ins_h<<e.hash_shift^e.window[o+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[o+3-1])&e.hash_mask,e.prev[o&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=o,o++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<lo&&0!==e.strm.avail_in)}function ko(e,t){for(var r,n;;){if(e.lookahead<lo){if(Ao(e),e.lookahead<lo&&0===t)return 1;if(0===e.lookahead)break}if(r=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==r&&e.strstart-r<=e.w_size-lo&&(e.match_length=_o(e,r)),e.match_length>=3)if(n=no(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=no(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(bo(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,4===t?(bo(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(bo(e,!1),0===e.strm.avail_out)?1:2}function Bo(e,t){for(var r,n,i;;){if(e.lookahead<lo){if(Ao(e),e.lookahead<lo&&0===t)return 1;if(0===e.lookahead)break}if(r=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==r&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-lo&&(e.match_length=_o(e,r),e.match_length<=5&&(1===e.strategy||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-3,n=no(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=i&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,n&&(bo(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((n=no(e,0,e.window[e.strstart-1]))&&bo(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=no(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,4===t?(bo(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(bo(e,!1),0===e.strm.avail_out)?1:2}function xo(e,t,r,n,i){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=n,this.func=i}function So(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new mi(1146),this.dyn_dtree=new mi(122),this.bl_tree=new mi(78),yo(this.dyn_ltree),yo(this.dyn_dtree),yo(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new mi(16),this.heap=new mi(573),yo(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new mi(573),yo(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Oo(e){var t,r=function(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=2,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:fo,e.adler=2===t.wrap?0:1,t.last_flush=0,Xi(t),0):go(e,co)}(e);return 0===r&&((t=e.state).window_size=2*t.w_size,yo(t.head),t.max_lazy_match=ao[t.level].max_lazy,t.good_match=ao[t.level].good_length,t.nice_match=ao[t.level].nice_length,t.max_chain_length=ao[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),r}function Uo(e,t){var r,n,i,o;if(!e||!e.state||t>5||t<0)return e?go(e,co):co;if(n=e.state,!e.output||!e.input&&0!==e.avail_in||n.status===po&&4!==t)return go(e,0===e.avail_out?-5:co);if(n.strm=e,r=n.last_flush,n.last_flush=t,42===n.status)if(2===n.wrap)e.adler=0,vo(n,31),vo(n,139),vo(n,8),n.gzhead?(vo(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),vo(n,255&n.gzhead.time),vo(n,n.gzhead.time>>8&255),vo(n,n.gzhead.time>>16&255),vo(n,n.gzhead.time>>24&255),vo(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),vo(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(vo(n,255&n.gzhead.extra.length),vo(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=so(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(vo(n,0),vo(n,0),vo(n,0),vo(n,0),vo(n,0),vo(n,9===n.level?2:n.strategy>=2||n.level<2?4:0),vo(n,3),n.status=fo);else{var s=8+(n.w_bits-8<<4)<<8;s|=(n.strategy>=2||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(s|=32),s+=31-s%31,n.status=fo,Eo(n,s),0!==n.strstart&&(Eo(n,e.adler>>>16),Eo(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>i&&(e.adler=so(e.adler,n.pending_buf,n.pending-i,i)),wo(e),i=n.pending,n.pending!==n.pending_buf_size));)vo(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(e.adler=so(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=so(e.adler,n.pending_buf,n.pending-i,i)),wo(e),i=n.pending,n.pending===n.pending_buf_size)){o=1;break}o=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,vo(n,o)}while(0!==o);n.gzhead.hcrc&&n.pending>i&&(e.adler=so(e.adler,n.pending_buf,n.pending-i,i)),0===o&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=so(e.adler,n.pending_buf,n.pending-i,i)),wo(e),i=n.pending,n.pending===n.pending_buf_size)){o=1;break}o=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,vo(n,o)}while(0!==o);n.gzhead.hcrc&&n.pending>i&&(e.adler=so(e.adler,n.pending_buf,n.pending-i,i)),0===o&&(n.status=ho)}else n.status=ho;if(n.status===ho&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&wo(e),n.pending+2<=n.pending_buf_size&&(vo(n,255&e.adler),vo(n,e.adler>>8&255),e.adler=0,n.status=fo)):n.status=fo),0!==n.pending){if(wo(e),0===e.avail_out)return n.last_flush=-1,0}else if(0===e.avail_in&&mo(t)<=mo(r)&&4!==t)return go(e,-5);if(n.status===po&&0!==e.avail_in)return go(e,-5);if(0!==e.avail_in||0!==n.lookahead||0!==t&&n.status!==po){var a=2===n.strategy?function(e,t){for(var r;;){if(0===e.lookahead&&(Ao(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,r=no(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(bo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(bo(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(bo(e,!1),0===e.strm.avail_out)?1:2}(n,t):3===n.strategy?function(e,t){for(var r,n,i,o,s=e.window;;){if(e.lookahead<=uo){if(Ao(e),e.lookahead<=uo&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(n=s[i=e.strstart-1])===s[++i]&&n===s[++i]&&n===s[++i]){o=e.strstart+uo;do{}while(n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&i<o);e.match_length=uo-(o-i),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(r=no(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=no(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(bo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(bo(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(bo(e,!1),0===e.strm.avail_out)?1:2}(n,t):ao[n.level].func(n,t);if(3!==a&&4!==a||(n.status=po),1===a||3===a)return 0===e.avail_out&&(n.last_flush=-1),0;if(2===a&&(1===t?to(n):5!==t&&(eo(n,0,0,!1),3===t&&(yo(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),wo(e),0===e.avail_out))return n.last_flush=-1,0}return 4!==t?0:n.wrap<=0?1:(2===n.wrap?(vo(n,255&e.adler),vo(n,e.adler>>8&255),vo(n,e.adler>>16&255),vo(n,e.adler>>24&255),vo(n,255&e.total_in),vo(n,e.total_in>>8&255),vo(n,e.total_in>>16&255),vo(n,e.total_in>>24&255)):(Eo(n,e.adler>>>16),Eo(n,65535&e.adler)),wo(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?0:1)}ao=[new xo(0,0,0,0,function(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Ao(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,bo(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-lo&&(bo(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(bo(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(bo(e,!1),e.strm.avail_out),1)}),new xo(4,4,8,4,ko),new xo(4,5,16,8,ko),new xo(4,6,32,32,ko),new xo(4,4,16,16,Bo),new xo(8,16,32,32,Bo),new xo(8,16,128,128,Bo),new xo(8,32,128,256,Bo),new xo(32,128,258,1024,Bo),new xo(32,258,258,4096,Bo)];function Co(e,t){var r,n,i,o,s,a,c,u,l,h,f,d,p,g,m,y,w,b,v,E,I,_,A,k,B;r=e.state,n=e.next_in,k=e.input,i=n+(e.avail_in-5),o=e.next_out,B=e.output,s=o-(t-e.avail_out),a=o+(e.avail_out-257),c=r.dmax,u=r.wsize,l=r.whave,h=r.wnext,f=r.window,d=r.hold,p=r.bits,g=r.lencode,m=r.distcode,y=(1<<r.lenbits)-1,w=(1<<r.distbits)-1;e:do{p<15&&(d+=k[n++]<<p,p+=8,d+=k[n++]<<p,p+=8),b=g[d&y];t:for(;;){if(d>>>=v=b>>>24,p-=v,0===(v=b>>>16&255))B[o++]=65535&b;else{if(!(16&v)){if(64&v){if(32&v){r.mode=12;break e}e.msg="invalid literal/length code",r.mode=30;break e}b=g[(65535&b)+(d&(1<<v)-1)];continue t}for(E=65535&b,(v&=15)&&(p<v&&(d+=k[n++]<<p,p+=8),E+=d&(1<<v)-1,d>>>=v,p-=v),p<15&&(d+=k[n++]<<p,p+=8,d+=k[n++]<<p,p+=8),b=m[d&w];;){if(d>>>=v=b>>>24,p-=v,16&(v=b>>>16&255)){if(I=65535&b,p<(v&=15)&&(d+=k[n++]<<p,(p+=8)<v&&(d+=k[n++]<<p,p+=8)),(I+=d&(1<<v)-1)>c){e.msg="invalid distance too far back",r.mode=30;break e}if(d>>>=v,p-=v,I>(v=o-s)){if((v=I-v)>l&&r.sane){e.msg="invalid distance too far back",r.mode=30;break e}if(_=0,A=f,0===h){if(_+=u-v,v<E){E-=v;do{B[o++]=f[_++]}while(--v);_=o-I,A=B}}else if(h<v){if(_+=u+h-v,(v-=h)<E){E-=v;do{B[o++]=f[_++]}while(--v);if(_=0,h<E){E-=v=h;do{B[o++]=f[_++]}while(--v);_=o-I,A=B}}}else if(_+=h-v,v<E){E-=v;do{B[o++]=f[_++]}while(--v);_=o-I,A=B}for(;E>2;)B[o++]=A[_++],B[o++]=A[_++],B[o++]=A[_++],E-=3;E&&(B[o++]=A[_++],E>1&&(B[o++]=A[_++]))}else{_=o-I;do{B[o++]=B[_++],B[o++]=B[_++],B[o++]=B[_++],E-=3}while(E>2);E&&(B[o++]=B[_++],E>1&&(B[o++]=B[_++]))}break}if(64&v){e.msg="invalid distance code",r.mode=30;break e}b=m[(65535&b)+(d&(1<<v)-1)]}}break}}while(n<i&&o<a);n-=E=p>>3,d&=(1<<(p-=E<<3))-1,e.next_in=n,e.next_out=o,e.avail_in=n<i?i-n+5:5-(n-i),e.avail_out=o<a?a-o+257:257-(o-a),r.hold=d,r.bits=p}var No=15,Ro=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],To=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],Lo=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],Do=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];function jo(e,t,r,n,i,o,s,a){var c,u,l,h,f,d,p,g,m,y=a.bits,w=0,b=0,v=0,E=0,I=0,_=0,A=0,k=0,B=0,x=0,S=null,O=0,U=new mi(16),C=new mi(16),N=null,R=0;for(w=0;w<=No;w++)U[w]=0;for(b=0;b<n;b++)U[t[r+b]]++;for(I=y,E=No;E>=1&&0===U[E];E--);if(I>E&&(I=E),0===E)return i[o++]=20971520,i[o++]=20971520,a.bits=1,0;for(v=1;v<E&&0===U[v];v++);for(I<v&&(I=v),k=1,w=1;w<=No;w++)if(k<<=1,(k-=U[w])<0)return-1;if(k>0&&(0===e||1!==E))return-1;for(C[1]=0,w=1;w<No;w++)C[w+1]=C[w]+U[w];for(b=0;b<n;b++)0!==t[r+b]&&(s[C[t[r+b]]++]=b);if(0===e?(S=N=s,d=19):1===e?(S=Ro,O-=257,N=To,R-=257,d=256):(S=Lo,N=Do,d=-1),x=0,b=0,w=v,f=o,_=I,A=0,l=-1,h=(B=1<<I)-1,1===e&&B>852||2===e&&B>592)return 1;for(;;){p=w-A,s[b]<d?(g=0,m=s[b]):s[b]>d?(g=N[R+s[b]],m=S[O+s[b]]):(g=96,m=0),c=1<<w-A,v=u=1<<_;do{i[f+(x>>A)+(u-=c)]=p<<24|g<<16|m}while(0!==u);for(c=1<<w-1;x&c;)c>>=1;if(0!==c?(x&=c-1,x+=c):x=0,b++,0===--U[w]){if(w===E)break;w=t[r+s[b]]}if(w>I&&(x&h)!==l){for(0===A&&(A=I),f+=v,k=1<<(_=w-A);_+A<E&&!((k-=U[_+A])<=0);)_++,k<<=1;if(B+=1<<_,1===e&&B>852||2===e&&B>592)return 1;i[l=x&h]=I<<24|_<<16|f-o}}return 0!==x&&(i[f+x]=w-A<<24|64<<16),a.bits=I,0}var Mo=-2,Po=12,Fo=30;function qo(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function Qo(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new mi(320),this.work=new mi(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function zo(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,function(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new yi(852),t.distcode=t.distdyn=new yi(592),t.sane=1,t.back=-1,0):Mo}(e)):Mo}function $o(e,t){var r,n;return e?(n=new Qo,e.state=n,n.window=null,r=function(e,t){var r,n;return e&&e.state?(n=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Mo:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=r,n.wbits=t,zo(e))):Mo}(e,t),0!==r&&(e.state=null),r):Mo}var Ho,Vo,Go=!0;function Ko(e){if(Go){var t;for(Ho=new yi(512),Vo=new yi(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(jo(1,e.lens,0,288,Ho,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;jo(2,e.lens,0,32,Vo,0,e.work,{bits:5}),Go=!1}e.lencode=Ho,e.lenbits=9,e.distcode=Vo,e.distbits=5}function Wo(e,t){var r,n,i,o,s,a,c,u,l,h,f,d,p,g,m,y,w,b,v,E,I,_,A,k,B=0,x=new gi(4),S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return Mo;(r=e.state).mode===Po&&(r.mode=13),s=e.next_out,i=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,u=r.hold,l=r.bits,h=a,f=c,_=0;e:for(;;)switch(r.mode){case 1:if(0===r.wrap){r.mode=13;break}for(;l<16;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(2&r.wrap&&35615===u){r.check=0,x[0]=255&u,x[1]=u>>>8&255,r.check=so(r.check,x,2,0),u=0,l=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",r.mode=Fo;break}if(8!=(15&u)){e.msg="unknown compression method",r.mode=Fo;break}if(l-=4,I=8+(15&(u>>>=4)),0===r.wbits)r.wbits=I;else if(I>r.wbits){e.msg="invalid window size",r.mode=Fo;break}r.dmax=1<<I,e.adler=r.check=1,r.mode=512&u?10:Po,u=0,l=0;break;case 2:for(;l<16;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(r.flags=u,8!=(255&r.flags)){e.msg="unknown compression method",r.mode=Fo;break}if(57344&r.flags){e.msg="unknown header flags set",r.mode=Fo;break}r.head&&(r.head.text=u>>8&1),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=so(r.check,x,2,0)),u=0,l=0,r.mode=3;case 3:for(;l<32;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}r.head&&(r.head.time=u),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,x[2]=u>>>16&255,x[3]=u>>>24&255,r.check=so(r.check,x,4,0)),u=0,l=0,r.mode=4;case 4:for(;l<16;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}r.head&&(r.head.xflags=255&u,r.head.os=u>>8),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=so(r.check,x,2,0)),u=0,l=0,r.mode=5;case 5:if(1024&r.flags){for(;l<16;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}r.length=u,r.head&&(r.head.extra_len=u),512&r.flags&&(x[0]=255&u,x[1]=u>>>8&255,r.check=so(r.check,x,2,0)),u=0,l=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&((d=r.length)>a&&(d=a),d&&(r.head&&(I=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),pi(r.head.extra,n,o,d,I)),512&r.flags&&(r.check=so(r.check,n,d,o)),a-=d,o+=d,r.length-=d),r.length))break e;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===a)break e;d=0;do{I=n[o+d++],r.head&&I&&r.length<65536&&(r.head.name+=String.fromCharCode(I))}while(I&&d<a);if(512&r.flags&&(r.check=so(r.check,n,d,o)),a-=d,o+=d,I)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=8;case 8:if(4096&r.flags){if(0===a)break e;d=0;do{I=n[o+d++],r.head&&I&&r.length<65536&&(r.head.comment+=String.fromCharCode(I))}while(I&&d<a);if(512&r.flags&&(r.check=so(r.check,n,d,o)),a-=d,o+=d,I)break e}else r.head&&(r.head.comment=null);r.mode=9;case 9:if(512&r.flags){for(;l<16;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(u!==(65535&r.check)){e.msg="header crc mismatch",r.mode=Fo;break}u=0,l=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=Po;break;case 10:for(;l<32;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}e.adler=r.check=qo(u),u=0,l=0,r.mode=11;case 11:if(0===r.havedict)return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,r.hold=u,r.bits=l,2;e.adler=r.check=1,r.mode=Po;case Po:if(5===t||6===t)break e;case 13:if(r.last){u>>>=7&l,l-=7&l,r.mode=27;break}for(;l<3;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}switch(r.last=1&u,l-=1,3&(u>>>=1)){case 0:r.mode=14;break;case 1:if(Ko(r),r.mode=20,6===t){u>>>=2,l-=2;break e}break;case 2:r.mode=17;break;case 3:e.msg="invalid block type",r.mode=Fo}u>>>=2,l-=2;break;case 14:for(u>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if((65535&u)!=(u>>>16^65535)){e.msg="invalid stored block lengths",r.mode=Fo;break}if(r.length=65535&u,u=0,l=0,r.mode=15,6===t)break e;case 15:r.mode=16;case 16:if(d=r.length){if(d>a&&(d=a),d>c&&(d=c),0===d)break e;pi(i,n,o,d,s),a-=d,o+=d,c-=d,s+=d,r.length-=d;break}r.mode=Po;break;case 17:for(;l<14;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(r.nlen=257+(31&u),u>>>=5,l-=5,r.ndist=1+(31&u),u>>>=5,l-=5,r.ncode=4+(15&u),u>>>=4,l-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Fo;break}r.have=0,r.mode=18;case 18:for(;r.have<r.ncode;){for(;l<3;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}r.lens[S[r.have++]]=7&u,u>>>=3,l-=3}for(;r.have<19;)r.lens[S[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,A={bits:r.lenbits},_=jo(0,r.lens,0,19,r.lencode,0,r.work,A),r.lenbits=A.bits,_){e.msg="invalid code lengths set",r.mode=Fo;break}r.have=0,r.mode=19;case 19:for(;r.have<r.nlen+r.ndist;){for(;y=(B=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,w=65535&B,!((m=B>>>24)<=l);){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(w<16)u>>>=m,l-=m,r.lens[r.have++]=w;else{if(16===w){for(k=m+2;l<k;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(u>>>=m,l-=m,0===r.have){e.msg="invalid bit length repeat",r.mode=Fo;break}I=r.lens[r.have-1],d=3+(3&u),u>>>=2,l-=2}else if(17===w){for(k=m+3;l<k;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}l-=m,I=0,d=3+(7&(u>>>=m)),u>>>=3,l-=3}else{for(k=m+7;l<k;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}l-=m,I=0,d=11+(127&(u>>>=m)),u>>>=7,l-=7}if(r.have+d>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Fo;break}for(;d--;)r.lens[r.have++]=I}}if(r.mode===Fo)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=Fo;break}if(r.lenbits=9,A={bits:r.lenbits},_=jo(1,r.lens,0,r.nlen,r.lencode,0,r.work,A),r.lenbits=A.bits,_){e.msg="invalid literal/lengths set",r.mode=Fo;break}if(r.distbits=6,r.distcode=r.distdyn,A={bits:r.distbits},_=jo(2,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,A),r.distbits=A.bits,_){e.msg="invalid distances set",r.mode=Fo;break}if(r.mode=20,6===t)break e;case 20:r.mode=21;case 21:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,r.hold=u,r.bits=l,Co(e,f),s=e.next_out,i=e.output,c=e.avail_out,o=e.next_in,n=e.input,a=e.avail_in,u=r.hold,l=r.bits,r.mode===Po&&(r.back=-1);break}for(r.back=0;y=(B=r.lencode[u&(1<<r.lenbits)-1])>>>16&255,w=65535&B,!((m=B>>>24)<=l);){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(y&&!(240&y)){for(b=m,v=y,E=w;y=(B=r.lencode[E+((u&(1<<b+v)-1)>>b)])>>>16&255,w=65535&B,!(b+(m=B>>>24)<=l);){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}u>>>=b,l-=b,r.back+=b}if(u>>>=m,l-=m,r.back+=m,r.length=w,0===y){r.mode=26;break}if(32&y){r.back=-1,r.mode=Po;break}if(64&y){e.msg="invalid literal/length code",r.mode=Fo;break}r.extra=15&y,r.mode=22;case 22:if(r.extra){for(k=r.extra;l<k;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}r.length+=u&(1<<r.extra)-1,u>>>=r.extra,l-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;y=(B=r.distcode[u&(1<<r.distbits)-1])>>>16&255,w=65535&B,!((m=B>>>24)<=l);){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(!(240&y)){for(b=m,v=y,E=w;y=(B=r.distcode[E+((u&(1<<b+v)-1)>>b)])>>>16&255,w=65535&B,!(b+(m=B>>>24)<=l);){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}u>>>=b,l-=b,r.back+=b}if(u>>>=m,l-=m,r.back+=m,64&y){e.msg="invalid distance code",r.mode=Fo;break}r.offset=w,r.extra=15&y,r.mode=24;case 24:if(r.extra){for(k=r.extra;l<k;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}r.offset+=u&(1<<r.extra)-1,u>>>=r.extra,l-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Fo;break}r.mode=25;case 25:if(0===c)break e;if(d=f-c,r.offset>d){if((d=r.offset-d)>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Fo;break}d>r.wnext?(d-=r.wnext,p=r.wsize-d):p=r.wnext-d,d>r.length&&(d=r.length),g=r.window}else g=i,p=s-r.offset,d=r.length;d>c&&(d=c),c-=d,r.length-=d;do{i[s++]=g[p++]}while(--d);0===r.length&&(r.mode=21);break;case 26:if(0===c)break e;i[s++]=r.length,c--,r.mode=21;break;case 27:if(r.wrap){for(;l<32;){if(0===a)break e;a--,u|=n[o++]<<l,l+=8}if(f-=c,e.total_out+=f,r.total+=f,f&&(e.adler=r.check=r.flags?so(r.check,i,f,s-f):io(r.check,i,f,s-f)),f=c,(r.flags?u:qo(u))!==r.check){e.msg="incorrect data check",r.mode=Fo;break}u=0,l=0}r.mode=28;case 28:if(r.wrap&&r.flags){for(;l<32;){if(0===a)break e;a--,u+=n[o++]<<l,l+=8}if(u!==(4294967295&r.total)){e.msg="incorrect length check",r.mode=Fo;break}u=0,l=0}r.mode=29;case 29:_=1;break e;case Fo:_=-3;break e;case 31:return-4;default:return Mo}return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,r.hold=u,r.bits=l,(r.wsize||f!==e.avail_out&&r.mode<Fo&&(r.mode<27||4!==t))&&function(e,t,r,n){var i,o=e.state;null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new gi(o.wsize)),n>=o.wsize?(pi(o.window,t,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):((i=o.wsize-o.wnext)>n&&(i=n),pi(o.window,t,r-n,i,o.wnext),(n-=i)?(pi(o.window,t,r-n,n,0),o.wnext=n,o.whave=o.wsize):(o.wnext+=i,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=i)))}(e,e.output,e.next_out,f-e.avail_out),h-=e.avail_in,f-=e.avail_out,e.total_in+=h,e.total_out+=f,r.total+=f,r.wrap&&f&&(e.adler=r.check=r.flags?so(r.check,i,f,e.next_out-f):io(r.check,i,f,e.next_out-f)),e.data_type=r.bits+(r.last?64:0)+(r.mode===Po?128:0)+(20===r.mode||15===r.mode?256:0),(0===h&&0===f||4===t)&&0===_&&(_=-5),_}var Jo;function Zo(e){if(e<1||e>7)throw new TypeError("Bad argument");this.mode=e,this.init_done=!1,this.write_in_progress=!1,this.pending_close=!1,this.windowBits=0,this.level=0,this.memLevel=0,this.strategy=0,this.dictionary=null}function Yo(e,t){for(var r=0;r<e.length;r++)this[t+r]=e[r]}Zo.prototype.init=function(e,t,r,n,i){var o;switch(this.windowBits=e,this.level=t,this.memLevel=r,this.strategy=n,3!==this.mode&&4!==this.mode||(this.windowBits+=16),7===this.mode&&(this.windowBits+=32),5!==this.mode&&6!==this.mode||(this.windowBits=-this.windowBits),this.strm=new di,this.mode){case 1:case 3:case 5:o=function(e,t,r,n,i,o){if(!e)return co;var s=1;if(-1===t&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),i<1||i>9||8!==r||n<8||n>15||t<0||t>9||o<0||o>4)return go(e,co);8===n&&(n=9);var a=new So;return e.state=a,a.strm=e,a.wrap=s,a.gzhead=null,a.w_bits=n,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=i+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new gi(2*a.w_size),a.head=new mi(a.hash_size),a.prev=new mi(a.w_size),a.lit_bufsize=1<<i+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new gi(a.pending_buf_size),a.d_buf=1*a.lit_bufsize,a.l_buf=3*a.lit_bufsize,a.level=t,a.strategy=o,a.method=r,Oo(e)}(this.strm,this.level,8,this.windowBits,this.memLevel,this.strategy);break;case 2:case 4:case 6:case 7:o=$o(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}0===o?(this.write_in_progress=!1,this.init_done=!0):this._error(o)},Zo.prototype.params=function(){throw new Error("deflateParams Not supported")},Zo.prototype._writeCheck=function(){if(!this.init_done)throw new Error("write before init");if(0===this.mode)throw new Error("already finalized");if(this.write_in_progress)throw new Error("write already in progress");if(this.pending_close)throw new Error("close is pending")},Zo.prototype.write=function(e,t,r,n,i,o,s){this._writeCheck(),this.write_in_progress=!0;var a=this;return Rr.nextTick(function(){a.write_in_progress=!1;var c=a._write(e,t,r,n,i,o,s);a.callback(c[0],c[1]),a.pending_close&&a.close()}),this},Zo.prototype.writeSync=function(e,t,r,n,i,o,s){return this._writeCheck(),this._write(e,t,r,n,i,o,s)},Zo.prototype._write=function(e,t,r,n,i,o,s){if(this.write_in_progress=!0,0!==e&&1!==e&&2!==e&&3!==e&&4!==e&&5!==e)throw new Error("Invalid flush value");null==t&&(t=new _t(0),n=0,r=0),i._set?i.set=i._set:i.set=Yo;var a,c=this.strm;switch(c.avail_in=n,c.input=t,c.next_in=r,c.avail_out=s,c.output=i,c.next_out=o,this.mode){case 1:case 3:case 5:a=Uo(c,e);break;case 7:case 2:case 4:case 6:a=Wo(c,e);break;default:throw new Error("Unknown mode "+this.mode)}return this._checkError(a,c,e)||this._error(a),this.write_in_progress=!1,[c.avail_in,c.avail_out]},Zo.prototype._checkError=function(e,t,r){switch(e){case 0:case-5:if(0!==t.avail_out&&4===r)return!1;break;case 1:break;default:return!1}return!0},Zo.prototype.close=function(){this.write_in_progress?this.pending_close=!0:(this.pending_close=!1,1===this.mode||3===this.mode||5===this.mode?function(e){var t;e&&e.state&&(42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==ho&&t!==fo&&t!==po?go(e,co):(e.state=null,t===fo&&go(e,-3)))}(this.strm):function(e){if(!e||!e.state)return Mo;var t=e.state;t.window&&(t.window=null),e.state=null}(this.strm),this.mode=0)},Zo.prototype.reset=function(){switch(this.mode){case 1:case 5:Jo=Oo(this.strm);break;case 2:case 6:Jo=zo(this.strm)}0!==Jo&&this._error(Jo)},Zo.prototype._error=function(e){this.onerror(fi[e]+": "+this.strm.msg,e),this.write_in_progress=!1,this.pending_close&&this.close()};var Xo=Object.freeze({__proto__:null,DEFLATE:1,DEFLATERAW:5,GUNZIP:4,GZIP:3,INFLATE:2,INFLATERAW:6,NONE:0,UNZIP:7,Z_BEST_COMPRESSION:9,Z_BEST_SPEED:1,Z_BINARY:0,Z_BLOCK:5,Z_BUF_ERROR:-5,Z_DATA_ERROR:-3,Z_DEFAULT_COMPRESSION:-1,Z_DEFAULT_STRATEGY:0,Z_DEFLATED:8,Z_ERRNO:-1,Z_FILTERED:1,Z_FINISH:4,Z_FIXED:4,Z_FULL_FLUSH:3,Z_HUFFMAN_ONLY:2,Z_NEED_DICT:2,Z_NO_COMPRESSION:0,Z_NO_FLUSH:0,Z_OK:0,Z_PARTIAL_FLUSH:1,Z_RLE:3,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_SYNC_FLUSH:2,Z_TEXT:1,Z_TREES:6,Z_UNKNOWN:2,Zlib:Zo});var es={};Object.keys(Xo).forEach(function(e){es[e]=Xo[e]}),es.Z_MIN_WINDOWBITS=8,es.Z_MAX_WINDOWBITS=15,es.Z_DEFAULT_WINDOWBITS=15,es.Z_MIN_CHUNK=64,es.Z_MAX_CHUNK=1/0,es.Z_DEFAULT_CHUNK=16384,es.Z_MIN_MEMLEVEL=1,es.Z_MAX_MEMLEVEL=9,es.Z_DEFAULT_MEMLEVEL=8,es.Z_MIN_LEVEL=-1,es.Z_MAX_LEVEL=9,es.Z_DEFAULT_LEVEL=es.Z_DEFAULT_COMPRESSION;var ts={Z_OK:es.Z_OK,Z_STREAM_END:es.Z_STREAM_END,Z_NEED_DICT:es.Z_NEED_DICT,Z_ERRNO:es.Z_ERRNO,Z_STREAM_ERROR:es.Z_STREAM_ERROR,Z_DATA_ERROR:es.Z_DATA_ERROR,Z_MEM_ERROR:es.Z_MEM_ERROR,Z_BUF_ERROR:es.Z_BUF_ERROR,Z_VERSION_ERROR:es.Z_VERSION_ERROR};function rs(e,t,r){var n=[],i=0;function o(){for(var t;null!==(t=e.read());)n.push(t),i+=t.length;e.once("readable",o)}function s(){var t=_t.concat(n,i);n=[],r(null,t),e.close()}e.on("error",function(t){e.removeListener("end",s),e.removeListener("readable",o),r(t)}),e.on("end",s),e.end(t),o()}function ns(e,t){if("string"==typeof t&&(t=new _t(t)),!_t.isBuffer(t))throw new TypeError("Not a string or buffer");var r=es.Z_FINISH;return e._processChunk(t,r)}function is(e){if(!(this instanceof is))return new is(e);hs.call(this,e,es.DEFLATE)}function os(e){if(!(this instanceof os))return new os(e);hs.call(this,e,es.INFLATE)}function ss(e){if(!(this instanceof ss))return new ss(e);hs.call(this,e,es.GZIP)}function as(e){if(!(this instanceof as))return new as(e);hs.call(this,e,es.GUNZIP)}function cs(e){if(!(this instanceof cs))return new cs(e);hs.call(this,e,es.DEFLATERAW)}function us(e){if(!(this instanceof us))return new us(e);hs.call(this,e,es.INFLATERAW)}function ls(e){if(!(this instanceof ls))return new ls(e);hs.call(this,e,es.UNZIP)}function hs(e,t){if(this._opts=e=e||{},this._chunkSize=e.chunkSize||es.Z_DEFAULT_CHUNK,ai.call(this,e),e.flush&&e.flush!==es.Z_NO_FLUSH&&e.flush!==es.Z_PARTIAL_FLUSH&&e.flush!==es.Z_SYNC_FLUSH&&e.flush!==es.Z_FULL_FLUSH&&e.flush!==es.Z_FINISH&&e.flush!==es.Z_BLOCK)throw new Error("Invalid flush flag: "+e.flush);if(this._flushFlag=e.flush||es.Z_NO_FLUSH,e.chunkSize&&(e.chunkSize<es.Z_MIN_CHUNK||e.chunkSize>es.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+e.chunkSize);if(e.windowBits&&(e.windowBits<es.Z_MIN_WINDOWBITS||e.windowBits>es.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+e.windowBits);if(e.level&&(e.level<es.Z_MIN_LEVEL||e.level>es.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+e.level);if(e.memLevel&&(e.memLevel<es.Z_MIN_MEMLEVEL||e.memLevel>es.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+e.memLevel);if(e.strategy&&e.strategy!=es.Z_FILTERED&&e.strategy!=es.Z_HUFFMAN_ONLY&&e.strategy!=es.Z_RLE&&e.strategy!=es.Z_FIXED&&e.strategy!=es.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+e.strategy);if(e.dictionary&&!_t.isBuffer(e.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._binding=new es.Zlib(t);var r=this;this._hadError=!1,this._binding.onerror=function(e,t){r._binding=null,r._hadError=!0;var n=new Error(e);n.errno=t,n.code=ts[t],r.emit("error",n)};var n=es.Z_DEFAULT_COMPRESSION;"number"==typeof e.level&&(n=e.level);var i=es.Z_DEFAULT_STRATEGY;"number"==typeof e.strategy&&(i=e.strategy),this._binding.init(e.windowBits||es.Z_DEFAULT_WINDOWBITS,n,e.memLevel||es.Z_DEFAULT_MEMLEVEL,i,e.dictionary),this._buffer=new _t(this._chunkSize),this._offset=0,this._closed=!1,this._level=n,this._strategy=i,this.once("end",this.close)}Object.keys(ts).forEach(function(e){ts[ts[e]]=e}),Nr(hs,ai),hs.prototype.params=function(e,t,r){if(e<es.Z_MIN_LEVEL||e>es.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+e);if(t!=es.Z_FILTERED&&t!=es.Z_HUFFMAN_ONLY&&t!=es.Z_RLE&&t!=es.Z_FIXED&&t!=es.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+t);if(this._level!==e||this._strategy!==t){var n=this;this.flush(es.Z_SYNC_FLUSH,function(){n._binding.params(e,t),n._hadError||(n._level=e,n._strategy=t,r&&r())})}else Rr.nextTick(r)},hs.prototype.reset=function(){return this._binding.reset()},hs.prototype._flush=function(e){this._transform(new _t(0),"",e)},hs.prototype.flush=function(e,t){var r=this._writableState;if(("function"==typeof e||void 0===e&&!t)&&(t=e,e=es.Z_FULL_FLUSH),r.ended)t&&Rr.nextTick(t);else if(r.ending)t&&this.once("end",t);else if(r.needDrain){var n=this;this.once("drain",function(){n.flush(t)})}else this._flushFlag=e,this.write(new _t(0),"",t)},hs.prototype.close=function(e){if(e&&Rr.nextTick(e),!this._closed){this._closed=!0,this._binding.close();var t=this;Rr.nextTick(function(){t.emit("close")})}},hs.prototype._transform=function(e,t,r){var n,i=this._writableState,o=(i.ending||i.ended)&&(!e||i.length===e.length);if(null===!e&&!_t.isBuffer(e))return r(new Error("invalid input"));o?n=es.Z_FINISH:(n=this._flushFlag,e.length>=i.length&&(this._flushFlag=this._opts.flush||es.Z_NO_FLUSH)),this._processChunk(e,n,r)},hs.prototype._processChunk=function(e,t,r){var n=e&&e.length,i=this._chunkSize-this._offset,o=0,s=this,a="function"==typeof r;if(!a){var c,u=[],l=0;this.on("error",function(e){c=e});do{var h=this._binding.writeSync(t,e,o,n,this._buffer,this._offset,i)}while(!this._hadError&&p(h[0],h[1]));if(this._hadError)throw c;var f=_t.concat(u,l);return this.close(),f}var d=this._binding.write(t,e,o,n,this._buffer,this._offset,i);function p(c,h){if(!s._hadError){var f=i-h;if(function(e,t){if(!e)throw new Error(t)}(f>=0,"have should not go down"),f>0){var d=s._buffer.slice(s._offset,s._offset+f);s._offset+=f,a?s.push(d):(u.push(d),l+=d.length)}if((0===h||s._offset>=s._chunkSize)&&(i=s._chunkSize,s._offset=0,s._buffer=new _t(s._chunkSize)),0===h){if(o+=n-c,n=c,!a)return!0;var g=s._binding.write(t,e,o,n,s._buffer,s._offset,s._chunkSize);return g.callback=p,void(g.buffer=e)}if(!a)return!1;r()}}d.buffer=e,d.callback=p},Nr(is,hs),Nr(os,hs),Nr(ss,hs),Nr(as,hs),Nr(cs,hs),Nr(us,hs),Nr(ls,hs);var fs={codes:ts,createDeflate:function(e){return new is(e)},createInflate:function(e){return new os(e)},createDeflateRaw:function(e){return new cs(e)},createInflateRaw:function(e){return new us(e)},createGzip:function(e){return new ss(e)},createGunzip:function(e){return new as(e)},createUnzip:function(e){return new ls(e)},deflate:function(e,t,r){return"function"==typeof t&&(r=t,t={}),rs(new is(t),e,r)},deflateSync:function(e,t){return ns(new is(t),e)},gzip:function(e,t,r){return"function"==typeof t&&(r=t,t={}),rs(new ss(t),e,r)},gzipSync:function(e,t){return ns(new ss(t),e)},deflateRaw:function(e,t,r){return"function"==typeof t&&(r=t,t={}),rs(new cs(t),e,r)},deflateRawSync:function(e,t){return ns(new cs(t),e)},unzip:function(e,t,r){return"function"==typeof t&&(r=t,t={}),rs(new ls(t),e,r)},unzipSync:function(e,t){return ns(new ls(t),e)},inflate:function(e,t,r){return"function"==typeof t&&(r=t,t={}),rs(new os(t),e,r)},inflateSync:function(e,t){return ns(new os(t),e)},gunzip:function(e,t,r){return"function"==typeof t&&(r=t,t={}),rs(new as(t),e,r)},gunzipSync:function(e,t){return ns(new as(t),e)},inflateRaw:function(e,t,r){return"function"==typeof t&&(r=t,t={}),rs(new us(t),e,r)},inflateRawSync:function(e,t){return ns(new us(t),e)},Deflate:is,Inflate:os,Gzip:ss,Gunzip:as,DeflateRaw:cs,InflateRaw:us,Unzip:ls,Zlib:hs};class ds extends Qe{constructor(e={}){super(),this.config=e}async _set(e,t){}async _get(e){}async _del(e){}async _clear(e){}validateKey(e){if(null==e||"string"!=typeof e||!e)throw new Error("Invalid key")}async set(e,t){return this.validateKey(e),await this._set(e,t),this.emit("set",t),t}async get(e){this.validateKey(e);const t=await this._get(e);return this.emit("get",t),t}async del(e){this.validateKey(e);const t=await this._del(e);return this.emit("delete",t),t}async delete(e){return this.del(e)}async clear(e){const t=await this._clear(e);return this.emit("clear",t),t}}class ps extends ds{constructor({client:e,keyPrefix:t="cache",ttl:r=0,prefix:n}){super({client:e,keyPrefix:t,ttl:r,prefix:n}),this.client=e,this.keyPrefix=t,this.config.ttl=r,this.config.client=e,this.config.prefix=void 0!==n?n:t+(t.endsWith("/")?"":"/")}async _set(e,t){let r=JSON.stringify(t);const n=r.length;return r=fs.gzipSync(r).toString("base64"),this.client.putObject({key:it(this.keyPrefix,e),body:r,contentEncoding:"gzip",contentType:"application/gzip",metadata:{compressor:"zlib",compressed:"true","client-id":this.client.id,"length-serialized":String(n),"length-compressed":String(r.length),"compression-gain":(r.length/n).toFixed(2)}})}async _get(e){const[t,n,i]=await G(async()=>{const{Body:t}=await this.client.getObject(it(this.keyPrefix,e));let n=await r(t);return n=Buffer.from(n,"base64"),n=fs.unzipSync(n).toString(),JSON.parse(n)});if(t)return i;if("NoSuchKey"===n.name||"NotFound"===n.name)return null;throw n}async _del(e){return await this.client.deleteObject(it(this.keyPrefix,e)),!0}async _clear(){const e=await this.client.getAllKeys({prefix:this.keyPrefix});await this.client.deleteObjects(e)}async size(){return(await this.keys()).length}async keys(){const e=await this.client.getAllKeys({prefix:this.keyPrefix}),t=this.keyPrefix.endsWith("/")?this.keyPrefix:this.keyPrefix+"/";return e.map(e=>e.startsWith(t)?e.slice(t.length):e)}}class gs extends ds{constructor(e={}){super(e),this.cache={},this.meta={},this.maxSize=e.maxSize||0,this.ttl=e.ttl||0}async _set(e,t){if(this.maxSize>0&&Object.keys(this.cache).length>=this.maxSize){const e=Object.entries(this.meta).sort((e,t)=>e[1].ts-t[1].ts)[0]?.[0];e&&(delete this.cache[e],delete this.meta[e])}return this.cache[e]=t,this.meta[e]={ts:Date.now()},t}async _get(e){if(!Object.prototype.hasOwnProperty.call(this.cache,e))return null;if(this.ttl>0){const t=Date.now(),r=this.meta[e];if(r&&t-r.ts>1e3*this.ttl)return delete this.cache[e],delete this.meta[e],null}return this.cache[e]}async _del(e){return delete this.cache[e],delete this.meta[e],!0}async _clear(e){if(!e)return this.cache={},this.meta={},!0;for(const t of Object.keys(this.cache))t.startsWith(e)&&(delete this.cache[t],delete this.meta[t]);return!0}async size(){return Object.keys(this.cache).length}async keys(){return Object.keys(this.cache)}}class ms extends We{constructor(e={}){super(e),this.driver=e.driver,this.config={includePartitions:!1!==e.includePartitions,...e}}async setup(e){await super.setup(e)}async onSetup(){this.config.driver?this.driver=this.config.driver:"memory"===this.config.driverType?this.driver=new gs(this.config.memoryOptions||{}):this.driver=new ps({client:this.database.client,...this.config.s3Options||{}}),this.installDatabaseProxy(),this.installResourceHooks()}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._cacheProxyInstalled)return;const e=this.installResourceHooks.bind(this);this.database._originalCreateResourceForCache=this.database.createResource,this.database.createResource=async function(...t){const r=await this._originalCreateResourceForCache(...t);return e(r),r},this.database._cacheProxyInstalled=!0}installResourceHooks(){for(const e of Object.values(this.database.resources))this.installResourceHooksForResource(e)}installResourceHooksForResource(e){if(!this.driver)return;Object.defineProperty(e,"cache",{value:this.driver,writable:!0,configurable:!0,enumerable:!1}),e.cacheKeyFor=async(t={})=>{const{action:r,params:n={},partition:i,partitionValues:o}=t;return this.generateCacheKey(e,r,n,i,o)};const t=["count","listIds","getMany","getAll","page","list","get"];for(const r of t)e.useMiddleware(r,async(t,n)=>{let i;if("getMany"===r)i=await e.cacheKeyFor({action:r,params:{ids:t.args[0]}});else if("page"===r){const{offset:n,size:o,partition:s,partitionValues:a}=t.args[0]||{};i=await e.cacheKeyFor({action:r,params:{offset:n,size:o},partition:s,partitionValues:a})}else if("list"===r||"listIds"===r||"count"===r){const{partition:n,partitionValues:o}=t.args[0]||{};i=await e.cacheKeyFor({action:r,partition:n,partitionValues:o})}else"getAll"===r?i=await e.cacheKeyFor({action:r}):"get"===r&&(i=await e.cacheKeyFor({action:r,params:{id:t.args[0]}}));const[o,s,a]=await G(()=>e.cache.get(i));if(o&&null!=a)return a;if(!o&&"NoSuchKey"!==s.name)throw s;const c=await n();return await e.cache.set(i,c),c});const r=["insert","update","delete","deleteMany"];for(const t of r)e.useMiddleware(t,async(r,n)=>{const i=await n();if("insert"===t)await this.clearCacheForResource(e,r.args[0]);else if("update"===t)await this.clearCacheForResource(e,{id:r.args[0],...r.args[1]});else if("delete"===t){let t={id:r.args[0]};if("function"==typeof e.get){const[n,i,o]=await G(()=>e.get(r.args[0]));n&&o&&(t=o)}await this.clearCacheForResource(e,t)}else"deleteMany"===t&&await this.clearCacheForResource(e);return i})}async clearCacheForResource(e,t){if(!e.cache)return;const r=`resource=${e.name}`;if(await e.cache.clear(r),!0===this.config.includePartitions&&e.config?.partitions&&Object.keys(e.config.partitions).length>0)if(t){const n=this.getPartitionValues(t,e);for(const[t,i]of Object.entries(n))if(i&&Object.keys(i).length>0&&Object.values(i).some(e=>null!=e)){const n=it(r,`partition=${t}`);await e.cache.clear(n)}}else for(const t of Object.keys(e.config.partitions)){const n=it(r,`partition=${t}`);await e.cache.clear(n)}}async generateCacheKey(e,t,r={},n=null,i=null){const o=[`resource=${e.name}`,`action=${t}`];if(n&&i&&Object.keys(i).length>0){o.push(`partition:${n}`);for(const[e,t]of Object.entries(i))null!=t&&o.push(`${e}:${t}`)}if(Object.keys(r).length>0){const e=await this.hashParams(r);o.push(e)}return it(...o)+".json.gz"}async hashParams(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("|")||"empty";return await Te(t)}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 e of Object.values(this.database.resources))if(e.cache){const t=`resource=${e.name}`;await e.cache.clear(t)}}async warmCache(e,t={}){const r=this.database.resources[e];if(!r)throw new Error(`Resource '${e}' not found`);const{includePartitions:n=!0}=t;if(await r.getAll(),n&&r.config.partitions)for(const[e,t]of Object.entries(r.config.partitions))if(t.fields){const t=await r.getAll(),n=Array.isArray(t)?t:[],i=new Set;for(const t of n.slice(0,10)){const n=this.getPartitionValues(t,r);n[e]&&i.add(JSON.stringify(n[e]))}for(const t of i){const n=JSON.parse(t);await r.list({partition:e,partitionValues:n})}}}}const ys={async setup(e){e&&e.client&&(this.client=e.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",e=>this.addRequest(e,this.map[e])),this.client.on("command.error",e=>this.addRequest(e,this.map[e])))},addRequest(e,t){t&&(this.costs.events[e]++,this.costs.events.total++,this.costs.requests.total++,this.costs.requests[t]++,this.costs.total+=this.costs.prices[t],this.client&&this.client.costs&&(this.client.costs.events[e]++,this.client.costs.events.total++,this.client.costs.requests.total++,this.client.costs.requests[t]++,this.client.costs.total+=this.client.costs.prices[t]))}};class ws extends We{constructor(e={}){super(),this.indexResource=null,this.config={minWordLength:e.minWordLength||3,maxResults:e.maxResults||100,...e},this.indexes=new Map}async setup(e){this.database=e;const[t,r,n]=await G(()=>e.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=t?n:e.resources.fulltext_indexes,await this.loadIndexes(),this.installIndexingHooks()}async start(){}async stop(){await this.saveIndexes()}async loadIndexes(){if(!this.indexResource)return;const[e,t,r]=await G(()=>this.indexResource.getAll());if(e)for(const e of r){const t=`${e.resourceName}:${e.fieldName}:${e.word}`;this.indexes.set(t,{recordIds:e.recordIds||[],count:e.count||0})}}async saveIndexes(){if(!this.indexResource)return;const[e,t]=await G(async()=>{const e=await this.indexResource.getAll();for(const t of e)await this.indexResource.delete(t.id);for(const[e,t]of this.indexes.entries()){const[r,n,i]=e.split(":");await this.indexResource.insert({id:`index-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:r,fieldName:n,word:i,recordIds:t.recordIds,count:t.count,lastUpdated:(new Date).toISOString()})}})}installIndexingHooks(){this.database.plugins||(this.database.plugins={}),this.database.plugins.fulltext=this;for(const e of Object.values(this.database.resources))"fulltext_indexes"!==e.name&&this.installResourceHooks(e);this.database._fulltextProxyInstalled||(this.database._previousCreateResourceForFullText=this.database.createResource,this.database.createResource=async function(...e){const t=await this._previousCreateResourceForFullText(...e);return this.plugins?.fulltext&&"fulltext_indexes"!==t.name&&this.plugins.fulltext.installResourceHooks(t),t},this.database._fulltextProxyInstalled=!0);for(const e of Object.values(this.database.resources))"fulltext_indexes"!==e.name&&this.installResourceHooks(e)}installResourceHooks(e){e._insert=e.insert,e._update=e.update,e._delete=e.delete,e._deleteMany=e.deleteMany,this.wrapResourceMethod(e,"insert",async(t,r,n)=>{const[i]=r;return this.indexRecord(e.name,t.id,i).catch(console.error),t}),this.wrapResourceMethod(e,"update",async(t,r,n)=>{const[i,o]=r;return this.removeRecordFromIndex(e.name,i).catch(console.error),this.indexRecord(e.name,i,t).catch(console.error),t}),this.wrapResourceMethod(e,"delete",async(t,r,n)=>{const[i]=r;return this.removeRecordFromIndex(e.name,i).catch(console.error),t}),this.wrapResourceMethod(e,"deleteMany",async(t,r,n)=>{const[i]=r;for(const t of i)this.removeRecordFromIndex(e.name,t).catch(console.error);return t})}async indexRecord(e,t,r){const n=this.getIndexedFields(e);if(n&&0!==n.length)for(const i of n){const n=this.getFieldValue(r,i);if(!n)continue;const o=this.tokenize(n);for(const r of o){if(r.length<this.config.minWordLength)continue;const n=`${e}:${i}:${r.toLowerCase()}`,o=this.indexes.get(n)||{recordIds:[],count:0};o.recordIds.includes(t)||(o.recordIds.push(t),o.count=o.recordIds.length),this.indexes.set(n,o)}}}async removeRecordFromIndex(e,t){for(const[r,n]of this.indexes.entries())if(r.startsWith(`${e}:`)){const e=n.recordIds.indexOf(t);e>-1&&(n.recordIds.splice(e,1),n.count=n.recordIds.length,0===n.recordIds.length?this.indexes.delete(r):this.indexes.set(r,n))}}getFieldValue(e,t){if(!t.includes("."))return e&&void 0!==e[t]?e[t]:null;const r=t.split(".");let n=e;for(const e of r){if(!n||"object"!=typeof n||!(e in n))return null;n=n[e]}return n}tokenize(e){if(!e)return[];return String(e).toLowerCase().replace(/[^\w\s\u00C0-\u017F]/g," ").split(/\s+/).filter(e=>e.length>0)}getIndexedFields(e){if(this.config.fields)return this.config.fields;return{users:["name","email"],products:["name","description"],articles:["title","content"]}[e]||[]}async search(e,t,r={}){const{fields:n=null,limit:i=this.config.maxResults,offset:o=0,exactMatch:s=!1}=r;if(!t||0===t.trim().length)return[];const a=this.tokenize(t),c=new Map,u=n||this.getIndexedFields(e);if(0===u.length)return[];for(const t of a)if(!(t.length<this.config.minWordLength))for(const r of u)if(s){const n=`${e}:${r}:${t.toLowerCase()}`,i=this.indexes.get(n);if(i)for(const e of i.recordIds){const t=c.get(e)||0;c.set(e,t+1)}}else for(const[n,i]of this.indexes.entries())if(n.startsWith(`${e}:${r}:${t.toLowerCase()}`))for(const e of i.recordIds){const t=c.get(e)||0;c.set(e,t+1)}return Array.from(c.entries()).map(([e,t])=>({recordId:e,score:t})).sort((e,t)=>t.score-e.score).slice(o,o+i)}async searchRecords(e,t,r={}){const n=await this.search(e,t,r);if(0===n.length)return[];const i=this.database.resources[e];if(!i)throw new Error(`Resource '${e}' not found`);const o=n.map(e=>e.recordId);return(await i.getMany(o)).filter(e=>e&&"object"==typeof e).map(e=>{const t=n.find(t=>t.recordId===e.id);return{...e,_searchScore:t?t.score:0}}).sort((e,t)=>t._searchScore-e._searchScore)}async rebuildIndex(e){const t=this.database.resources[e];if(!t)throw new Error(`Resource '${e}' not found`);for(const[t]of this.indexes.entries())t.startsWith(`${e}:`)&&this.indexes.delete(t);const r=await t.getAll();for(let t=0;t<r.length;t+=100){const n=r.slice(t,t+100);for(const t of n){const[r,n]=await G(()=>this.indexRecord(e,t.id,t))}}await this.saveIndexes()}async getIndexStats(){const e={totalIndexes:this.indexes.size,resources:{},totalWords:0};for(const[t,r]of this.indexes.entries()){const[n,i]=t.split(":");e.resources[n]||(e.resources[n]={fields:{},totalRecords:new Set,totalWords:0}),e.resources[n].fields[i]||(e.resources[n].fields[i]={words:0,totalOccurrences:0}),e.resources[n].fields[i].words++,e.resources[n].fields[i].totalOccurrences+=r.count,e.resources[n].totalWords++;for(const t of r.recordIds)e.resources[n].totalRecords.add(t);e.totalWords++}for(const t in e.resources)e.resources[t].totalRecords=e.resources[t].totalRecords.size;return e}async rebuildAllIndexes({timeout:e}={}){return e?Promise.race([this._rebuildAllIndexesInternal(),new Promise((t,r)=>setTimeout(()=>r(new Error("Timeout")),e))]):this._rebuildAllIndexesInternal()}async _rebuildAllIndexesInternal(){const e=Object.keys(this.database.resources).filter(e=>"fulltext_indexes"!==e);for(const t of e){const[e,r]=await G(()=>this.rebuildIndex(t))}}async clearIndex(e){for(const[t]of this.indexes.entries())t.startsWith(`${e}:`)&&this.indexes.delete(t);await this.saveIndexes()}async clearAllIndexes(){this.indexes.clear(),await this.saveIndexes()}}class bs extends We{constructor(e={}){super(),this.config={collectPerformance:!1!==e.collectPerformance,collectErrors:!1!==e.collectErrors,collectUsage:!1!==e.collectUsage,retentionDays:e.retentionDays||30,flushInterval:e.flushInterval||6e4,...e},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(e){if(this.database=e,"test"===process.env.NODE_ENV)return;const[t,r]=await G(async()=>{const[t,r,n]=await G(()=>e.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=t?n:e.resources.metrics;const[i,o,s]=await G(()=>e.createResource({name:"error_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",error:"string|required",timestamp:"string|required",metadata:"json"}}));this.errorsResource=i?s:e.resources.error_logs;const[a,c,u]=await G(()=>e.createResource({name:"performance_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",duration:"number|required",timestamp:"string|required",metadata:"json"}}));this.performanceResource=a?u:e.resources.performance_logs});t||(this.metricsResource=e.resources.metrics,this.errorsResource=e.resources.error_logs,this.performanceResource=e.resources.performance_logs),this.installMetricsHooks(),"test"!==process.env.NODE_ENV&&this.startFlushTimer()}async start(){}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"test"!==process.env.NODE_ENV&&await this.flushMetrics()}installMetricsHooks(){for(const e of Object.values(this.database.resources))["metrics","error_logs","performance_logs"].includes(e.name)||this.installResourceHooks(e);this.database._createResource=this.database.createResource,this.database.createResource=async function(...e){const t=await this._createResource(...e);return this.plugins?.metrics&&!["metrics","error_logs","performance_logs"].includes(t.name)&&this.plugins.metrics.installResourceHooks(t),t}}installResourceHooks(e){e._insert=e.insert,e._update=e.update,e._delete=e.delete,e._deleteMany=e.deleteMany,e._get=e.get,e._getMany=e.getMany,e._getAll=e.getAll,e._list=e.list,e._listIds=e.listIds,e._count=e.count,e._page=e.page,e.insert=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._insert(...t));if(this.recordOperation(e.name,"insert",Date.now()-r,!n),n||this.recordError(e.name,"insert",i),!n)throw i;return o}.bind(this),e.update=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._update(...t));if(this.recordOperation(e.name,"update",Date.now()-r,!n),n||this.recordError(e.name,"update",i),!n)throw i;return o}.bind(this),e.delete=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._delete(...t));if(this.recordOperation(e.name,"delete",Date.now()-r,!n),n||this.recordError(e.name,"delete",i),!n)throw i;return o}.bind(this),e.deleteMany=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._deleteMany(...t));if(this.recordOperation(e.name,"delete",Date.now()-r,!n),n||this.recordError(e.name,"delete",i),!n)throw i;return o}.bind(this),e.get=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._get(...t));if(this.recordOperation(e.name,"get",Date.now()-r,!n),n||this.recordError(e.name,"get",i),!n)throw i;return o}.bind(this),e.getMany=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._getMany(...t));if(this.recordOperation(e.name,"get",Date.now()-r,!n),n||this.recordError(e.name,"get",i),!n)throw i;return o}.bind(this),e.getAll=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._getAll(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!n),n||this.recordError(e.name,"list",i),!n)throw i;return o}.bind(this),e.list=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._list(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!n),n||this.recordError(e.name,"list",i),!n)throw i;return o}.bind(this),e.listIds=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._listIds(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!n),n||this.recordError(e.name,"list",i),!n)throw i;return o}.bind(this),e.count=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._count(...t));if(this.recordOperation(e.name,"count",Date.now()-r,!n),n||this.recordError(e.name,"count",i),!n)throw i;return o}.bind(this),e.page=async function(...t){const r=Date.now(),[n,i,o]=await G(()=>e._page(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!n),n||this.recordError(e.name,"list",i),!n)throw i;return o}.bind(this)}recordOperation(e,t,r,n){this.metrics.operations[t]&&(this.metrics.operations[t].count++,this.metrics.operations[t].totalTime+=r,n&&this.metrics.operations[t].errors++),this.metrics.resources[e]||(this.metrics.resources[e]={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[e][t]&&(this.metrics.resources[e][t].count++,this.metrics.resources[e][t].totalTime+=r,n&&this.metrics.resources[e][t].errors++),this.config.collectPerformance&&this.metrics.performance.push({resourceName:e,operation:t,duration:r,timestamp:(new Date).toISOString()})}recordError(e,t,r){this.config.collectErrors&&this.metrics.errors.push({resourceName:e,operation:t,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(console.error)},this.config.flushInterval))}async flushMetrics(){if(!this.metricsResource)return;const[e,t]=await G(async()=>{const e="test"===process.env.NODE_ENV?{}:{global:"true"},t="test"===process.env.NODE_ENV?{}:{perf:"true"},r="test"===process.env.NODE_ENV?{}:{error:"true"},n="test"===process.env.NODE_ENV?{}:{resource:"true"};for(const[t,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:t,count:r.count,totalTime:r.totalTime,errors:r.errors,avgTime:r.count>0?r.totalTime/r.count:0,timestamp:(new Date).toISOString(),metadata:e});for(const[e,t]of Object.entries(this.metrics.resources))for(const[r,i]of Object.entries(t))i.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:e,operation:r,count:i.count,totalTime:i.totalTime,errors:i.errors,avgTime:i.count>0?i.totalTime/i.count:0,timestamp:(new Date).toISOString(),metadata:n});if(this.config.collectPerformance&&this.metrics.performance.length>0)for(const e of this.metrics.performance)await this.performanceResource.insert({id:`perf-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e.resourceName,operation:e.operation,duration:e.duration,timestamp:e.timestamp,metadata:t});if(this.config.collectErrors&&this.metrics.errors.length>0)for(const e of this.metrics.errors)await this.errorsResource.insert({id:`error-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e.resourceName,operation:e.operation,error:e.error,stack:e.stack,timestamp:e.timestamp,metadata:r});this.resetMetrics()});e||console.error("Failed to flush metrics:",t)}resetMetrics(){for(const e of Object.keys(this.metrics.operations))this.metrics.operations[e]={count:0,totalTime:0,errors:0};for(const e of Object.keys(this.metrics.resources))for(const t of Object.keys(this.metrics.resources[e]))this.metrics.resources[e][t]={count:0,totalTime:0,errors:0};this.metrics.performance=[],this.metrics.errors=[]}async getMetrics(e={}){const{type:t="operation",resourceName:r,operation:n,startDate:i,endDate:o,limit:s=100,offset:a=0}=e;if(!this.metricsResource)return[];let c=(await this.metricsResource.getAll()).filter(e=>(!t||e.type===t)&&((!r||e.resourceName===r)&&((!n||e.operation===n)&&(!(i&&new Date(e.timestamp)<new Date(i))&&!(o&&new Date(e.timestamp)>new Date(o))))));return c.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),c.slice(a,a+s)}async getErrorLogs(e={}){if(!this.errorsResource)return[];const{resourceName:t,operation:r,startDate:n,endDate:i,limit:o=100,offset:s=0}=e;let a=(await this.errorsResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&(!(n&&new Date(e.timestamp)<new Date(n))&&!(i&&new Date(e.timestamp)>new Date(i)))));return a.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),a.slice(s,s+o)}async getPerformanceLogs(e={}){if(!this.performanceResource)return[];const{resourceName:t,operation:r,startDate:n,endDate:i,limit:o=100,offset:s=0}=e;let a=(await this.performanceResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&(!(n&&new Date(e.timestamp)<new Date(n))&&!(i&&new Date(e.timestamp)>new Date(i)))));return a.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),a.slice(s,s+o)}async getStats(){const e=new Date,t=new Date(e.getTime()-864e5),[r,n,i]=await Promise.all([this.getMetrics({startDate:t.toISOString()}),this.getErrorLogs({startDate:t.toISOString()}),this.getPerformanceLogs({startDate:t.toISOString()})]),o={period:"24h",totalOperations:0,totalErrors:n.length,avgResponseTime:0,operationsByType:{},resources:{},uptime:{startTime:this.metrics.startTime,duration:e.getTime()-new Date(this.metrics.startTime).getTime()}};for(const e of r)if("operation"===e.type){o.totalOperations+=e.count,o.operationsByType[e.operation]||(o.operationsByType[e.operation]={count:0,errors:0,avgTime:0}),o.operationsByType[e.operation].count+=e.count,o.operationsByType[e.operation].errors+=e.errors;const t=o.operationsByType[e.operation],r=t.count,n=(t.avgTime*(r-e.count)+e.totalTime)/r;t.avgTime=n}const s=r.reduce((e,t)=>e+t.totalTime,0),a=r.reduce((e,t)=>e+t.count,0);return o.avgResponseTime=a>0?s/a:0,o}async cleanupOldData(){const e=new Date;if(e.setDate(e.getDate()-this.config.retentionDays),this.metricsResource){const t=await this.getMetrics({endDate:e.toISOString()});for(const e of t)await this.metricsResource.delete(e.id)}if(this.errorsResource){const t=await this.getErrorLogs({endDate:e.toISOString()});for(const e of t)await this.errorsResource.delete(e.id)}if(this.performanceResource){const t=await this.getPerformanceLogs({endDate:e.toISOString()});for(const e of t)await this.performanceResource.delete(e.id)}}}var vs="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Es(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Is(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if("function"==typeof t){var r=function e(){var r=!1;try{r=this instanceof e}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var _s,As,ks={},Bs={};var xs,Ss,Os,Us={};function Cs(){if(Os)return Ss;Os=1;var e=As?_s:(As=1,_s=function(e,t){if(t=t.split(":")[0],!(e=+e))return!1;switch(t){case"http":case"ws":return 80!==e;case"https":case"wss":return 443!==e;case"ftp":return 21!==e;case"gopher":return 70!==e;case"file":return!1}return 0!==e}),t=function(){if(xs)return Us;xs=1;var e=Object.prototype.hasOwnProperty;function t(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(e){return null}}function r(e){try{return encodeURIComponent(e)}catch(e){return null}}return Us.stringify=function(t,n){n=n||"";var i,o,s=[];for(o in"string"!=typeof n&&(n="?"),t)if(e.call(t,o)){if((i=t[o])||null!=i&&!isNaN(i)||(i=""),o=r(o),i=r(i),null===o||null===i)continue;s.push(o+"="+i)}return s.length?n+s.join("&"):""},Us.parse=function(e){for(var r,n=/([^=?#&]+)=?([^&]*)/g,i={};r=n.exec(e);){var o=t(r[1]),s=t(r[2]);null===o||null===s||o in i||(i[o]=s)}return i},Us}(),r=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,n=/[\n\r\t]/g,i=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o=/:\d+$/,s=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,a=/^[a-zA-Z]:/;function c(e){return(e||"").toString().replace(r,"")}var u=[["#","hash"],["?","query"],function(e,t){return f(t.protocol)?e.replace(/\\/g,"/"):e},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],l={hash:1,query:1};function h(e){var t,r=("undefined"!=typeof window?window:void 0!==vs?vs:"undefined"!=typeof self?self:{}).location||{},n={},o=typeof(e=e||r);if("blob:"===e.protocol)n=new p(unescape(e.pathname),{});else if("string"===o)for(t in n=new p(e,{}),l)delete n[t];else if("object"===o){for(t in e)t in l||(n[t]=e[t]);void 0===n.slashes&&(n.slashes=i.test(e.href))}return n}function f(e){return"file:"===e||"ftp:"===e||"http:"===e||"https:"===e||"ws:"===e||"wss:"===e}function d(e,t){e=(e=c(e)).replace(n,""),t=t||{};var r,i=s.exec(e),o=i[1]?i[1].toLowerCase():"",a=!!i[2],u=!!i[3],l=0;return a?u?(r=i[2]+i[3]+i[4],l=i[2].length+i[3].length):(r=i[2]+i[4],l=i[2].length):u?(r=i[3]+i[4],l=i[3].length):r=i[4],"file:"===o?l>=2&&(r=r.slice(2)):f(o)?r=i[4]:o?a&&(r=r.slice(2)):l>=2&&f(t.protocol)&&(r=i[4]),{protocol:o,slashes:a||f(o),slashesCount:l,rest:r}}function p(r,i,o){if(r=(r=c(r)).replace(n,""),!(this instanceof p))return new p(r,i,o);var s,l,g,m,y,w,b=u.slice(),v=typeof i,E=this,I=0;for("object"!==v&&"string"!==v&&(o=i,i=null),o&&"function"!=typeof o&&(o=t.parse),s=!(l=d(r||"",i=h(i))).protocol&&!l.slashes,E.slashes=l.slashes||s&&i.slashes,E.protocol=l.protocol||i.protocol||"",r=l.rest,("file:"===l.protocol&&(2!==l.slashesCount||a.test(r))||!l.slashes&&(l.protocol||l.slashesCount<2||!f(E.protocol)))&&(b[3]=[/(.*)/,"pathname"]);I<b.length;I++)"function"!=typeof(m=b[I])?(g=m[0],w=m[1],g!=g?E[w]=r:"string"==typeof g?~(y="@"===g?r.lastIndexOf(g):r.indexOf(g))&&("number"==typeof m[2]?(E[w]=r.slice(0,y),r=r.slice(y+m[2])):(E[w]=r.slice(y),r=r.slice(0,y))):(y=g.exec(r))&&(E[w]=y[1],r=r.slice(0,y.index)),E[w]=E[w]||s&&m[3]&&i[w]||"",m[4]&&(E[w]=E[w].toLowerCase())):r=m(r,E);o&&(E.query=o(E.query)),s&&i.slashes&&"/"!==E.pathname.charAt(0)&&(""!==E.pathname||""!==i.pathname)&&(E.pathname=function(e,t){if(""===e)return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,s=0;n--;)"."===r[n]?r.splice(n,1):".."===r[n]?(r.splice(n,1),s++):s&&(0===n&&(o=!0),r.splice(n,1),s--);return o&&r.unshift(""),"."!==i&&".."!==i||r.push(""),r.join("/")}(E.pathname,i.pathname)),"/"!==E.pathname.charAt(0)&&f(E.protocol)&&(E.pathname="/"+E.pathname),e(E.port,E.protocol)||(E.host=E.hostname,E.port=""),E.username=E.password="",E.auth&&(~(y=E.auth.indexOf(":"))?(E.username=E.auth.slice(0,y),E.username=encodeURIComponent(decodeURIComponent(E.username)),E.password=E.auth.slice(y+1),E.password=encodeURIComponent(decodeURIComponent(E.password))):E.username=encodeURIComponent(decodeURIComponent(E.auth)),E.auth=E.password?E.username+":"+E.password:E.username),E.origin="file:"!==E.protocol&&f(E.protocol)&&E.host?E.protocol+"//"+E.host:"null",E.href=E.toString()}return p.prototype={set:function(r,n,i){var s=this;switch(r){case"query":"string"==typeof n&&n.length&&(n=(i||t.parse)(n)),s[r]=n;break;case"port":s[r]=n,e(n,s.protocol)?n&&(s.host=s.hostname+":"+n):(s.host=s.hostname,s[r]="");break;case"hostname":s[r]=n,s.port&&(n+=":"+s.port),s.host=n;break;case"host":s[r]=n,o.test(n)?(n=n.split(":"),s.port=n.pop(),s.hostname=n.join(":")):(s.hostname=n,s.port="");break;case"protocol":s.protocol=n.toLowerCase(),s.slashes=!i;break;case"pathname":case"hash":if(n){var a="pathname"===r?"/":"#";s[r]=n.charAt(0)!==a?a+n:n}else s[r]=n;break;case"username":case"password":s[r]=encodeURIComponent(n);break;case"auth":var c=n.indexOf(":");~c?(s.username=n.slice(0,c),s.username=encodeURIComponent(decodeURIComponent(s.username)),s.password=n.slice(c+1),s.password=encodeURIComponent(decodeURIComponent(s.password))):s.username=encodeURIComponent(decodeURIComponent(n))}for(var l=0;l<u.length;l++){var h=u[l];h[4]&&(s[h[1]]=s[h[1]].toLowerCase())}return s.auth=s.password?s.username+":"+s.password:s.username,s.origin="file:"!==s.protocol&&f(s.protocol)&&s.host?s.protocol+"//"+s.host:"null",s.href=s.toString(),s},toString:function(e){e&&"function"==typeof e||(e=t.stringify);var r,n=this,i=n.host,s=n.protocol;s&&":"!==s.charAt(s.length-1)&&(s+=":");var a=s+(n.protocol&&n.slashes||f(n.protocol)?"//":"");return n.username?(a+=n.username,n.password&&(a+=":"+n.password),a+="@"):n.password?(a+=":"+n.password,a+="@"):"file:"!==n.protocol&&f(n.protocol)&&!i&&"/"!==n.pathname&&(a+="@"),(":"===i[i.length-1]||o.test(n.hostname)&&!n.port)&&(i+=":"),a+=i+n.pathname,(r="object"==typeof n.query?e(n.query):n.query)&&(a+="?"!==r.charAt(0)?"?"+r:r),n.hash&&(a+=n.hash),a}},p.extractProtocol=d,p.location=h,p.trimLeft=c,p.qs=t,Ss=p}function Ns(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var Rs=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function Ts(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}}function Ls(e,t,r,n){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?Ds(js(e),function(n){var i=encodeURIComponent(Ts(n))+r;return Rs(e[n])?Ds(e[n],function(e){return i+encodeURIComponent(Ts(e))}).join(t):i+encodeURIComponent(Ts(e[n]))}).join(t):n?encodeURIComponent(Ts(n))+r+encodeURIComponent(Ts(e)):""}function Ds(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n<e.length;n++)r.push(t(e[n],n));return r}var js=Object.keys||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t};function Ms(e,t,r,n){t=t||"&",r=r||"=";var i={};if("string"!=typeof e||0===e.length)return i;var o=/\+/g;e=e.split(t);var s=1e3;n&&"number"==typeof n.maxKeys&&(s=n.maxKeys);var a=e.length;s>0&&a>s&&(a=s);for(var c=0;c<a;++c){var u,l,h,f,d=e[c].replace(o,"%20"),p=d.indexOf(r);p>=0?(u=d.substr(0,p),l=d.substr(p+1)):(u=d,l=""),h=decodeURIComponent(u),f=decodeURIComponent(l),Ns(i,h)?Rs(i[h])?i[h].push(f):i[h]=[i[h],f]:i[h]=f}return i}var Ps,Fs,qs,Qs={encode:Ls,stringify:Ls,decode:Ms,parse:Ms},zs=Is(Object.freeze({__proto__:null,decode:Ms,default:Qs,encode:Ls,parse:Ms,stringify:Ls})),$s={},Hs={},Vs={},Gs={exports:{}};function Ks(){return Ps||(Ps=1,function(e){var t=4294967296,r=1/t,n=9007199254740991;function i(e){return e<=n&&e>=-n}function o(e,t,r){if("number"!=typeof(e=+e)||e<t||e>r||Math.floor(e)!==e)throw new TypeError('"value" argument is out of bounds');return e}function s(e,t,r){if(t<0||t+r>e.length)throw new RangeError("Index out of range")}e.exports.isContiguousInt=i,e.exports.assertContiguousInt=function(e){if(!i(e))throw new TypeError("number cannot be represented as a contiguous integer")},["UInt","Int"].forEach(function(t){var r=t+"8";e.exports["read"+r]=_t.prototype["read"+r].call,e.exports["write"+r]=_t.prototype["write"+r].call,["16","32"].forEach(function(r){["LE","BE"].forEach(function(n){var i=t+r+n,o=_t.prototype["read"+i];e.exports["read"+i]=function(e,t){return o.call(e,t)};var s=_t.prototype["write"+i];e.exports["write"+i]=function(e,t,r){return s.call(e,t,r)}})})}),e.exports.readUInt24BE=function(e,t){return e.readUInt8(t)<<16|e.readUInt16BE(t+1)},e.exports.writeUInt24BE=function(e,t,r){t=o(t,0,16777215),s(e,r,3),e.writeUInt8(t>>>16,r),e.writeUInt16BE(65535&t,r+1)},e.exports.readUInt40BE=function(e,r){return(e.readUInt8(r)||0)*t+e.readUInt32BE(r+1)},e.exports.writeUInt40BE=function(e,t,n){t=o(t,0,0xffffffffff),s(e,n,5),e.writeUInt8(Math.floor(t*r),n),e.writeInt32BE(-1&t,n+1)},e.exports.readUInt48BE=function(e,r){return e.readUInt16BE(r)*t+e.readUInt32BE(r+2)},e.exports.writeUInt48BE=function(e,t,n){t=o(t,0,0xffffffffffff),s(e,n,6),e.writeUInt16BE(Math.floor(t*r),n),e.writeInt32BE(-1&t,n+2)},e.exports.readUInt56BE=function(e,r){return((e.readUInt8(r)||0)<<16|e.readUInt16BE(r+1))*t+e.readUInt32BE(r+3)},e.exports.writeUInt56BE=function(e,t,n){if(t=o(t,0,72057594037927940),s(e,n,7),t<72057594037927940){var i=Math.floor(t*r);e.writeUInt8(i>>>16,n),e.writeUInt16BE(65535&i,n+1),e.writeInt32BE(-1&t,n+3)}else e[n]=255,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=255},e.exports.readUInt64BE=function(e,r){return e.readUInt32BE(r)*t+e.readUInt32BE(r+4)},e.exports.writeUInt64BE=function(e,t,n){t=o(t,0,0x10000000000000000),s(e,n,8),t<0x10000000000000000?(e.writeUInt32BE(Math.floor(t*r),n),e.writeInt32BE(-1&t,n+4)):(e[n]=255,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=255,e[n+7]=255)},e.exports.readUInt24LE=function(e,t){return e.readUInt8(t+2)<<16|e.readUInt16LE(t)},e.exports.writeUInt24LE=function(e,t,r){t=o(t,0,16777215),s(e,r,3),e.writeUInt16LE(65535&t,r),e.writeUInt8(t>>>16,r+2)},e.exports.readUInt40LE=function(e,r){return(e.readUInt8(r+4)||0)*t+e.readUInt32LE(r)},e.exports.writeUInt40LE=function(e,t,n){t=o(t,0,0xffffffffff),s(e,n,5),e.writeInt32LE(-1&t,n),e.writeUInt8(Math.floor(t*r),n+4)},e.exports.readUInt48LE=function(e,r){return e.readUInt16LE(r+4)*t+e.readUInt32LE(r)},e.exports.writeUInt48LE=function(e,t,n){t=o(t,0,0xffffffffffff),s(e,n,6),e.writeInt32LE(-1&t,n),e.writeUInt16LE(Math.floor(t*r),n+4)},e.exports.readUInt56LE=function(e,r){return((e.readUInt8(r+6)||0)<<16|e.readUInt16LE(r+4))*t+e.readUInt32LE(r)},e.exports.writeUInt56LE=function(e,t,n){if(t=o(t,0,72057594037927940),s(e,n,7),t<72057594037927940){e.writeInt32LE(-1&t,n);var i=Math.floor(t*r);e.writeUInt16LE(65535&i,n+4),e.writeUInt8(i>>>16,n+6)}else e[n]=255,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=255},e.exports.readUInt64LE=function(e,r){return e.readUInt32LE(r+4)*t+e.readUInt32LE(r)},e.exports.writeUInt64LE=function(e,t,n){t=o(t,0,0x10000000000000000),s(e,n,8),t<0x10000000000000000?(e.writeInt32LE(-1&t,n),e.writeUInt32LE(Math.floor(t*r),n+4)):(e[n]=255,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=255,e[n+7]=255)},e.exports.readInt24BE=function(e,t){return(e.readInt8(t)<<16)+e.readUInt16BE(t+1)},e.exports.writeInt24BE=function(e,t,r){t=o(t,-8388608,8388607),s(e,r,3),e.writeInt8(t>>16,r),e.writeUInt16BE(65535&t,r+1)},e.exports.readInt40BE=function(e,r){return(e.readInt8(r)||0)*t+e.readUInt32BE(r+1)},e.exports.writeInt40BE=function(e,t,n){t=o(t,-549755813888,549755813887),s(e,n,5),e.writeInt8(Math.floor(t*r),n),e.writeInt32BE(-1&t,n+1)},e.exports.readInt48BE=function(e,r){return e.readInt16BE(r)*t+e.readUInt32BE(r+2)},e.exports.writeInt48BE=function(e,t,n){t=o(t,-0x800000000000,0x7fffffffffff),s(e,n,6),e.writeInt16BE(Math.floor(t*r),n),e.writeInt32BE(-1&t,n+2)},e.exports.readInt56BE=function(e,r){return(((e.readInt8(r)||0)<<16)+e.readUInt16BE(r+1))*t+e.readUInt32BE(r+3)},e.exports.writeInt56BE=function(e,t,n){if(t=o(t,-0x800000000000000,0x80000000000000),s(e,n,7),t<0x80000000000000){var i=Math.floor(t*r);e.writeInt8(i>>16,n),e.writeUInt16BE(65535&i,n+1),e.writeInt32BE(-1&t,n+3)}else e[n]=127,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=255},e.exports.readInt64BE=function(e,r){return e.readInt32BE(r)*t+e.readUInt32BE(r+4)},e.exports.writeInt64BE=function(e,t,n){t=o(t,-23611832414348226e5,0x8000000000000000),s(e,n,8),t<0x8000000000000000?(e.writeInt32BE(Math.floor(t*r),n),e.writeInt32BE(-1&t,n+4)):(e[n]=127,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=255,e[n+7]=255)},e.exports.readInt24LE=function(e,t){return(e.readInt8(t+2)<<16)+e.readUInt16LE(t)},e.exports.writeInt24LE=function(e,t,r){t=o(t,-8388608,8388607),s(e,r,3),e.writeUInt16LE(65535&t,r),e.writeInt8(t>>16,r+2)},e.exports.readInt40LE=function(e,r){return(e.readInt8(r+4)||0)*t+e.readUInt32LE(r)},e.exports.writeInt40LE=function(e,t,n){t=o(t,-549755813888,549755813887),s(e,n,5),e.writeInt32LE(-1&t,n),e.writeInt8(Math.floor(t*r),n+4)},e.exports.readInt48LE=function(e,r){return e.readInt16LE(r+4)*t+e.readUInt32LE(r)},e.exports.writeInt48LE=function(e,t,n){t=o(t,-0x800000000000,0x7fffffffffff),s(e,n,6),e.writeInt32LE(-1&t,n),e.writeInt16LE(Math.floor(t*r),n+4)},e.exports.readInt56LE=function(e,r){return(((e.readInt8(r+6)||0)<<16)+e.readUInt16LE(r+4))*t+e.readUInt32LE(r)},e.exports.writeInt56LE=function(e,t,n){if(t=o(t,-0x80000000000000,0x80000000000000),s(e,n,7),t<0x80000000000000){e.writeInt32LE(-1&t,n);var i=Math.floor(t*r);e.writeUInt16LE(65535&i,n+4),e.writeInt8(i>>16,n+6)}else e[n]=255,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=127},e.exports.readInt64LE=function(e,r){return e.readInt32LE(r+4)*t+e.readUInt32LE(r)},e.exports.writeInt64LE=function(e,t,n){t=o(t,-0x8000000000000000,0x8000000000000000),s(e,n,8),t<0x8000000000000000?(e.writeInt32LE(-1&t,n),e.writeInt32LE(Math.floor(t*r),n+4)):(e[n]=255,e[n+1]=255,e[n+2]=255,e[n+3]=255,e[n+4]=255,e[n+5]=255,e[n+6]=255,e[n+7]=127)}}(Gs)),Gs.exports}function Ws(){if(Fs)return Vs;Fs=1;var e=Ks();function t(e,t,n){var i=n;for(var o in n+=4,t)if(void 0!==t[o]){var s=_t.byteLength(o);e.writeUInt8(s,n),n++,e.write(o,n,"utf8"),n+=s,n+=r(e,t[o],n)}var a=n-i;return e.writeUInt32BE(a-4,i),a}function r(n,i,o){var s,a=o,c=typeof i,u=i;function l(e){n.write(e,o),o++}switch(i&&"object"===c&&i.hasOwnProperty("!")&&(u=i.value,c=i["!"]),"number"==c&&(c=(s=u)>=0x8000000000000000||Math.abs(s)<0x4000000000000&&Math.floor(s)!==s?"double":u<128&&u>=-128?"byte":u>=-32768&&u<32768?"short":u>=-2147483648&&u<2147483648?"int":"long"),c){case"string":var h=_t.byteLength(u,"utf8");l("S"),n.writeUInt32BE(h,o),o+=4,n.write(u,o,"utf8"),o+=h;break;case"object":null===u?l("V"):Array.isArray(u)?(l("A"),o+=function(e,t,n){var i=n;n+=4;for(var o=0,s=t.length;o<s;o++)n+=r(e,t[o],n);var a=n-i;return e.writeUInt32BE(a-4,i),a}(n,u,o)):_t.isBuffer(u)?(l("x"),n.writeUInt32BE(u.length,o),o+=4,u.copy(n,o),o+=u.length):(l("F"),o+=t(n,u,o));break;case"boolean":l("t"),n.writeUInt8(u?1:0,o),o++;break;case"double":case"float64":l("d"),n.writeDoubleBE(u,o),o+=8;break;case"byte":case"int8":l("b"),n.writeInt8(u,o),o++;break;case"unsignedbyte":case"uint8":l("B"),n.writeUInt8(u,o),o++;break;case"short":case"int16":l("s"),n.writeInt16BE(u,o),o+=2;break;case"unsignedshort":case"uint16":l("u"),n.writeUInt16BE(u,o),o+=2;break;case"int":case"int32":l("I"),n.writeInt32BE(u,o),o+=4;break;case"unsignedint":case"uint32":l("i"),n.writeUInt32BE(u,o),o+=4;break;case"long":case"int64":l("l"),e.writeInt64BE(n,u,o),o+=8;break;case"timestamp":l("T"),e.writeUInt64BE(n,u,o),o+=8;break;case"float":l("f"),n.writeFloatBE(u,o),o+=4;break;case"decimal":if(l("D"),!(u.hasOwnProperty("places")&&u.hasOwnProperty("digits")&&u.places>=0&&u.places<256))throw new TypeError("Decimal value must be {'places': 0..255, 'digits': uint32}, got "+JSON.stringify(u));n[o]=u.places,o++,n.writeUInt32BE(u.digits,o),o+=4;break;default:throw new TypeError("Unknown type to encode: "+c)}return o-a}return Vs.encodeTable=t,Vs.decodeFields=function t(r){var n,i,o,s={},a=0,c=r.length;function u(){var i=String.fromCharCode(r[a]);switch(a++,i){case"b":o=r.readInt8(a),a++;break;case"B":o=r.readUInt8(a),a++;break;case"S":n=r.readUInt32BE(a),a+=4,o=r.toString("utf8",a,a+n),a+=n;break;case"I":o=r.readInt32BE(a),a+=4;break;case"i":o=r.readUInt32BE(a),a+=4;break;case"D":var s=r[a];a++;var c=r.readUInt32BE(a);a+=4,o={"!":"decimal",value:{places:s,digits:c}};break;case"T":o=e.readUInt64BE(r,a),a+=8,o={"!":"timestamp",value:o};break;case"F":n=r.readUInt32BE(a),a+=4,o=t(r.subarray(a,a+n)),a+=n;break;case"A":n=r.readUInt32BE(a),function(e){var t=[];for(;a<e;)u(),t.push(o);o=t}((a+=4)+n);break;case"d":o=r.readDoubleBE(a),a+=8;break;case"f":o=r.readFloatBE(a),a+=4;break;case"l":o=e.readInt64BE(r,a),a+=8;break;case"s":o=r.readInt16BE(a),a+=2;break;case"u":o=r.readUInt16BE(a),a+=2;break;case"t":o=0!=r[a],a++;break;case"V":o=null;break;case"x":n=r.readUInt32BE(a),a+=4,o=r.subarray(a,a+n),a+=n;break;default:throw new TypeError('Unexpected type tag "'+i+'"')}}for(;a<c;)n=r.readUInt8(a),a++,i=r.toString("utf8",a,a+n),a+=n,u(),s[i]=o;return s},Vs}function Js(){if(qs)return Hs;qs=1;var e=Ws(),t=Ks(),r=e.encodeTable,n=e.decodeFields,i=_t.alloc(65536);Hs.constants={FRAME_METHOD:1,FRAME_HEADER:2,FRAME_BODY:3,FRAME_HEARTBEAT:8,FRAME_MIN_SIZE:4096,FRAME_END:206,REPLY_SUCCESS:200,CONTENT_TOO_LARGE:311,NO_ROUTE:312,NO_CONSUMERS:313,ACCESS_REFUSED:403,NOT_FOUND:404,RESOURCE_LOCKED:405,PRECONDITION_FAILED:406,CONNECTION_FORCED:320,INVALID_PATH:402,FRAME_ERROR:501,SYNTAX_ERROR:502,COMMAND_INVALID:503,CHANNEL_ERROR:504,UNEXPECTED_FRAME:505,RESOURCE_ERROR:506,NOT_ALLOWED:530,NOT_IMPLEMENTED:540,INTERNAL_ERROR:541},Hs.constant_strs={1:"FRAME-METHOD",2:"FRAME-HEADER",3:"FRAME-BODY",8:"FRAME-HEARTBEAT",200:"REPLY-SUCCESS",206:"FRAME-END",311:"CONTENT-TOO-LARGE",312:"NO-ROUTE",313:"NO-CONSUMERS",320:"CONNECTION-FORCED",402:"INVALID-PATH",403:"ACCESS-REFUSED",404:"NOT-FOUND",405:"RESOURCE-LOCKED",406:"PRECONDITION-FAILED",501:"FRAME-ERROR",502:"SYNTAX-ERROR",503:"COMMAND-INVALID",504:"CHANNEL-ERROR",505:"UNEXPECTED-FRAME",506:"RESOURCE-ERROR",530:"NOT-ALLOWED",540:"NOT-IMPLEMENTED",541:"INTERNAL-ERROR",4096:"FRAME-MIN-SIZE"},Hs.FRAME_OVERHEAD=8,Hs.decode=function(e,r){switch(e){case 3932170:return s=0,a={prefetchSize:void 0,prefetchCount:void 0,global:void 0},o=(i=r).readUInt32BE(s),s+=4,a.prefetchSize=o,o=i.readUInt16BE(s),s+=2,a.prefetchCount=o,o=!!(1&i[s]),a.global=o,a;case 3932171:case 3932271:case 655411:case 655421:case 655431:case 1310761:case 2621451:case 2621461:case 2621471:case 2621491:case 3276821:case 3276851:case 5898250:case 5898251:case 5898260:case 5898261:case 5898270:case 5898271:case 5570571:return{};case 3932180:return function(e){var t,r,i=0,o={ticket:void 0,queue:void 0,consumerTag:void 0,noLocal:void 0,noAck:void 0,exclusive:void 0,nowait:void 0,arguments:void 0};return t=e.readUInt16BE(i),i+=2,o.ticket=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.queue=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.consumerTag=t,t=!!(1&e[i]),o.noLocal=t,t=!!(2&e[i]),o.noAck=t,t=!!(4&e[i]),o.exclusive=t,t=!!(8&e[i]),o.nowait=t,i++,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.arguments=t,o}(r);case 3932181:return function(e){var t,r,n=0,i={consumerTag:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.consumerTag=t,i}(r);case 3932190:return function(e){var t,r,n=0,i={consumerTag:void 0,nowait:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.consumerTag=t,t=!!(1&e[n]),i.nowait=t,i}(r);case 3932191:return function(e){var t,r,n=0,i={consumerTag:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.consumerTag=t,i}(r);case 3932200:return function(e){var t,r,n=0,i={ticket:void 0,exchange:void 0,routingKey:void 0,mandatory:void 0,immediate:void 0};return t=e.readUInt16BE(n),n+=2,i.ticket=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.exchange=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.routingKey=t,t=!!(1&e[n]),i.mandatory=t,t=!!(2&e[n]),i.immediate=t,i}(r);case 3932210:return function(e){var t,r,n=0,i={replyCode:void 0,replyText:void 0,exchange:void 0,routingKey:void 0};return t=e.readUInt16BE(n),n+=2,i.replyCode=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.replyText=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.exchange=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.routingKey=t,i}(r);case 3932220:return function(e){var r,n,i=0,o={consumerTag:void 0,deliveryTag:void 0,redelivered:void 0,exchange:void 0,routingKey:void 0};return n=e.readUInt8(i),i++,r=e.toString("utf8",i,i+n),i+=n,o.consumerTag=r,r=t.readUInt64BE(e,i),i+=8,o.deliveryTag=r,r=!!(1&e[i]),o.redelivered=r,i++,n=e.readUInt8(i),i++,r=e.toString("utf8",i,i+n),i+=n,o.exchange=r,n=e.readUInt8(i),i++,r=e.toString("utf8",i,i+n),i+=n,o.routingKey=r,o}(r);case 3932230:return function(e){var t,r,n=0,i={ticket:void 0,queue:void 0,noAck:void 0};return t=e.readUInt16BE(n),n+=2,i.ticket=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.queue=t,t=!!(1&e[n]),i.noAck=t,i}(r);case 3932231:return function(e){var r,n,i=0,o={deliveryTag:void 0,redelivered:void 0,exchange:void 0,routingKey:void 0,messageCount:void 0};return r=t.readUInt64BE(e,i),i+=8,o.deliveryTag=r,r=!!(1&e[i]),o.redelivered=r,i++,n=e.readUInt8(i),i++,r=e.toString("utf8",i,i+n),i+=n,o.exchange=r,n=e.readUInt8(i),i++,r=e.toString("utf8",i,i+n),i+=n,o.routingKey=r,r=e.readUInt32BE(i),i+=4,o.messageCount=r,o}(r);case 3932232:return function(e){var t,r,n=0,i={clusterId:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.clusterId=t,i}(r);case 3932240:return function(e){var r,n=0,i={deliveryTag:void 0,multiple:void 0};return r=t.readUInt64BE(e,n),n+=8,i.deliveryTag=r,r=!!(1&e[n]),i.multiple=r,i}(r);case 3932250:return function(e){var r,n=0,i={deliveryTag:void 0,requeue:void 0};return r=t.readUInt64BE(e,n),n+=8,i.deliveryTag=r,r=!!(1&e[n]),i.requeue=r,i}(r);case 3932260:return function(e){var t,r={requeue:void 0};return t=!!(1&e[0]),r.requeue=t,r}(r);case 3932270:return function(e){var t,r={requeue:void 0};return t=!!(1&e[0]),r.requeue=t,r}(r);case 3932280:return function(e){var r,n=0,i={deliveryTag:void 0,multiple:void 0,requeue:void 0};return r=t.readUInt64BE(e,n),n+=8,i.deliveryTag=r,r=!!(1&e[n]),i.multiple=r,r=!!(2&e[n]),i.requeue=r,i}(r);case 655370:return function(e){var t,r,i=0,o={versionMajor:void 0,versionMinor:void 0,serverProperties:void 0,mechanisms:void 0,locales:void 0};return t=e[i],i++,o.versionMajor=t,t=e[i],i++,o.versionMinor=t,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.serverProperties=t,r=e.readUInt32BE(i),i+=4,t=e.subarray(i,i+r),i+=r,o.mechanisms=t,r=e.readUInt32BE(i),i+=4,t=e.subarray(i,i+r),i+=r,o.locales=t,o}(r);case 655371:return function(e){var t,r,i=0,o={clientProperties:void 0,mechanism:void 0,response:void 0,locale:void 0};return r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.clientProperties=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.mechanism=t,r=e.readUInt32BE(i),i+=4,t=e.subarray(i,i+r),i+=r,o.response=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.locale=t,o}(r);case 655380:return function(e){var t,r,n=0,i={challenge:void 0};return r=e.readUInt32BE(n),n+=4,t=e.subarray(n,n+r),n+=r,i.challenge=t,i}(r);case 655381:return function(e){var t,r,n=0,i={response:void 0};return r=e.readUInt32BE(n),n+=4,t=e.subarray(n,n+r),n+=r,i.response=t,i}(r);case 655390:return function(e){var t,r=0,n={channelMax:void 0,frameMax:void 0,heartbeat:void 0};return t=e.readUInt16BE(r),r+=2,n.channelMax=t,t=e.readUInt32BE(r),r+=4,n.frameMax=t,t=e.readUInt16BE(r),r+=2,n.heartbeat=t,n}(r);case 655391:return function(e){var t,r=0,n={channelMax:void 0,frameMax:void 0,heartbeat:void 0};return t=e.readUInt16BE(r),r+=2,n.channelMax=t,t=e.readUInt32BE(r),r+=4,n.frameMax=t,t=e.readUInt16BE(r),r+=2,n.heartbeat=t,n}(r);case 655400:return function(e){var t,r,n=0,i={virtualHost:void 0,capabilities:void 0,insist:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.virtualHost=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.capabilities=t,t=!!(1&e[n]),i.insist=t,i}(r);case 655401:return function(e){var t,r,n=0,i={knownHosts:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.knownHosts=t,i}(r);case 655410:return function(e){var t,r,n=0,i={replyCode:void 0,replyText:void 0,classId:void 0,methodId:void 0};return t=e.readUInt16BE(n),n+=2,i.replyCode=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.replyText=t,t=e.readUInt16BE(n),n+=2,i.classId=t,t=e.readUInt16BE(n),n+=2,i.methodId=t,i}(r);case 655420:return function(e){var t,r,n=0,i={reason:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.reason=t,i}(r);case 655430:return function(e){var t,r,n=0,i={newSecret:void 0,reason:void 0};return r=e.readUInt32BE(n),n+=4,t=e.subarray(n,n+r),n+=r,i.newSecret=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.reason=t,i}(r);case 1310730:return function(e){var t,r,n=0,i={outOfBand:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.outOfBand=t,i}(r);case 1310731:return function(e){var t,r,n=0,i={channelId:void 0};return r=e.readUInt32BE(n),n+=4,t=e.subarray(n,n+r),n+=r,i.channelId=t,i}(r);case 1310740:return function(e){var t,r={active:void 0};return t=!!(1&e[0]),r.active=t,r}(r);case 1310741:return function(e){var t,r={active:void 0};return t=!!(1&e[0]),r.active=t,r}(r);case 1310760:return function(e){var t,r,n=0,i={replyCode:void 0,replyText:void 0,classId:void 0,methodId:void 0};return t=e.readUInt16BE(n),n+=2,i.replyCode=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.replyText=t,t=e.readUInt16BE(n),n+=2,i.classId=t,t=e.readUInt16BE(n),n+=2,i.methodId=t,i}(r);case 1966090:return function(e){var t,r,n=0,i={realm:void 0,exclusive:void 0,passive:void 0,active:void 0,write:void 0,read:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.realm=t,t=!!(1&e[n]),i.exclusive=t,t=!!(2&e[n]),i.passive=t,t=!!(4&e[n]),i.active=t,t=!!(8&e[n]),i.write=t,t=!!(16&e[n]),i.read=t,i}(r);case 1966091:return function(e){var t,r=0,n={ticket:void 0};return t=e.readUInt16BE(r),r+=2,n.ticket=t,n}(r);case 2621450:return function(e){var t,r,i=0,o={ticket:void 0,exchange:void 0,type:void 0,passive:void 0,durable:void 0,autoDelete:void 0,internal:void 0,nowait:void 0,arguments:void 0};return t=e.readUInt16BE(i),i+=2,o.ticket=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.exchange=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.type=t,t=!!(1&e[i]),o.passive=t,t=!!(2&e[i]),o.durable=t,t=!!(4&e[i]),o.autoDelete=t,t=!!(8&e[i]),o.internal=t,t=!!(16&e[i]),o.nowait=t,i++,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.arguments=t,o}(r);case 2621460:return function(e){var t,r,n=0,i={ticket:void 0,exchange:void 0,ifUnused:void 0,nowait:void 0};return t=e.readUInt16BE(n),n+=2,i.ticket=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.exchange=t,t=!!(1&e[n]),i.ifUnused=t,t=!!(2&e[n]),i.nowait=t,i}(r);case 2621470:return function(e){var t,r,i=0,o={ticket:void 0,destination:void 0,source:void 0,routingKey:void 0,nowait:void 0,arguments:void 0};return t=e.readUInt16BE(i),i+=2,o.ticket=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.destination=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.source=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.routingKey=t,t=!!(1&e[i]),o.nowait=t,i++,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.arguments=t,o}(r);case 2621480:return function(e){var t,r,i=0,o={ticket:void 0,destination:void 0,source:void 0,routingKey:void 0,nowait:void 0,arguments:void 0};return t=e.readUInt16BE(i),i+=2,o.ticket=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.destination=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.source=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.routingKey=t,t=!!(1&e[i]),o.nowait=t,i++,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.arguments=t,o}(r);case 3276810:return function(e){var t,r,i=0,o={ticket:void 0,queue:void 0,passive:void 0,durable:void 0,exclusive:void 0,autoDelete:void 0,nowait:void 0,arguments:void 0};return t=e.readUInt16BE(i),i+=2,o.ticket=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.queue=t,t=!!(1&e[i]),o.passive=t,t=!!(2&e[i]),o.durable=t,t=!!(4&e[i]),o.exclusive=t,t=!!(8&e[i]),o.autoDelete=t,t=!!(16&e[i]),o.nowait=t,i++,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.arguments=t,o}(r);case 3276811:return function(e){var t,r,n=0,i={queue:void 0,messageCount:void 0,consumerCount:void 0};return r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.queue=t,t=e.readUInt32BE(n),n+=4,i.messageCount=t,t=e.readUInt32BE(n),n+=4,i.consumerCount=t,i}(r);case 3276820:return function(e){var t,r,i=0,o={ticket:void 0,queue:void 0,exchange:void 0,routingKey:void 0,nowait:void 0,arguments:void 0};return t=e.readUInt16BE(i),i+=2,o.ticket=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.queue=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.exchange=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.routingKey=t,t=!!(1&e[i]),o.nowait=t,i++,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.arguments=t,o}(r);case 3276830:return function(e){var t,r,n=0,i={ticket:void 0,queue:void 0,nowait:void 0};return t=e.readUInt16BE(n),n+=2,i.ticket=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.queue=t,t=!!(1&e[n]),i.nowait=t,i}(r);case 3276831:return function(e){var t,r=0,n={messageCount:void 0};return t=e.readUInt32BE(r),r+=4,n.messageCount=t,n}(r);case 3276840:return function(e){var t,r,n=0,i={ticket:void 0,queue:void 0,ifUnused:void 0,ifEmpty:void 0,nowait:void 0};return t=e.readUInt16BE(n),n+=2,i.ticket=t,r=e.readUInt8(n),n++,t=e.toString("utf8",n,n+r),n+=r,i.queue=t,t=!!(1&e[n]),i.ifUnused=t,t=!!(2&e[n]),i.ifEmpty=t,t=!!(4&e[n]),i.nowait=t,i}(r);case 3276841:return function(e){var t,r=0,n={messageCount:void 0};return t=e.readUInt32BE(r),r+=4,n.messageCount=t,n}(r);case 3276850:return function(e){var t,r,i=0,o={ticket:void 0,queue:void 0,exchange:void 0,routingKey:void 0,arguments:void 0};return t=e.readUInt16BE(i),i+=2,o.ticket=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.queue=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.exchange=t,r=e.readUInt8(i),i++,t=e.toString("utf8",i,i+r),i+=r,o.routingKey=t,r=e.readUInt32BE(i),i+=4,t=n(e.subarray(i,i+r)),i+=r,o.arguments=t,o}(r);case 5570570:return function(e){var t,r={nowait:void 0};return t=!!(1&e[0]),r.nowait=t,r}(r);case 60:return function(e){var r,i,o,s=2;if(0===(r=e.readUInt16BE(0)))return{};var a={contentType:void 0,contentEncoding:void 0,headers:void 0,deliveryMode:void 0,priority:void 0,correlationId:void 0,replyTo:void 0,expiration:void 0,messageId:void 0,timestamp:void 0,type:void 0,userId:void 0,appId:void 0,clusterId:void 0};return 32768&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.contentType=i),16384&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.contentEncoding=i),8192&r&&(o=e.readUInt32BE(s),s+=4,i=n(e.subarray(s,s+o)),s+=o,a.headers=i),4096&r&&(i=e[s],s++,a.deliveryMode=i),2048&r&&(i=e[s],s++,a.priority=i),1024&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.correlationId=i),512&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.replyTo=i),256&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.expiration=i),128&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.messageId=i),64&r&&(i=t.readUInt64BE(e,s),s+=8,a.timestamp=i),32&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.type=i),16&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.userId=i),8&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.appId=i),4&r&&(o=e.readUInt8(s),s++,i=e.toString("utf8",s,s+o),s+=o,a.clusterId=i),a}(r);default:throw new Error("Unknown class/method ID")}var i,o,s,a},Hs.encodeMethod=function(e,n,o){switch(e){case 3932170:return function(e,t){var r=0,n=null,i=0,o=_t.alloc(19);if(o[0]=1,o.writeUInt16BE(e,1),o.writeUInt32BE(3932170,7),r=11,void 0===(n=t.prefetchSize))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'prefetchSize' is the wrong type; must be a number (but not NaN)");if(o.writeUInt32BE(n,r),r+=4,void 0===(n=t.prefetchCount))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'prefetchCount' is the wrong type; must be a number (but not NaN)");return o.writeUInt16BE(n,r),r+=2,void 0===(n=t.global)&&(n=!1),n&&(i+=1),o[r]=i,o[++r]=206,o.writeUInt32BE(r-7,3),o}(n,o);case 3932171:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(3932171,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 3932180:return function(e,t){var n,o=0,s=null,a=0,c=0,u=0;if(void 0===(s=t.queue))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(c+=l,void 0===(s=t.consumerTag))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)");var h=_t.byteLength(s,"utf8");if(c+=h,void 0===(s=t.arguments))s={};else if("object"!=typeof s)throw new TypeError("Field 'arguments' is the wrong type; must be an object");n=r(i,s,u);var f=i.slice(u,u+n);u+=n,c+=f.length;var d=_t.alloc(17+c);if(d[0]=1,d.writeUInt16BE(e,1),d.writeUInt32BE(3932180,7),o=11,void 0===(s=t.ticket))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return d.writeUInt16BE(s,o),o+=2,void 0===(s=t.queue)&&(s=""),d[o]=l,o++,d.write(s,o,"utf8"),o+=l,void 0===(s=t.consumerTag)&&(s=""),d[o]=h,o++,d.write(s,o,"utf8"),o+=h,void 0===(s=t.noLocal)&&(s=!1),s&&(a+=1),void 0===(s=t.noAck)&&(s=!1),s&&(a+=2),void 0===(s=t.exclusive)&&(s=!1),s&&(a+=4),void 0===(s=t.nowait)&&(s=!1),s&&(a+=8),d[o]=a,o++,a=0,d[o+=f.copy(d,o)]=206,d.writeUInt32BE(o-7,3),d}(n,o);case 3932181:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.consumerTag))throw new Error("Missing value for mandatory field 'consumerTag'");if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(13+i);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(3932181,7),r=11,void 0===(n=t.consumerTag)&&(n=void 0),s[r]=o,r++,s.write(n,r,"utf8"),s[r+=o]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 3932190:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.consumerTag))throw new Error("Missing value for mandatory field 'consumerTag'");if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");o+=s;var a=_t.alloc(14+o);return a[0]=1,a.writeUInt16BE(e,1),a.writeUInt32BE(3932190,7),r=11,void 0===(n=t.consumerTag)&&(n=void 0),a[r]=s,r++,a.write(n,r,"utf8"),r+=s,void 0===(n=t.nowait)&&(n=!1),n&&(i+=1),a[r]=i,a[++r]=206,a.writeUInt32BE(r-7,3),a}(n,o);case 3932191:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.consumerTag))throw new Error("Missing value for mandatory field 'consumerTag'");if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(13+i);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(3932191,7),r=11,void 0===(n=t.consumerTag)&&(n=void 0),s[r]=o,r++,s.write(n,r,"utf8"),s[r+=o]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 3932200:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.exchange))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");if(o+=s,void 0===(n=t.routingKey))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var a=_t.byteLength(n,"utf8");o+=a;var c=_t.alloc(17+o);if(c[0]=1,c.writeUInt16BE(e,1),c.writeUInt32BE(3932200,7),r=11,void 0===(n=t.ticket))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return c.writeUInt16BE(n,r),r+=2,void 0===(n=t.exchange)&&(n=""),c[r]=s,r++,c.write(n,r,"utf8"),r+=s,void 0===(n=t.routingKey)&&(n=""),c[r]=a,r++,c.write(n,r,"utf8"),r+=a,void 0===(n=t.mandatory)&&(n=!1),n&&(i+=1),void 0===(n=t.immediate)&&(n=!1),n&&(i+=2),c[r]=i,c[++r]=206,c.writeUInt32BE(r-7,3),c}(n,o);case 3932210:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.replyText))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");if(i+=o,void 0===(n=t.exchange))throw new Error("Missing value for mandatory field 'exchange'");if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");if(i+=s,void 0===(n=t.routingKey))throw new Error("Missing value for mandatory field 'routingKey'");if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var a=_t.byteLength(n,"utf8");i+=a;var c=_t.alloc(17+i);if(c[0]=1,c.writeUInt16BE(e,1),c.writeUInt32BE(3932210,7),r=11,void 0===(n=t.replyCode))throw new Error("Missing value for mandatory field 'replyCode'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)");return c.writeUInt16BE(n,r),r+=2,void 0===(n=t.replyText)&&(n=""),c[r]=o,r++,c.write(n,r,"utf8"),r+=o,void 0===(n=t.exchange)&&(n=void 0),c[r]=s,r++,c.write(n,r,"utf8"),r+=s,void 0===(n=t.routingKey)&&(n=void 0),c[r]=a,r++,c.write(n,r,"utf8"),c[r+=a]=206,c.writeUInt32BE(r-7,3),c}(n,o);case 3932220:return function(e,r){var n=0,i=null,o=0,s=0;if(void 0===(i=r.consumerTag))throw new Error("Missing value for mandatory field 'consumerTag'");if(!("string"==typeof i&&_t.byteLength(i)<256))throw new TypeError("Field 'consumerTag' is the wrong type; must be a string (up to 255 chars)");var a=_t.byteLength(i,"utf8");if(s+=a,void 0===(i=r.exchange))throw new Error("Missing value for mandatory field 'exchange'");if(!("string"==typeof i&&_t.byteLength(i)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var c=_t.byteLength(i,"utf8");if(s+=c,void 0===(i=r.routingKey))throw new Error("Missing value for mandatory field 'routingKey'");if(!("string"==typeof i&&_t.byteLength(i)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var u=_t.byteLength(i,"utf8");s+=u;var l=_t.alloc(24+s);if(l[0]=1,l.writeUInt16BE(e,1),l.writeUInt32BE(3932220,7),n=11,void 0===(i=r.consumerTag)&&(i=void 0),l[n]=a,n++,l.write(i,n,"utf8"),n+=a,void 0===(i=r.deliveryTag))throw new Error("Missing value for mandatory field 'deliveryTag'");if("number"!=typeof i||isNaN(i))throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)");return t.writeUInt64BE(l,i,n),n+=8,void 0===(i=r.redelivered)&&(i=!1),i&&(o+=1),l[n]=o,n++,o=0,void 0===(i=r.exchange)&&(i=void 0),l[n]=c,n++,l.write(i,n,"utf8"),n+=c,void 0===(i=r.routingKey)&&(i=void 0),l[n]=u,n++,l.write(i,n,"utf8"),l[n+=u]=206,l.writeUInt32BE(n-7,3),l}(n,o);case 3932230:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.queue))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");o+=s;var a=_t.alloc(16+o);if(a[0]=1,a.writeUInt16BE(e,1),a.writeUInt32BE(3932230,7),r=11,void 0===(n=t.ticket))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return a.writeUInt16BE(n,r),r+=2,void 0===(n=t.queue)&&(n=""),a[r]=s,r++,a.write(n,r,"utf8"),r+=s,void 0===(n=t.noAck)&&(n=!1),n&&(i+=1),a[r]=i,a[++r]=206,a.writeUInt32BE(r-7,3),a}(n,o);case 3932231:return function(e,r){var n=0,i=null,o=0,s=0;if(void 0===(i=r.exchange))throw new Error("Missing value for mandatory field 'exchange'");if(!("string"==typeof i&&_t.byteLength(i)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var a=_t.byteLength(i,"utf8");if(s+=a,void 0===(i=r.routingKey))throw new Error("Missing value for mandatory field 'routingKey'");if(!("string"==typeof i&&_t.byteLength(i)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var c=_t.byteLength(i,"utf8");s+=c;var u=_t.alloc(27+s);if(u[0]=1,u.writeUInt16BE(e,1),u.writeUInt32BE(3932231,7),n=11,void 0===(i=r.deliveryTag))throw new Error("Missing value for mandatory field 'deliveryTag'");if("number"!=typeof i||isNaN(i))throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)");if(t.writeUInt64BE(u,i,n),n+=8,void 0===(i=r.redelivered)&&(i=!1),i&&(o+=1),u[n]=o,n++,o=0,void 0===(i=r.exchange)&&(i=void 0),u[n]=a,n++,u.write(i,n,"utf8"),n+=a,void 0===(i=r.routingKey)&&(i=void 0),u[n]=c,n++,u.write(i,n,"utf8"),n+=c,void 0===(i=r.messageCount))throw new Error("Missing value for mandatory field 'messageCount'");if("number"!=typeof i||isNaN(i))throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)");return u.writeUInt32BE(i,n),u[n+=4]=206,u.writeUInt32BE(n-7,3),u}(n,o);case 3932232:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.clusterId))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(13+i);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(3932232,7),r=11,void 0===(n=t.clusterId)&&(n=""),s[r]=o,r++,s.write(n,r,"utf8"),s[r+=o]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 3932240:return function(e,r){var n=0,i=null,o=0,s=_t.alloc(21);if(s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(3932240,7),n=11,void 0===(i=r.deliveryTag))i=0;else if("number"!=typeof i||isNaN(i))throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)");return t.writeUInt64BE(s,i,n),n+=8,void 0===(i=r.multiple)&&(i=!1),i&&(o+=1),s[n]=o,s[++n]=206,s.writeUInt32BE(n-7,3),s}(n,o);case 3932250:return function(e,r){var n=0,i=null,o=0,s=_t.alloc(21);if(s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(3932250,7),n=11,void 0===(i=r.deliveryTag))throw new Error("Missing value for mandatory field 'deliveryTag'");if("number"!=typeof i||isNaN(i))throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)");return t.writeUInt64BE(s,i,n),n+=8,void 0===(i=r.requeue)&&(i=!0),i&&(o+=1),s[n]=o,s[++n]=206,s.writeUInt32BE(n-7,3),s}(n,o);case 3932260:return function(e,t){var r=0,n=null,i=0,o=_t.alloc(13);return o[0]=1,o.writeUInt16BE(e,1),o.writeUInt32BE(3932260,7),r=11,void 0===(n=t.requeue)&&(n=!1),n&&(i+=1),o[r]=i,o[++r]=206,o.writeUInt32BE(r-7,3),o}(n,o);case 3932270:return function(e,t){var r=0,n=null,i=0,o=_t.alloc(13);return o[0]=1,o.writeUInt16BE(e,1),o.writeUInt32BE(3932270,7),r=11,void 0===(n=t.requeue)&&(n=!1),n&&(i+=1),o[r]=i,o[++r]=206,o.writeUInt32BE(r-7,3),o}(n,o);case 3932271:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(3932271,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 3932280:return function(e,r){var n=0,i=null,o=0,s=_t.alloc(21);if(s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(3932280,7),n=11,void 0===(i=r.deliveryTag))i=0;else if("number"!=typeof i||isNaN(i))throw new TypeError("Field 'deliveryTag' is the wrong type; must be a number (but not NaN)");return t.writeUInt64BE(s,i,n),n+=8,void 0===(i=r.multiple)&&(i=!1),i&&(o+=1),void 0===(i=r.requeue)&&(i=!0),i&&(o+=2),s[n]=o,s[++n]=206,s.writeUInt32BE(n-7,3),s}(n,o);case 655370:return function(e,t){var n,o=0,s=null,a=0,c=0;if(void 0===(s=t.serverProperties))throw new Error("Missing value for mandatory field 'serverProperties'");if("object"!=typeof s)throw new TypeError("Field 'serverProperties' is the wrong type; must be an object");n=r(i,s,c);var u=i.slice(c,c+n);if(c+=n,a+=u.length,void 0===(s=t.mechanisms))s=_t.from("PLAIN");else if(!_t.isBuffer(s))throw new TypeError("Field 'mechanisms' is the wrong type; must be a Buffer");if(a+=s.length,void 0===(s=t.locales))s=_t.from("en_US");else if(!_t.isBuffer(s))throw new TypeError("Field 'locales' is the wrong type; must be a Buffer");a+=s.length;var l=_t.alloc(22+a);if(l[0]=1,l.writeUInt16BE(e,1),l.writeUInt32BE(655370,7),o=11,void 0===(s=t.versionMajor))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'versionMajor' is the wrong type; must be a number (but not NaN)");if(l.writeUInt8(s,o),o++,void 0===(s=t.versionMinor))s=9;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'versionMinor' is the wrong type; must be a number (but not NaN)");return l.writeUInt8(s,o),o++,o+=u.copy(l,o),void 0===(s=t.mechanisms)&&(s=_t.from("PLAIN")),n=s.length,l.writeUInt32BE(n,o),o+=4,s.copy(l,o),o+=n,void 0===(s=t.locales)&&(s=_t.from("en_US")),n=s.length,l.writeUInt32BE(n,o),o+=4,s.copy(l,o),l[o+=n]=206,l.writeUInt32BE(o-7,3),l}(n,o);case 655371:return function(e,t){var n,o=0,s=null,a=0,c=0;if(void 0===(s=t.clientProperties))throw new Error("Missing value for mandatory field 'clientProperties'");if("object"!=typeof s)throw new TypeError("Field 'clientProperties' is the wrong type; must be an object");n=r(i,s,c);var u=i.slice(c,c+n);if(c+=n,a+=u.length,void 0===(s=t.mechanism))s="PLAIN";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'mechanism' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(a+=l,void 0===(s=t.response))throw new Error("Missing value for mandatory field 'response'");if(!_t.isBuffer(s))throw new TypeError("Field 'response' is the wrong type; must be a Buffer");if(a+=s.length,void 0===(s=t.locale))s="en_US";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'locale' is the wrong type; must be a string (up to 255 chars)");var h=_t.byteLength(s,"utf8");a+=h;var f=_t.alloc(18+a);return f[0]=1,f.writeUInt16BE(e,1),f.writeUInt32BE(655371,7),o=11,o+=u.copy(f,o),void 0===(s=t.mechanism)&&(s="PLAIN"),f[o]=l,o++,f.write(s,o,"utf8"),o+=l,void 0===(s=t.response)&&(s=_t.from(void 0)),n=s.length,f.writeUInt32BE(n,o),o+=4,s.copy(f,o),o+=n,void 0===(s=t.locale)&&(s="en_US"),f[o]=h,o++,f.write(s,o,"utf8"),f[o+=h]=206,f.writeUInt32BE(o-7,3),f}(n,o);case 655380:return function(e,t){var r,n=0,i=null,o=0;if(void 0===(i=t.challenge))throw new Error("Missing value for mandatory field 'challenge'");if(!_t.isBuffer(i))throw new TypeError("Field 'challenge' is the wrong type; must be a Buffer");o+=i.length;var s=_t.alloc(16+o);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(655380,7),n=11,void 0===(i=t.challenge)&&(i=_t.from(void 0)),r=i.length,s.writeUInt32BE(r,n),n+=4,i.copy(s,n),s[n+=r]=206,s.writeUInt32BE(n-7,3),s}(n,o);case 655381:return function(e,t){var r,n=0,i=null,o=0;if(void 0===(i=t.response))throw new Error("Missing value for mandatory field 'response'");if(!_t.isBuffer(i))throw new TypeError("Field 'response' is the wrong type; must be a Buffer");o+=i.length;var s=_t.alloc(16+o);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(655381,7),n=11,void 0===(i=t.response)&&(i=_t.from(void 0)),r=i.length,s.writeUInt32BE(r,n),n+=4,i.copy(s,n),s[n+=r]=206,s.writeUInt32BE(n-7,3),s}(n,o);case 655390:return function(e,t){var r=0,n=null,i=_t.alloc(20);if(i[0]=1,i.writeUInt16BE(e,1),i.writeUInt32BE(655390,7),r=11,void 0===(n=t.channelMax))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)");if(i.writeUInt16BE(n,r),r+=2,void 0===(n=t.frameMax))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)");if(i.writeUInt32BE(n,r),r+=4,void 0===(n=t.heartbeat))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)");return i.writeUInt16BE(n,r),i[r+=2]=206,i.writeUInt32BE(r-7,3),i}(n,o);case 655391:return function(e,t){var r=0,n=null,i=_t.alloc(20);if(i[0]=1,i.writeUInt16BE(e,1),i.writeUInt32BE(655391,7),r=11,void 0===(n=t.channelMax))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'channelMax' is the wrong type; must be a number (but not NaN)");if(i.writeUInt16BE(n,r),r+=2,void 0===(n=t.frameMax))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'frameMax' is the wrong type; must be a number (but not NaN)");if(i.writeUInt32BE(n,r),r+=4,void 0===(n=t.heartbeat))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'heartbeat' is the wrong type; must be a number (but not NaN)");return i.writeUInt16BE(n,r),i[r+=2]=206,i.writeUInt32BE(r-7,3),i}(n,o);case 655400:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.virtualHost))n="/";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'virtualHost' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");if(o+=s,void 0===(n=t.capabilities))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'capabilities' is the wrong type; must be a string (up to 255 chars)");var a=_t.byteLength(n,"utf8");o+=a;var c=_t.alloc(15+o);return c[0]=1,c.writeUInt16BE(e,1),c.writeUInt32BE(655400,7),r=11,void 0===(n=t.virtualHost)&&(n="/"),c[r]=s,r++,c.write(n,r,"utf8"),r+=s,void 0===(n=t.capabilities)&&(n=""),c[r]=a,r++,c.write(n,r,"utf8"),r+=a,void 0===(n=t.insist)&&(n=!1),n&&(i+=1),c[r]=i,c[++r]=206,c.writeUInt32BE(r-7,3),c}(n,o);case 655401:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.knownHosts))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'knownHosts' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(13+i);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(655401,7),r=11,void 0===(n=t.knownHosts)&&(n=""),s[r]=o,r++,s.write(n,r,"utf8"),s[r+=o]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 655410:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.replyText))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(19+i);if(s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(655410,7),r=11,void 0===(n=t.replyCode))throw new Error("Missing value for mandatory field 'replyCode'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)");if(s.writeUInt16BE(n,r),r+=2,void 0===(n=t.replyText)&&(n=""),s[r]=o,r++,s.write(n,r,"utf8"),r+=o,void 0===(n=t.classId))throw new Error("Missing value for mandatory field 'classId'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)");if(s.writeUInt16BE(n,r),r+=2,void 0===(n=t.methodId))throw new Error("Missing value for mandatory field 'methodId'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)");return s.writeUInt16BE(n,r),s[r+=2]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 655411:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(655411,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 655420:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.reason))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'reason' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(13+i);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(655420,7),r=11,void 0===(n=t.reason)&&(n=""),s[r]=o,r++,s.write(n,r,"utf8"),s[r+=o]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 655421:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(655421,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 655430:return function(e,t){var r,n=0,i=null,o=0;if(void 0===(i=t.newSecret))throw new Error("Missing value for mandatory field 'newSecret'");if(!_t.isBuffer(i))throw new TypeError("Field 'newSecret' is the wrong type; must be a Buffer");if(o+=i.length,void 0===(i=t.reason))throw new Error("Missing value for mandatory field 'reason'");if(!("string"==typeof i&&_t.byteLength(i)<256))throw new TypeError("Field 'reason' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(i,"utf8");o+=s;var a=_t.alloc(17+o);return a[0]=1,a.writeUInt16BE(e,1),a.writeUInt32BE(655430,7),n=11,void 0===(i=t.newSecret)&&(i=_t.from(void 0)),r=i.length,a.writeUInt32BE(r,n),n+=4,i.copy(a,n),n+=r,void 0===(i=t.reason)&&(i=void 0),a[n]=s,n++,a.write(i,n,"utf8"),a[n+=s]=206,a.writeUInt32BE(n-7,3),a}(n,o);case 655431:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(655431,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 1310730:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.outOfBand))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'outOfBand' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(13+i);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(1310730,7),r=11,void 0===(n=t.outOfBand)&&(n=""),s[r]=o,r++,s.write(n,r,"utf8"),s[r+=o]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 1310731:return function(e,t){var r,n=0,i=null,o=0;if(void 0===(i=t.channelId))i=_t.from("");else if(!_t.isBuffer(i))throw new TypeError("Field 'channelId' is the wrong type; must be a Buffer");o+=i.length;var s=_t.alloc(16+o);return s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(1310731,7),n=11,void 0===(i=t.channelId)&&(i=_t.from("")),r=i.length,s.writeUInt32BE(r,n),n+=4,i.copy(s,n),s[n+=r]=206,s.writeUInt32BE(n-7,3),s}(n,o);case 1310740:return function(e,t){var r,n=0,i=0,o=_t.alloc(13);if(o[0]=1,o.writeUInt16BE(e,1),o.writeUInt32BE(1310740,7),n=11,void 0===(r=t.active))throw new Error("Missing value for mandatory field 'active'");return r&&(i+=1),o[n]=i,o[++n]=206,o.writeUInt32BE(n-7,3),o}(n,o);case 1310741:return function(e,t){var r,n=0,i=0,o=_t.alloc(13);if(o[0]=1,o.writeUInt16BE(e,1),o.writeUInt32BE(1310741,7),n=11,void 0===(r=t.active))throw new Error("Missing value for mandatory field 'active'");return r&&(i+=1),o[n]=i,o[++n]=206,o.writeUInt32BE(n-7,3),o}(n,o);case 1310760:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.replyText))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'replyText' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(19+i);if(s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(1310760,7),r=11,void 0===(n=t.replyCode))throw new Error("Missing value for mandatory field 'replyCode'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'replyCode' is the wrong type; must be a number (but not NaN)");if(s.writeUInt16BE(n,r),r+=2,void 0===(n=t.replyText)&&(n=""),s[r]=o,r++,s.write(n,r,"utf8"),r+=o,void 0===(n=t.classId))throw new Error("Missing value for mandatory field 'classId'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'classId' is the wrong type; must be a number (but not NaN)");if(s.writeUInt16BE(n,r),r+=2,void 0===(n=t.methodId))throw new Error("Missing value for mandatory field 'methodId'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'methodId' is the wrong type; must be a number (but not NaN)");return s.writeUInt16BE(n,r),s[r+=2]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 1310761:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(1310761,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 1966090:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.realm))n="/data";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'realm' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");o+=s;var a=_t.alloc(14+o);return a[0]=1,a.writeUInt16BE(e,1),a.writeUInt32BE(1966090,7),r=11,void 0===(n=t.realm)&&(n="/data"),a[r]=s,r++,a.write(n,r,"utf8"),r+=s,void 0===(n=t.exclusive)&&(n=!1),n&&(i+=1),void 0===(n=t.passive)&&(n=!0),n&&(i+=2),void 0===(n=t.active)&&(n=!0),n&&(i+=4),void 0===(n=t.write)&&(n=!0),n&&(i+=8),void 0===(n=t.read)&&(n=!0),n&&(i+=16),a[r]=i,a[++r]=206,a.writeUInt32BE(r-7,3),a}(n,o);case 1966091:return function(e,t){var r=0,n=null,i=_t.alloc(14);if(i[0]=1,i.writeUInt16BE(e,1),i.writeUInt32BE(1966091,7),r=11,void 0===(n=t.ticket))n=1;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return i.writeUInt16BE(n,r),i[r+=2]=206,i.writeUInt32BE(r-7,3),i}(n,o);case 2621450:return function(e,t){var n,o=0,s=null,a=0,c=0,u=0;if(void 0===(s=t.exchange))throw new Error("Missing value for mandatory field 'exchange'");if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(c+=l,void 0===(s=t.type))s="direct";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)");var h=_t.byteLength(s,"utf8");if(c+=h,void 0===(s=t.arguments))s={};else if("object"!=typeof s)throw new TypeError("Field 'arguments' is the wrong type; must be an object");n=r(i,s,u);var f=i.slice(u,u+n);u+=n,c+=f.length;var d=_t.alloc(17+c);if(d[0]=1,d.writeUInt16BE(e,1),d.writeUInt32BE(2621450,7),o=11,void 0===(s=t.ticket))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return d.writeUInt16BE(s,o),o+=2,void 0===(s=t.exchange)&&(s=void 0),d[o]=l,o++,d.write(s,o,"utf8"),o+=l,void 0===(s=t.type)&&(s="direct"),d[o]=h,o++,d.write(s,o,"utf8"),o+=h,void 0===(s=t.passive)&&(s=!1),s&&(a+=1),void 0===(s=t.durable)&&(s=!1),s&&(a+=2),void 0===(s=t.autoDelete)&&(s=!1),s&&(a+=4),void 0===(s=t.internal)&&(s=!1),s&&(a+=8),void 0===(s=t.nowait)&&(s=!1),s&&(a+=16),d[o]=a,o++,a=0,d[o+=f.copy(d,o)]=206,d.writeUInt32BE(o-7,3),d}(n,o);case 2621451:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(2621451,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 2621460:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.exchange))throw new Error("Missing value for mandatory field 'exchange'");if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");o+=s;var a=_t.alloc(16+o);if(a[0]=1,a.writeUInt16BE(e,1),a.writeUInt32BE(2621460,7),r=11,void 0===(n=t.ticket))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return a.writeUInt16BE(n,r),r+=2,void 0===(n=t.exchange)&&(n=void 0),a[r]=s,r++,a.write(n,r,"utf8"),r+=s,void 0===(n=t.ifUnused)&&(n=!1),n&&(i+=1),void 0===(n=t.nowait)&&(n=!1),n&&(i+=2),a[r]=i,a[++r]=206,a.writeUInt32BE(r-7,3),a}(n,o);case 2621461:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(2621461,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 2621470:return function(e,t){var n,o=0,s=null,a=0,c=0,u=0;if(void 0===(s=t.destination))throw new Error("Missing value for mandatory field 'destination'");if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(c+=l,void 0===(s=t.source))throw new Error("Missing value for mandatory field 'source'");if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)");var h=_t.byteLength(s,"utf8");if(c+=h,void 0===(s=t.routingKey))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var f=_t.byteLength(s,"utf8");if(c+=f,void 0===(s=t.arguments))s={};else if("object"!=typeof s)throw new TypeError("Field 'arguments' is the wrong type; must be an object");n=r(i,s,u);var d=i.slice(u,u+n);u+=n,c+=d.length;var p=_t.alloc(18+c);if(p[0]=1,p.writeUInt16BE(e,1),p.writeUInt32BE(2621470,7),o=11,void 0===(s=t.ticket))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return p.writeUInt16BE(s,o),o+=2,void 0===(s=t.destination)&&(s=void 0),p[o]=l,o++,p.write(s,o,"utf8"),o+=l,void 0===(s=t.source)&&(s=void 0),p[o]=h,o++,p.write(s,o,"utf8"),o+=h,void 0===(s=t.routingKey)&&(s=""),p[o]=f,o++,p.write(s,o,"utf8"),o+=f,void 0===(s=t.nowait)&&(s=!1),s&&(a+=1),p[o]=a,o++,a=0,p[o+=d.copy(p,o)]=206,p.writeUInt32BE(o-7,3),p}(n,o);case 2621471:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(2621471,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 2621480:return function(e,t){var n,o=0,s=null,a=0,c=0,u=0;if(void 0===(s=t.destination))throw new Error("Missing value for mandatory field 'destination'");if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'destination' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(c+=l,void 0===(s=t.source))throw new Error("Missing value for mandatory field 'source'");if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'source' is the wrong type; must be a string (up to 255 chars)");var h=_t.byteLength(s,"utf8");if(c+=h,void 0===(s=t.routingKey))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var f=_t.byteLength(s,"utf8");if(c+=f,void 0===(s=t.arguments))s={};else if("object"!=typeof s)throw new TypeError("Field 'arguments' is the wrong type; must be an object");n=r(i,s,u);var d=i.slice(u,u+n);u+=n,c+=d.length;var p=_t.alloc(18+c);if(p[0]=1,p.writeUInt16BE(e,1),p.writeUInt32BE(2621480,7),o=11,void 0===(s=t.ticket))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return p.writeUInt16BE(s,o),o+=2,void 0===(s=t.destination)&&(s=void 0),p[o]=l,o++,p.write(s,o,"utf8"),o+=l,void 0===(s=t.source)&&(s=void 0),p[o]=h,o++,p.write(s,o,"utf8"),o+=h,void 0===(s=t.routingKey)&&(s=""),p[o]=f,o++,p.write(s,o,"utf8"),o+=f,void 0===(s=t.nowait)&&(s=!1),s&&(a+=1),p[o]=a,o++,a=0,p[o+=d.copy(p,o)]=206,p.writeUInt32BE(o-7,3),p}(n,o);case 2621491:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(2621491,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 3276810:return function(e,t){var n,o=0,s=null,a=0,c=0,u=0;if(void 0===(s=t.queue))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(c+=l,void 0===(s=t.arguments))s={};else if("object"!=typeof s)throw new TypeError("Field 'arguments' is the wrong type; must be an object");n=r(i,s,u);var h=i.slice(u,u+n);u+=n,c+=h.length;var f=_t.alloc(16+c);if(f[0]=1,f.writeUInt16BE(e,1),f.writeUInt32BE(3276810,7),o=11,void 0===(s=t.ticket))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return f.writeUInt16BE(s,o),o+=2,void 0===(s=t.queue)&&(s=""),f[o]=l,o++,f.write(s,o,"utf8"),o+=l,void 0===(s=t.passive)&&(s=!1),s&&(a+=1),void 0===(s=t.durable)&&(s=!1),s&&(a+=2),void 0===(s=t.exclusive)&&(s=!1),s&&(a+=4),void 0===(s=t.autoDelete)&&(s=!1),s&&(a+=8),void 0===(s=t.nowait)&&(s=!1),s&&(a+=16),f[o]=a,o++,a=0,f[o+=h.copy(f,o)]=206,f.writeUInt32BE(o-7,3),f}(n,o);case 3276811:return function(e,t){var r=0,n=null,i=0;if(void 0===(n=t.queue))throw new Error("Missing value for mandatory field 'queue'");if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var o=_t.byteLength(n,"utf8");i+=o;var s=_t.alloc(21+i);if(s[0]=1,s.writeUInt16BE(e,1),s.writeUInt32BE(3276811,7),r=11,void 0===(n=t.queue)&&(n=void 0),s[r]=o,r++,s.write(n,r,"utf8"),r+=o,void 0===(n=t.messageCount))throw new Error("Missing value for mandatory field 'messageCount'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)");if(s.writeUInt32BE(n,r),r+=4,void 0===(n=t.consumerCount))throw new Error("Missing value for mandatory field 'consumerCount'");if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'consumerCount' is the wrong type; must be a number (but not NaN)");return s.writeUInt32BE(n,r),s[r+=4]=206,s.writeUInt32BE(r-7,3),s}(n,o);case 3276820:return function(e,t){var n,o=0,s=null,a=0,c=0,u=0;if(void 0===(s=t.queue))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(c+=l,void 0===(s=t.exchange))throw new Error("Missing value for mandatory field 'exchange'");if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var h=_t.byteLength(s,"utf8");if(c+=h,void 0===(s=t.routingKey))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var f=_t.byteLength(s,"utf8");if(c+=f,void 0===(s=t.arguments))s={};else if("object"!=typeof s)throw new TypeError("Field 'arguments' is the wrong type; must be an object");n=r(i,s,u);var d=i.slice(u,u+n);u+=n,c+=d.length;var p=_t.alloc(18+c);if(p[0]=1,p.writeUInt16BE(e,1),p.writeUInt32BE(3276820,7),o=11,void 0===(s=t.ticket))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return p.writeUInt16BE(s,o),o+=2,void 0===(s=t.queue)&&(s=""),p[o]=l,o++,p.write(s,o,"utf8"),o+=l,void 0===(s=t.exchange)&&(s=void 0),p[o]=h,o++,p.write(s,o,"utf8"),o+=h,void 0===(s=t.routingKey)&&(s=""),p[o]=f,o++,p.write(s,o,"utf8"),o+=f,void 0===(s=t.nowait)&&(s=!1),s&&(a+=1),p[o]=a,o++,a=0,p[o+=d.copy(p,o)]=206,p.writeUInt32BE(o-7,3),p}(n,o);case 3276821:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(3276821,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 3276830:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.queue))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");o+=s;var a=_t.alloc(16+o);if(a[0]=1,a.writeUInt16BE(e,1),a.writeUInt32BE(3276830,7),r=11,void 0===(n=t.ticket))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return a.writeUInt16BE(n,r),r+=2,void 0===(n=t.queue)&&(n=""),a[r]=s,r++,a.write(n,r,"utf8"),r+=s,void 0===(n=t.nowait)&&(n=!1),n&&(i+=1),a[r]=i,a[++r]=206,a.writeUInt32BE(r-7,3),a}(n,o);case 3276831:return function(e,t){var r,n=0,i=_t.alloc(16);if(i[0]=1,i.writeUInt16BE(e,1),i.writeUInt32BE(3276831,7),n=11,void 0===(r=t.messageCount))throw new Error("Missing value for mandatory field 'messageCount'");if("number"!=typeof r||isNaN(r))throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)");return i.writeUInt32BE(r,n),i[n+=4]=206,i.writeUInt32BE(n-7,3),i}(n,o);case 3276840:return function(e,t){var r=0,n=null,i=0,o=0;if(void 0===(n=t.queue))n="";else if(!("string"==typeof n&&_t.byteLength(n)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var s=_t.byteLength(n,"utf8");o+=s;var a=_t.alloc(16+o);if(a[0]=1,a.writeUInt16BE(e,1),a.writeUInt32BE(3276840,7),r=11,void 0===(n=t.ticket))n=0;else if("number"!=typeof n||isNaN(n))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return a.writeUInt16BE(n,r),r+=2,void 0===(n=t.queue)&&(n=""),a[r]=s,r++,a.write(n,r,"utf8"),r+=s,void 0===(n=t.ifUnused)&&(n=!1),n&&(i+=1),void 0===(n=t.ifEmpty)&&(n=!1),n&&(i+=2),void 0===(n=t.nowait)&&(n=!1),n&&(i+=4),a[r]=i,a[++r]=206,a.writeUInt32BE(r-7,3),a}(n,o);case 3276841:return function(e,t){var r,n=0,i=_t.alloc(16);if(i[0]=1,i.writeUInt16BE(e,1),i.writeUInt32BE(3276841,7),n=11,void 0===(r=t.messageCount))throw new Error("Missing value for mandatory field 'messageCount'");if("number"!=typeof r||isNaN(r))throw new TypeError("Field 'messageCount' is the wrong type; must be a number (but not NaN)");return i.writeUInt32BE(r,n),i[n+=4]=206,i.writeUInt32BE(n-7,3),i}(n,o);case 3276850:return function(e,t){var n,o=0,s=null,a=0,c=0;if(void 0===(s=t.queue))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'queue' is the wrong type; must be a string (up to 255 chars)");var u=_t.byteLength(s,"utf8");if(a+=u,void 0===(s=t.exchange))throw new Error("Missing value for mandatory field 'exchange'");if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'exchange' is the wrong type; must be a string (up to 255 chars)");var l=_t.byteLength(s,"utf8");if(a+=l,void 0===(s=t.routingKey))s="";else if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'routingKey' is the wrong type; must be a string (up to 255 chars)");var h=_t.byteLength(s,"utf8");if(a+=h,void 0===(s=t.arguments))s={};else if("object"!=typeof s)throw new TypeError("Field 'arguments' is the wrong type; must be an object");n=r(i,s,c);var f=i.slice(c,c+n);c+=n,a+=f.length;var d=_t.alloc(17+a);if(d[0]=1,d.writeUInt16BE(e,1),d.writeUInt32BE(3276850,7),o=11,void 0===(s=t.ticket))s=0;else if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'ticket' is the wrong type; must be a number (but not NaN)");return d.writeUInt16BE(s,o),o+=2,void 0===(s=t.queue)&&(s=""),d[o]=u,o++,d.write(s,o,"utf8"),o+=u,void 0===(s=t.exchange)&&(s=void 0),d[o]=l,o++,d.write(s,o,"utf8"),o+=l,void 0===(s=t.routingKey)&&(s=""),d[o]=h,o++,d.write(s,o,"utf8"),o+=h,d[o+=f.copy(d,o)]=206,d.writeUInt32BE(o-7,3),d}(n,o);case 3276851:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(3276851,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 5898250:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(5898250,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 5898251:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(5898251,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 5898260:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(5898260,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 5898261:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(5898261,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 5898270:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(5898270,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 5898271:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(5898271,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);case 5570570:return function(e,t){var r=0,n=null,i=0,o=_t.alloc(13);return o[0]=1,o.writeUInt16BE(e,1),o.writeUInt32BE(5570570,7),r=11,void 0===(n=t.nowait)&&(n=!1),n&&(i+=1),o[r]=i,o[++r]=206,o.writeUInt32BE(r-7,3),o}(n,o);case 5570571:return function(e){var t=_t.alloc(12);return t[0]=1,t.writeUInt16BE(e,1),t.writeUInt32BE(5570571,7),t[11]=206,t.writeUInt32BE(4,3),t}(n);default:throw new Error("Unknown class/method ID")}},Hs.encodeProperties=function(e,n,o,s){if(60===e)return function(e,n,o){var s,a,c=0,u=0,l=0,h=0;if(null!=(s=o.contentType)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'contentType' is the wrong type; must be a string (up to 255 chars)");var f=_t.byteLength(s,"utf8");h+=1,h+=f}if(null!=(s=o.contentEncoding)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'contentEncoding' is the wrong type; must be a string (up to 255 chars)");var d=_t.byteLength(s,"utf8");h+=1,h+=d}if(null!=(s=o.headers)){if("object"!=typeof s)throw new TypeError("Field 'headers' is the wrong type; must be an object");a=r(i,s,l);var p=i.slice(l,l+a);l+=a,h+=p.length}if(null!=(s=o.deliveryMode)){if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'deliveryMode' is the wrong type; must be a number (but not NaN)");h+=1}if(null!=(s=o.priority)){if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'priority' is the wrong type; must be a number (but not NaN)");h+=1}if(null!=(s=o.correlationId)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'correlationId' is the wrong type; must be a string (up to 255 chars)");var g=_t.byteLength(s,"utf8");h+=1,h+=g}if(null!=(s=o.replyTo)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'replyTo' is the wrong type; must be a string (up to 255 chars)");var m=_t.byteLength(s,"utf8");h+=1,h+=m}if(null!=(s=o.expiration)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'expiration' is the wrong type; must be a string (up to 255 chars)");var y=_t.byteLength(s,"utf8");h+=1,h+=y}if(null!=(s=o.messageId)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'messageId' is the wrong type; must be a string (up to 255 chars)");var w=_t.byteLength(s,"utf8");h+=1,h+=w}if(null!=(s=o.timestamp)){if("number"!=typeof s||isNaN(s))throw new TypeError("Field 'timestamp' is the wrong type; must be a number (but not NaN)");h+=8}if(null!=(s=o.type)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'type' is the wrong type; must be a string (up to 255 chars)");var b=_t.byteLength(s,"utf8");h+=1,h+=b}if(null!=(s=o.userId)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'userId' is the wrong type; must be a string (up to 255 chars)");var v=_t.byteLength(s,"utf8");h+=1,h+=v}if(null!=(s=o.appId)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'appId' is the wrong type; must be a string (up to 255 chars)");var E=_t.byteLength(s,"utf8");h+=1,h+=E}if(null!=(s=o.clusterId)){if(!("string"==typeof s&&_t.byteLength(s)<256))throw new TypeError("Field 'clusterId' is the wrong type; must be a string (up to 255 chars)");var I=_t.byteLength(s,"utf8");h+=1,h+=I}var _=_t.alloc(22+h);return _[0]=2,_.writeUInt16BE(e,1),_.writeUInt32BE(3932160,7),t.writeUInt64BE(_,n,11),u=0,c=21,null!=(s=o.contentType)&&(u+=32768,_[c]=f,c++,_.write(s,c,"utf8"),c+=f),null!=(s=o.contentEncoding)&&(u+=16384,_[c]=d,c++,_.write(s,c,"utf8"),c+=d),null!=(s=o.headers)&&(u+=8192,c+=p.copy(_,c)),null!=(s=o.deliveryMode)&&(u+=4096,_.writeUInt8(s,c),c++),null!=(s=o.priority)&&(u+=2048,_.writeUInt8(s,c),c++),null!=(s=o.correlationId)&&(u+=1024,_[c]=g,c++,_.write(s,c,"utf8"),c+=g),null!=(s=o.replyTo)&&(u+=512,_[c]=m,c++,_.write(s,c,"utf8"),c+=m),null!=(s=o.expiration)&&(u+=256,_[c]=y,c++,_.write(s,c,"utf8"),c+=y),null!=(s=o.messageId)&&(u+=128,_[c]=w,c++,_.write(s,c,"utf8"),c+=w),null!=(s=o.timestamp)&&(u+=64,t.writeUInt64BE(_,s,c),c+=8),null!=(s=o.type)&&(u+=32,_[c]=b,c++,_.write(s,c,"utf8"),c+=b),null!=(s=o.userId)&&(u+=16,_[c]=v,c++,_.write(s,c,"utf8"),c+=v),null!=(s=o.appId)&&(u+=8,_[c]=E,c++,_.write(s,c,"utf8"),c+=E),null!=(s=o.clusterId)&&(u+=4,_[c]=I,c++,_.write(s,c,"utf8"),c+=I),_[c]=206,_.writeUInt32BE(c-7,3),_.writeUInt16BE(u,19),_.subarray(0,c+1)}(n,o,s);throw new Error("Unknown class/properties ID")},Hs.info=function(e){switch(e){case 3932170:return o;case 3932171:return s;case 3932180:return a;case 3932181:return c;case 3932190:return u;case 3932191:return l;case 3932200:return h;case 3932210:return f;case 3932220:return d;case 3932230:return p;case 3932231:return g;case 3932232:return m;case 3932240:return y;case 3932250:return w;case 3932260:return b;case 3932270:return v;case 3932271:return E;case 3932280:return I;case 655370:return _;case 655371:return A;case 655380:return k;case 655381:return B;case 655390:return x;case 655391:return S;case 655400:return O;case 655401:return U;case 655410:return C;case 655411:return N;case 655420:return R;case 655421:return T;case 655430:return L;case 655431:return D;case 1310730:return j;case 1310731:return M;case 1310740:return P;case 1310741:return F;case 1310760:return q;case 1310761:return Q;case 1966090:return z;case 1966091:return $;case 2621450:return H;case 2621451:return V;case 2621460:return G;case 2621461:return K;case 2621470:return W;case 2621471:return J;case 2621480:return Z;case 2621491:return Y;case 3276810:return X;case 3276811:return ee;case 3276820:return te;case 3276821:return re;case 3276830:return ne;case 3276831:return ie;case 3276840:return oe;case 3276841:return se;case 3276850:return ae;case 3276851:return ce;case 5898250:return ue;case 5898251:return le;case 5898260:return he;case 5898261:return fe;case 5898270:return de;case 5898271:return pe;case 5570570:return ge;case 5570571:return me;case 60:return ye;default:throw new Error("Unknown class/method ID")}},Hs.BasicQos=3932170;var o=Hs.methodInfoBasicQos={id:3932170,classId:60,methodId:10,name:"BasicQos",args:[{type:"long",name:"prefetchSize",default:0},{type:"short",name:"prefetchCount",default:0},{type:"bit",name:"global",default:!1}]};Hs.BasicQosOk=3932171;var s=Hs.methodInfoBasicQosOk={id:3932171,classId:60,methodId:11,name:"BasicQosOk",args:[]};Hs.BasicConsume=3932180;var a=Hs.methodInfoBasicConsume={id:3932180,classId:60,methodId:20,name:"BasicConsume",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"queue",default:""},{type:"shortstr",name:"consumerTag",default:""},{type:"bit",name:"noLocal",default:!1},{type:"bit",name:"noAck",default:!1},{type:"bit",name:"exclusive",default:!1},{type:"bit",name:"nowait",default:!1},{type:"table",name:"arguments",default:{}}]};Hs.BasicConsumeOk=3932181;var c=Hs.methodInfoBasicConsumeOk={id:3932181,classId:60,methodId:21,name:"BasicConsumeOk",args:[{type:"shortstr",name:"consumerTag"}]};Hs.BasicCancel=3932190;var u=Hs.methodInfoBasicCancel={id:3932190,classId:60,methodId:30,name:"BasicCancel",args:[{type:"shortstr",name:"consumerTag"},{type:"bit",name:"nowait",default:!1}]};Hs.BasicCancelOk=3932191;var l=Hs.methodInfoBasicCancelOk={id:3932191,classId:60,methodId:31,name:"BasicCancelOk",args:[{type:"shortstr",name:"consumerTag"}]};Hs.BasicPublish=3932200;var h=Hs.methodInfoBasicPublish={id:3932200,classId:60,methodId:40,name:"BasicPublish",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"exchange",default:""},{type:"shortstr",name:"routingKey",default:""},{type:"bit",name:"mandatory",default:!1},{type:"bit",name:"immediate",default:!1}]};Hs.BasicReturn=3932210;var f=Hs.methodInfoBasicReturn={id:3932210,classId:60,methodId:50,name:"BasicReturn",args:[{type:"short",name:"replyCode"},{type:"shortstr",name:"replyText",default:""},{type:"shortstr",name:"exchange"},{type:"shortstr",name:"routingKey"}]};Hs.BasicDeliver=3932220;var d=Hs.methodInfoBasicDeliver={id:3932220,classId:60,methodId:60,name:"BasicDeliver",args:[{type:"shortstr",name:"consumerTag"},{type:"longlong",name:"deliveryTag"},{type:"bit",name:"redelivered",default:!1},{type:"shortstr",name:"exchange"},{type:"shortstr",name:"routingKey"}]};Hs.BasicGet=3932230;var p=Hs.methodInfoBasicGet={id:3932230,classId:60,methodId:70,name:"BasicGet",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"queue",default:""},{type:"bit",name:"noAck",default:!1}]};Hs.BasicGetOk=3932231;var g=Hs.methodInfoBasicGetOk={id:3932231,classId:60,methodId:71,name:"BasicGetOk",args:[{type:"longlong",name:"deliveryTag"},{type:"bit",name:"redelivered",default:!1},{type:"shortstr",name:"exchange"},{type:"shortstr",name:"routingKey"},{type:"long",name:"messageCount"}]};Hs.BasicGetEmpty=3932232;var m=Hs.methodInfoBasicGetEmpty={id:3932232,classId:60,methodId:72,name:"BasicGetEmpty",args:[{type:"shortstr",name:"clusterId",default:""}]};Hs.BasicAck=3932240;var y=Hs.methodInfoBasicAck={id:3932240,classId:60,methodId:80,name:"BasicAck",args:[{type:"longlong",name:"deliveryTag",default:0},{type:"bit",name:"multiple",default:!1}]};Hs.BasicReject=3932250;var w=Hs.methodInfoBasicReject={id:3932250,classId:60,methodId:90,name:"BasicReject",args:[{type:"longlong",name:"deliveryTag"},{type:"bit",name:"requeue",default:!0}]};Hs.BasicRecoverAsync=3932260;var b=Hs.methodInfoBasicRecoverAsync={id:3932260,classId:60,methodId:100,name:"BasicRecoverAsync",args:[{type:"bit",name:"requeue",default:!1}]};Hs.BasicRecover=3932270;var v=Hs.methodInfoBasicRecover={id:3932270,classId:60,methodId:110,name:"BasicRecover",args:[{type:"bit",name:"requeue",default:!1}]};Hs.BasicRecoverOk=3932271;var E=Hs.methodInfoBasicRecoverOk={id:3932271,classId:60,methodId:111,name:"BasicRecoverOk",args:[]};Hs.BasicNack=3932280;var I=Hs.methodInfoBasicNack={id:3932280,classId:60,methodId:120,name:"BasicNack",args:[{type:"longlong",name:"deliveryTag",default:0},{type:"bit",name:"multiple",default:!1},{type:"bit",name:"requeue",default:!0}]};Hs.ConnectionStart=655370;var _=Hs.methodInfoConnectionStart={id:655370,classId:10,methodId:10,name:"ConnectionStart",args:[{type:"octet",name:"versionMajor",default:0},{type:"octet",name:"versionMinor",default:9},{type:"table",name:"serverProperties"},{type:"longstr",name:"mechanisms",default:"PLAIN"},{type:"longstr",name:"locales",default:"en_US"}]};Hs.ConnectionStartOk=655371;var A=Hs.methodInfoConnectionStartOk={id:655371,classId:10,methodId:11,name:"ConnectionStartOk",args:[{type:"table",name:"clientProperties"},{type:"shortstr",name:"mechanism",default:"PLAIN"},{type:"longstr",name:"response"},{type:"shortstr",name:"locale",default:"en_US"}]};Hs.ConnectionSecure=655380;var k=Hs.methodInfoConnectionSecure={id:655380,classId:10,methodId:20,name:"ConnectionSecure",args:[{type:"longstr",name:"challenge"}]};Hs.ConnectionSecureOk=655381;var B=Hs.methodInfoConnectionSecureOk={id:655381,classId:10,methodId:21,name:"ConnectionSecureOk",args:[{type:"longstr",name:"response"}]};Hs.ConnectionTune=655390;var x=Hs.methodInfoConnectionTune={id:655390,classId:10,methodId:30,name:"ConnectionTune",args:[{type:"short",name:"channelMax",default:0},{type:"long",name:"frameMax",default:0},{type:"short",name:"heartbeat",default:0}]};Hs.ConnectionTuneOk=655391;var S=Hs.methodInfoConnectionTuneOk={id:655391,classId:10,methodId:31,name:"ConnectionTuneOk",args:[{type:"short",name:"channelMax",default:0},{type:"long",name:"frameMax",default:0},{type:"short",name:"heartbeat",default:0}]};Hs.ConnectionOpen=655400;var O=Hs.methodInfoConnectionOpen={id:655400,classId:10,methodId:40,name:"ConnectionOpen",args:[{type:"shortstr",name:"virtualHost",default:"/"},{type:"shortstr",name:"capabilities",default:""},{type:"bit",name:"insist",default:!1}]};Hs.ConnectionOpenOk=655401;var U=Hs.methodInfoConnectionOpenOk={id:655401,classId:10,methodId:41,name:"ConnectionOpenOk",args:[{type:"shortstr",name:"knownHosts",default:""}]};Hs.ConnectionClose=655410;var C=Hs.methodInfoConnectionClose={id:655410,classId:10,methodId:50,name:"ConnectionClose",args:[{type:"short",name:"replyCode"},{type:"shortstr",name:"replyText",default:""},{type:"short",name:"classId"},{type:"short",name:"methodId"}]};Hs.ConnectionCloseOk=655411;var N=Hs.methodInfoConnectionCloseOk={id:655411,classId:10,methodId:51,name:"ConnectionCloseOk",args:[]};Hs.ConnectionBlocked=655420;var R=Hs.methodInfoConnectionBlocked={id:655420,classId:10,methodId:60,name:"ConnectionBlocked",args:[{type:"shortstr",name:"reason",default:""}]};Hs.ConnectionUnblocked=655421;var T=Hs.methodInfoConnectionUnblocked={id:655421,classId:10,methodId:61,name:"ConnectionUnblocked",args:[]};Hs.ConnectionUpdateSecret=655430;var L=Hs.methodInfoConnectionUpdateSecret={id:655430,classId:10,methodId:70,name:"ConnectionUpdateSecret",args:[{type:"longstr",name:"newSecret"},{type:"shortstr",name:"reason"}]};Hs.ConnectionUpdateSecretOk=655431;var D=Hs.methodInfoConnectionUpdateSecretOk={id:655431,classId:10,methodId:71,name:"ConnectionUpdateSecretOk",args:[]};Hs.ChannelOpen=1310730;var j=Hs.methodInfoChannelOpen={id:1310730,classId:20,methodId:10,name:"ChannelOpen",args:[{type:"shortstr",name:"outOfBand",default:""}]};Hs.ChannelOpenOk=1310731;var M=Hs.methodInfoChannelOpenOk={id:1310731,classId:20,methodId:11,name:"ChannelOpenOk",args:[{type:"longstr",name:"channelId",default:""}]};Hs.ChannelFlow=1310740;var P=Hs.methodInfoChannelFlow={id:1310740,classId:20,methodId:20,name:"ChannelFlow",args:[{type:"bit",name:"active"}]};Hs.ChannelFlowOk=1310741;var F=Hs.methodInfoChannelFlowOk={id:1310741,classId:20,methodId:21,name:"ChannelFlowOk",args:[{type:"bit",name:"active"}]};Hs.ChannelClose=1310760;var q=Hs.methodInfoChannelClose={id:1310760,classId:20,methodId:40,name:"ChannelClose",args:[{type:"short",name:"replyCode"},{type:"shortstr",name:"replyText",default:""},{type:"short",name:"classId"},{type:"short",name:"methodId"}]};Hs.ChannelCloseOk=1310761;var Q=Hs.methodInfoChannelCloseOk={id:1310761,classId:20,methodId:41,name:"ChannelCloseOk",args:[]};Hs.AccessRequest=1966090;var z=Hs.methodInfoAccessRequest={id:1966090,classId:30,methodId:10,name:"AccessRequest",args:[{type:"shortstr",name:"realm",default:"/data"},{type:"bit",name:"exclusive",default:!1},{type:"bit",name:"passive",default:!0},{type:"bit",name:"active",default:!0},{type:"bit",name:"write",default:!0},{type:"bit",name:"read",default:!0}]};Hs.AccessRequestOk=1966091;var $=Hs.methodInfoAccessRequestOk={id:1966091,classId:30,methodId:11,name:"AccessRequestOk",args:[{type:"short",name:"ticket",default:1}]};Hs.ExchangeDeclare=2621450;var H=Hs.methodInfoExchangeDeclare={id:2621450,classId:40,methodId:10,name:"ExchangeDeclare",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"exchange"},{type:"shortstr",name:"type",default:"direct"},{type:"bit",name:"passive",default:!1},{type:"bit",name:"durable",default:!1},{type:"bit",name:"autoDelete",default:!1},{type:"bit",name:"internal",default:!1},{type:"bit",name:"nowait",default:!1},{type:"table",name:"arguments",default:{}}]};Hs.ExchangeDeclareOk=2621451;var V=Hs.methodInfoExchangeDeclareOk={id:2621451,classId:40,methodId:11,name:"ExchangeDeclareOk",args:[]};Hs.ExchangeDelete=2621460;var G=Hs.methodInfoExchangeDelete={id:2621460,classId:40,methodId:20,name:"ExchangeDelete",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"exchange"},{type:"bit",name:"ifUnused",default:!1},{type:"bit",name:"nowait",default:!1}]};Hs.ExchangeDeleteOk=2621461;var K=Hs.methodInfoExchangeDeleteOk={id:2621461,classId:40,methodId:21,name:"ExchangeDeleteOk",args:[]};Hs.ExchangeBind=2621470;var W=Hs.methodInfoExchangeBind={id:2621470,classId:40,methodId:30,name:"ExchangeBind",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"destination"},{type:"shortstr",name:"source"},{type:"shortstr",name:"routingKey",default:""},{type:"bit",name:"nowait",default:!1},{type:"table",name:"arguments",default:{}}]};Hs.ExchangeBindOk=2621471;var J=Hs.methodInfoExchangeBindOk={id:2621471,classId:40,methodId:31,name:"ExchangeBindOk",args:[]};Hs.ExchangeUnbind=2621480;var Z=Hs.methodInfoExchangeUnbind={id:2621480,classId:40,methodId:40,name:"ExchangeUnbind",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"destination"},{type:"shortstr",name:"source"},{type:"shortstr",name:"routingKey",default:""},{type:"bit",name:"nowait",default:!1},{type:"table",name:"arguments",default:{}}]};Hs.ExchangeUnbindOk=2621491;var Y=Hs.methodInfoExchangeUnbindOk={id:2621491,classId:40,methodId:51,name:"ExchangeUnbindOk",args:[]};Hs.QueueDeclare=3276810;var X=Hs.methodInfoQueueDeclare={id:3276810,classId:50,methodId:10,name:"QueueDeclare",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"queue",default:""},{type:"bit",name:"passive",default:!1},{type:"bit",name:"durable",default:!1},{type:"bit",name:"exclusive",default:!1},{type:"bit",name:"autoDelete",default:!1},{type:"bit",name:"nowait",default:!1},{type:"table",name:"arguments",default:{}}]};Hs.QueueDeclareOk=3276811;var ee=Hs.methodInfoQueueDeclareOk={id:3276811,classId:50,methodId:11,name:"QueueDeclareOk",args:[{type:"shortstr",name:"queue"},{type:"long",name:"messageCount"},{type:"long",name:"consumerCount"}]};Hs.QueueBind=3276820;var te=Hs.methodInfoQueueBind={id:3276820,classId:50,methodId:20,name:"QueueBind",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"queue",default:""},{type:"shortstr",name:"exchange"},{type:"shortstr",name:"routingKey",default:""},{type:"bit",name:"nowait",default:!1},{type:"table",name:"arguments",default:{}}]};Hs.QueueBindOk=3276821;var re=Hs.methodInfoQueueBindOk={id:3276821,classId:50,methodId:21,name:"QueueBindOk",args:[]};Hs.QueuePurge=3276830;var ne=Hs.methodInfoQueuePurge={id:3276830,classId:50,methodId:30,name:"QueuePurge",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"queue",default:""},{type:"bit",name:"nowait",default:!1}]};Hs.QueuePurgeOk=3276831;var ie=Hs.methodInfoQueuePurgeOk={id:3276831,classId:50,methodId:31,name:"QueuePurgeOk",args:[{type:"long",name:"messageCount"}]};Hs.QueueDelete=3276840;var oe=Hs.methodInfoQueueDelete={id:3276840,classId:50,methodId:40,name:"QueueDelete",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"queue",default:""},{type:"bit",name:"ifUnused",default:!1},{type:"bit",name:"ifEmpty",default:!1},{type:"bit",name:"nowait",default:!1}]};Hs.QueueDeleteOk=3276841;var se=Hs.methodInfoQueueDeleteOk={id:3276841,classId:50,methodId:41,name:"QueueDeleteOk",args:[{type:"long",name:"messageCount"}]};Hs.QueueUnbind=3276850;var ae=Hs.methodInfoQueueUnbind={id:3276850,classId:50,methodId:50,name:"QueueUnbind",args:[{type:"short",name:"ticket",default:0},{type:"shortstr",name:"queue",default:""},{type:"shortstr",name:"exchange"},{type:"shortstr",name:"routingKey",default:""},{type:"table",name:"arguments",default:{}}]};Hs.QueueUnbindOk=3276851;var ce=Hs.methodInfoQueueUnbindOk={id:3276851,classId:50,methodId:51,name:"QueueUnbindOk",args:[]};Hs.TxSelect=5898250;var ue=Hs.methodInfoTxSelect={id:5898250,classId:90,methodId:10,name:"TxSelect",args:[]};Hs.TxSelectOk=5898251;var le=Hs.methodInfoTxSelectOk={id:5898251,classId:90,methodId:11,name:"TxSelectOk",args:[]};Hs.TxCommit=5898260;var he=Hs.methodInfoTxCommit={id:5898260,classId:90,methodId:20,name:"TxCommit",args:[]};Hs.TxCommitOk=5898261;var fe=Hs.methodInfoTxCommitOk={id:5898261,classId:90,methodId:21,name:"TxCommitOk",args:[]};Hs.TxRollback=5898270;var de=Hs.methodInfoTxRollback={id:5898270,classId:90,methodId:30,name:"TxRollback",args:[]};Hs.TxRollbackOk=5898271;var pe=Hs.methodInfoTxRollbackOk={id:5898271,classId:90,methodId:31,name:"TxRollbackOk",args:[]};Hs.ConfirmSelect=5570570;var ge=Hs.methodInfoConfirmSelect={id:5570570,classId:85,methodId:10,name:"ConfirmSelect",args:[{type:"bit",name:"nowait",default:!1}]};Hs.ConfirmSelectOk=5570571;var me=Hs.methodInfoConfirmSelectOk={id:5570571,classId:85,methodId:11,name:"ConfirmSelectOk",args:[]};Hs.BasicProperties=60;var ye=Hs.propertiesInfoBasicProperties={id:60,name:"BasicProperties",args:[{type:"shortstr",name:"contentType"},{type:"shortstr",name:"contentEncoding"},{type:"table",name:"headers"},{type:"octet",name:"deliveryMode"},{type:"octet",name:"priority"},{type:"shortstr",name:"correlationId"},{type:"shortstr",name:"replyTo"},{type:"shortstr",name:"expiration"},{type:"shortstr",name:"messageId"},{type:"timestamp",name:"timestamp"},{type:"shortstr",name:"type"},{type:"shortstr",name:"userId"},{type:"shortstr",name:"appId"},{type:"shortstr",name:"clusterId"}]};return Hs}var Zs,Ys={};function Xs(){if(Zs)return Ys;Zs=1;const e=Ks();var t=Js(),r=t.constants,n=t.decode;Ys.PROTOCOL_HEADER="AMQP"+String.fromCharCode(0,0,9,1);var i=r.FRAME_METHOD,o=r.FRAME_HEARTBEAT,s=r.FRAME_HEADER,a=r.FRAME_BODY,c=r.FRAME_END;Ys.makeBodyFrame=function(e,t){const r=7+t.length+1,n=_t.alloc(r);let i=0;return i=n.writeUInt8(a,i),i=n.writeUInt16BE(e,i),i=n.writeInt32BE(t.length,i),t.copy(n,i),i+=t.length,n.writeUInt8(c,i),n},Ys.parseFrame=function(e){if(e.length<7)return!1;const t=e.readUInt8(0),r=e.readUInt16BE(1),n=e.readUInt32BE(3),i=7+n+1;if(e.length<i)return!1;if(e.readUInt8(7+n)!==c)throw new Error("Invalid frame");return{type:t,channel:r,size:n,payload:e.subarray(7,7+n),rest:e.subarray(i)}};var u={channel:0};return Ys.decodeFrame=t=>{const r=t.payload,c=t.channel;switch(t.type){case i:{const e=r.readUInt32BE(0),t=r.subarray(4);return{id:e,channel:c,fields:n(e,t)}}case s:{const t=r.readUInt16BE(0),i=(l=r,h=4,"function"==typeof _t.prototype.readBigInt64BE?Number(l.readBigInt64BE(h)):e.readInt64BE(l,h)),o=r.subarray(12);return{id:t,channel:c,size:i,fields:n(t,o)}}case a:return{channel:c,content:r};case o:return u;default:throw new Error("Unknown frame type "+t.type)}var l,h},Ys.HEARTBEAT_BUF=_t.from([r.FRAME_HEARTBEAT,0,0,0,0,0,0,r.FRAME_END]),Ys.HEARTBEAT=u,Ys}var ea={};function ta(e,t){if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0}var ra,na=Object.prototype.hasOwnProperty,ia=Object.keys||function(e){var t=[];for(var r in e)na.call(e,r)&&t.push(r);return t},oa=Array.prototype.slice;function sa(){return void 0!==ra?ra:ra="foo"===function(){}.name}function aa(e){return Object.prototype.toString.call(e)}function ca(e){return!sr(e)&&("function"==typeof ct.ArrayBuffer&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):!!e&&(e instanceof DataView||!!(e.buffer&&e.buffer instanceof ArrayBuffer))))}function ua(e,t){e||ga(e,!0,t,"==",ma)}var la=/\s*function\s+([^\(\s]*)\s*/;function ha(e){if(sn(e)){if(sa())return e.name;var t=e.toString().match(la);return t&&t[1]}}function fa(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=function(e){return da(pa(e.actual),128)+" "+e.operator+" "+da(pa(e.expected),128)}(this),this.generatedMessage=!0);var t=e.stackStartFunction||ga;if(Error.captureStackTrace)Error.captureStackTrace(this,t);else{var r=new Error;if(r.stack){var n=r.stack,i=ha(t),o=n.indexOf("\n"+i);if(o>=0){var s=n.indexOf("\n",o+1);n=n.substring(s+1)}this.stack=n}}}function da(e,t){return"string"==typeof e?e.length<t?e:e.slice(0,t):e}function pa(e){if(sa()||!sn(e))return qr(e);var t=ha(e);return"[Function"+(t?": "+t:"")+"]"}function ga(e,t,r,n,i){throw new fa({message:r,actual:e,expected:t,operator:n,stackStartFunction:i})}function ma(e,t){e||ga(e,!0,t,"==",ma)}function ya(e,t,r){e!=t&&ga(e,t,r,"==",ya)}function wa(e,t,r){e==t&&ga(e,t,r,"!=",wa)}function ba(e,t,r){Ea(e,t,!1)||ga(e,t,r,"deepEqual",ba)}function va(e,t,r){Ea(e,t,!0)||ga(e,t,r,"deepStrictEqual",va)}function Ea(e,t,r,n){if(e===t)return!0;if(sr(e)&&sr(t))return 0===ta(e,t);if(nn(e)&&nn(t))return e.getTime()===t.getTime();if(tn(e)&&tn(t))return e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.lastIndex===t.lastIndex&&e.ignoreCase===t.ignoreCase;if(null!==e&&"object"==typeof e||null!==t&&"object"==typeof t){if(ca(e)&&ca(t)&&aa(e)===aa(t)&&!(e instanceof Float32Array||e instanceof Float64Array))return 0===ta(new Uint8Array(e.buffer),new Uint8Array(t.buffer));if(sr(e)!==sr(t))return!1;var i=(n=n||{actual:[],expected:[]}).actual.indexOf(e);return-1!==i&&i===n.expected.indexOf(t)||(n.actual.push(e),n.expected.push(t),function(e,t,r,n){if(null==e||null==t)return!1;if(an(e)||an(t))return e===t;if(r&&Object.getPrototypeOf(e)!==Object.getPrototypeOf(t))return!1;var i=Ia(e),o=Ia(t);if(i&&!o||!i&&o)return!1;if(i)return Ea(e=oa.call(e),t=oa.call(t),r);var s,a,c=ia(e),u=ia(t);if(c.length!==u.length)return!1;for(c.sort(),u.sort(),a=c.length-1;a>=0;a--)if(c[a]!==u[a])return!1;for(a=c.length-1;a>=0;a--)if(!Ea(e[s=c[a]],t[s],r,n))return!1;return!0}(e,t,r,n))}return r?e===t:e==t}function Ia(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function _a(e,t,r){Ea(e,t,!1)&&ga(e,t,r,"notDeepEqual",_a)}function Aa(e,t,r){Ea(e,t,!0)&&ga(e,t,r,"notDeepStrictEqual",Aa)}function ka(e,t,r){e!==t&&ga(e,t,r,"===",ka)}function Ba(e,t,r){e===t&&ga(e,t,r,"!==",Ba)}function xa(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function Sa(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&ga(i,r,"Missing expected exception"+n);var o="string"==typeof n,s=!e&&i&&!r;if((!e&&on(i)&&o&&xa(i,r)||s)&&ga(i,r,"Got unwanted exception"+n),e&&i&&r&&!xa(i,r)||!e&&i)throw i}function Oa(e,t,r){Sa(!0,e,t,r)}function Ua(e,t,r){Sa(!1,e,t,r)}function Ca(e){if(e)throw e}ua.AssertionError=fa,Nr(fa,Error),ua.fail=ga,ua.ok=ma,ua.equal=ya,ua.notEqual=wa,ua.deepEqual=ba,ua.deepStrictEqual=va,ua.notDeepEqual=_a,ua.notDeepStrictEqual=Aa,ua.strictEqual=ka,ua.notStrictEqual=Ba,ua.throws=Oa,ua.doesNotThrow=Ua,ua.ifError=Ca;var Na,Ra=Is(Object.freeze({__proto__:null,AssertionError:fa,assert:ma,deepEqual:ba,deepStrictEqual:va,default:ua,doesNotThrow:Ua,equal:ya,fail:ga,ifError:Ca,notDeepEqual:_a,notDeepStrictEqual:Aa,notEqual:wa,notStrictEqual:Ba,ok:ma,strictEqual:ka,throws:Oa}));var Ta,La=Is(hi),Da=Is(Ke),ja={exports:{}};var Ma,Pa={},Fa=Is(vn);function qa(){if(Ma)return Pa;Ma=1;var e=Js(),t=Fa.format,r=Xs().HEARTBEAT;return Pa.closeMessage=function(r){var n=r.fields.replyCode;return t('%d (%s) with message "%s"',n,e.constant_strs[n],r.fields.replyText)},Pa.methodName=function(t){return e.info(t).name},Pa.inspect=function(n,i){if(n===r)return"<Heartbeat>";if(n.id){var o=e.info(n.id);return t("<%s channel:%d%s>",o.name,n.channel,i?" "+JSON.stringify(n.fields,void 0,2):"")}return t("<Content channel:%d size:%d>",n.channel,n.size)},Pa}var Qa,za={};var $a,Ha,Va={};function Ga(){if($a)return Va;function e(e,t){return e&&e.split("\n").slice(t).join("\n")}function t(t,r){var n=new Error;this.message=t,this.stack=this.toString()+"\n"+e(n.stack,2),this.stackAtStateChange=r}return $a=1,(0,Fa.inherits)(t,Error),t.prototype.name="IllegalOperationError",Va.IllegalOperationError=t,Va.stackCapture=function(t){return"Stack capture: "+t+"\n"+e((new Error).stack,2)},Va}function Ka(){if(Ha)return $s;Ha=1;var e=Js(),t=e.constants,r=Xs(),n=r.HEARTBEAT,i=function(){if(Na)return ea;Na=1;var e=Ra,t="function"==typeof setImmediate?setImmediate:Rr.nextTick;return ea.Mux=class{constructor(e){this.newStreams=[],this.oldStreams=[],this.blocked=!1,this.scheduledRead=!1,this.out=e;var t=this;e.on("drain",function(){t.blocked=!1,t._readIncoming()})}_readIncoming(){if(!this.blocked){var t=!0,r=this.out;n(this.newStreams),t?(e.equal(0,this.newStreams.length),n(this.oldStreams)):(e(this.newStreams.length>0,"Expect some new streams to remain"),Array.prototype.push.apply(this.oldStreams,this.newStreams),this.newStreams=[]),this.blocked=!t}function n(e){for(var n;t&&(n=e.shift());){var i=n.read();null!==i&&(t=r.write(i),e.push(n))}}}_scheduleRead(){var e=this;e.scheduledRead||(t(function(){e.scheduledRead=!1,e._readIncoming()}),e.scheduledRead=!0)}pipeFrom(e){var t=this;function r(){t.newStreams.push(e),t._scheduleRead()}function n(){e.removeListener("readable",r),e.removeListener("error",n),e.removeListener("end",n),e.removeListener("unpipeFrom",i)}function i(e){e===t&&n()}e.on("unpipeFrom",i),e.on("end",n),e.on("error",n),e.on("readable",r)}unpipeFrom(e){e.emit("unpipeFrom",this)}},ea}().Mux,o=La.Duplex,s=Da,a=(Ta||(Ta=1,function(e){var t=Da;e.exports.UNITS_TO_MS=1e3,e.exports.Heart=class extends t{constructor(t,r,n){super(),this.interval=t;var i=t*e.exports.UNITS_TO_MS,o=this.emit.bind(this,"beat"),s=this.emit.bind(this,"timeout");this.sendTimer=setInterval(this.runHeartbeat.bind(this,r,o),i/2);var a=0;this.recvTimer=setInterval(this.runHeartbeat.bind(this,function(){return n()?(a=0,!0):++a<2},s),i)}clear(){clearInterval(this.sendTimer),clearInterval(this.recvTimer)}runHeartbeat(e,t){e()||t()}}}(ja)),ja.exports).Heart,c=qa().methodName,u=qa().closeMessage,l=qa().inspect,h=function(){if(Qa)return za;function e(e){return Math.floor(e/32)}function t(e){if(0===e)return 32;let t,r=31;return t=e<<16,0!=t&&(r-=16,e=t),t=e<<8,0!=t&&(r-=8,e=t),t=e<<4,0!=t&&(r-=4,e=t),t=e<<2,0!=t&&(r-=2,e=t),r-(e<<1>>>31)}return Qa=1,za.BitSet=class{constructor(e){if(e){const t=Math.ceil(e/32);this.words=new Array(t)}else this.words=[];this.wordsInUse=0}ensureSize(e){const t=this.words.length;t<e&&(this.words=this.words.concat(new Array(e-t)))}set(t){const r=e(t);r>=this.wordsInUse&&(this.ensureSize(r+1),this.wordsInUse=r+1);const n=1<<t;this.words[r]|=n}clear(t){const r=e(t);if(r>=this.wordsInUse)return;const n=~(1<<t);this.words[r]&=n}get(t){const r=e(t);if(r>=this.wordsInUse)return!1;const n=1<<t;return!!(this.words[r]&n)}nextSetBit(r){let n=e(r);if(n>=this.wordsInUse)return-1;let i=this.words[n]&4294967295<<r;for(;;){if(i)return 32*n+t(i);if(n++,n===this.wordsInUse)return-1;i=this.words[n]}}nextClearBit(r){let n=e(r);if(n>=this.wordsInUse)return r;let i=~this.words[n]&4294967295<<r;for(;;){if(i)return 32*n+t(i);if(n++,n==this.wordsInUse)return 32*n;i=~this.words[n]}}},za}().BitSet,f=Fa.format,d=La.PassThrough,p=Ga().IllegalOperationError,g=Ga().stackCapture;function m(e){var r=this.channels[e.channel];if(r)return r.channel.accept(e);this.closeWithError(f("Frame on unknown channel %d",e.channel),t.CHANNEL_ERROR,new Error(f("Frame on unknown channel: %s",l(e,!1))))}function y(r){return function(i){if(i===n);else if(i.id===e.ConnectionClose){r.sendMethod(0,e.ConnectionCloseOk,{});var o=f("Connection closed: %s",u(i)),s=g(o),a=new Error(o);a.code=i.fields.replyCode,B(a)&&r.emit("error",a),r.toClosed(s,a)}else i.id===e.ConnectionBlocked?r.emit("blocked",i.fields.reason):i.id===e.ConnectionUnblocked?r.emit("unblocked"):i.id===e.ConnectionUpdateSecretOk?r.emit("update-secret-ok"):r.closeWithError(f("Unexpected frame on channel 0"),t.UNEXPECTED_FRAME,new Error(f("Unexpected frame on channel 0: %s",l(i,!1))))}}function w(e,t){return function(){throw new p(e,t)}}function b(e,t,r){e.sendMethod=e.sendContent=e.sendMessage=w(t,r)}var v=e.encodeMethod,E=e.encodeProperties,I=e.FRAME_OVERHEAD,_=r.makeBodyFrame,A=r.parseFrame,k=r.decodeFrame;function B(t){switch(t&&t.code){case e.constants.CONNECTION_FORCED:case e.constants.REPLY_SUCCESS:return!1;default:return!0}}return $s.Connection=class extends s{constructor(e){super();var r=this.stream=function(e){if(e instanceof o)return e;var t=new o;return t.wrap(e),t._write=function(t,r,n){return e.write(t,r,n)},t}(e);this.muxer=new i(r),this.rest=_t.alloc(0),this.frameMax=t.FRAME_MIN_SIZE,this.sentSinceLastCheck=!1,this.recvSinceLastCheck=!1,this.expectSocketClose=!1,this.freeChannels=new h,this.channels=[{channel:{accept:y(this)},buffer:e}]}sendProtocolHeader(){this.sendBytes(r.PROTOCOL_HEADER)}open(t,r){var n=this,i=r||function(){},o=Object.create(t);function s(e){n.step(function(t,r){null!==t?h(t):0!==r.channel?h(new Error(f("Frame on channel != 0 during handshake: %s",l(r,!1)))):e(r)})}function a(e,t){s(function(r){r.id===e?t(r):h(new Error(f("Expected %s; got %s",c(e),l(r,!1))))})}function h(e){i(e)}function d(e){n.sendMethod(0,e,o)}function p(e,t){return 0===e||0===t?Math.max(e,t):Math.min(e,t)}function g(r){switch(r.id){case e.ConnectionSecure:h(new Error("Wasn't expecting to have to go through secure"));break;case e.ConnectionClose:h(new Error(f("Handshake terminated by server: %s",u(r))));break;case e.ConnectionTune:var n=r.fields;o.frameMax=p(n.frameMax,t.frameMax),o.channelMax=p(n.channelMax,t.channelMax),o.heartbeat=p(n.heartbeat,t.heartbeat);try{d(e.ConnectionTuneOk),d(e.ConnectionOpen)}catch(e){return void h(e)}a(e.ConnectionOpenOk,y);break;default:h(new Error(f("Expected connection.secure, connection.close, or connection.tune during handshake; got %s",l(r,!1))))}}function y(e){n.channelMax=o.channelMax||65535,n.frameMax=o.frameMax||4294967295,n.heartbeat=o.heartbeat,n.heartbeater=n.startHeartbeater(),n.accept=m,function(e){n.stream.removeListener("end",w),n.stream.removeListener("error",w),n.stream.on("error",n.onSocketError.bind(n)),n.stream.on("end",n.onSocketError.bind(n,new Error("Unexpected close"))),n.on("frameError",n.onSocketError.bind(n)),n.acceptLoop(),i(null,e)}(e)}function w(e){h(e||new Error("Socket closed abruptly during opening handshake"))}this.stream.on("end",w),this.stream.on("error",w),this.sendProtocolHeader(),a(e.ConnectionStart,function(r){if(r.fields.mechanisms.toString().split(" ").indexOf(t.mechanism)<0)h(new Error(f("SASL mechanism %s is not provided by the server",t.mechanism)));else{n.serverProperties=r.fields.serverProperties;try{d(e.ConnectionStartOk)}catch(e){return void h(e)}s(g)}})}close(e){var r=e&&function(){e(null)};this.closeBecause("Cheers, thanks",t.REPLY_SUCCESS,r)}closeBecause(t,r,n){this.sendMethod(0,e.ConnectionClose,{replyText:t,replyCode:r,methodId:0,classId:0});var i=g("closeBecause called: "+t);this.toClosing(i,n)}closeWithError(e,t,r){this.emit("error",r),this.closeBecause(e,t)}onSocketError(e){if(!this.expectSocketClose){this.expectSocketClose=!0,this.emit("error",e);var t=g("Socket error");this.toClosed(t,e)}}toClosing(t,r){var n=this.sendMethod.bind(this);this.accept=function(t){if(t.id===e.ConnectionCloseOk){r&&r();var i=g("ConnectionCloseOk received");this.toClosed(i,void 0)}else t.id===e.ConnectionClose&&n(0,e.ConnectionCloseOk,{})},b(this,"Connection closing",t)}_closeChannels(e){for(var t=1;t<this.channels.length;t++){var r=this.channels[t];null!==r&&r.channel.toClosed(e)}}toClosed(e,t){this._closeChannels(e);var r=f("Connection closed (%s)",t?t.toString():"by client");b(this,r,e),this.accept=w(r,e),this.close=function(t){t&&t(new p(r,e))},this.heartbeater&&this.heartbeater.clear(),this.expectSocketClose=!0,this.stream.end(),this.emit("close",t)}_updateSecret(t,r,n){this.sendMethod(0,e.ConnectionUpdateSecret,{newSecret:t,reason:r}),this.once("update-secret-ok",n)}startHeartbeater(){if(0===this.heartbeat)return null;var e=this,t=new a(this.heartbeat,this.checkSend.bind(this),this.checkRecv.bind(this));return t.on("timeout",function(){var t=new Error("Heartbeat timeout");e.emit("error",t);var r=g("Heartbeat timeout");e.toClosed(r,t)}),t.on("beat",function(){e.sendHeartbeat()}),t}freshChannel(e,t){var r=this.freeChannels.nextClearBit(1);if(r<0||r>this.channelMax)throw new Error("No channels left to allocate");this.freeChannels.set(r);var n=t&&t.highWaterMark||1024,i=new d({objectMode:!0,highWaterMark:n});return this.channels[r]={channel:e,buffer:i},i.on("drain",function(){e.onBufferDrain()}),this.muxer.pipeFrom(i),r}releaseChannel(e){this.freeChannels.clear(e),this.channels[e].buffer.end(),this.channels[e]=null}acceptLoop(){var e=this;function t(){try{for(var t;t=e.recvFrame();)e.accept(t)}catch(t){e.emit("frameError",t)}}e.stream.on("readable",t),t()}step(e){var t=this;!function r(){var n;try{n=t.recvFrame()}catch(t){return void e(t,null)}n?e(null,n):t.stream.once("readable",r)}()}checkSend(){var e=this.sentSinceLastCheck;return this.sentSinceLastCheck=!1,e}checkRecv(){var e=this.recvSinceLastCheck;return this.recvSinceLastCheck=!1,e}sendBytes(e){this.sentSinceLastCheck=!0,this.stream.write(e)}sendHeartbeat(){return this.sendBytes(r.HEARTBEAT_BUF)}sendMethod(e,t,r){var n=v(t,e,r);return this.sentSinceLastCheck=!0,this.channels[e].buffer.write(n)}sendMessage(e,t,r,n,i,o){if(!_t.isBuffer(o))throw new TypeError("content is not a buffer");var s=v(t,e,r),a=E(n,e,o.length,i),c=this.channels[e].buffer;this.sentSinceLastCheck=!0;var u=s.length+a.length,l=o.length>0?o.length+I:0,h=u+l;if(h<2048){var f=_t.allocUnsafe(h),d=s.copy(f,0);return d+=a.copy(f,d),l>0&&_(e,o).copy(f,d),c.write(f)}if(u<2048){var p=_t.allocUnsafe(u);d=s.copy(p,0);a.copy(p,d),c.write(p)}else c.write(s),c.write(a);return this.sendContent(e,o)}sendContent(e,t){if(!_t.isBuffer(t))throw new TypeError(f("Expected buffer; got %s",t));for(var r=!0,n=this.channels[e].buffer,i=this.frameMax-I,o=0;o<t.length;o+=i){var s=o+i,a=s>t.length?t.subarray(o):t.subarray(o,s),c=_(e,a);r=n.write(c)}return this.sentSinceLastCheck=!0,r}recvFrame(){var e=A(this.rest);if(e)return this.rest=e.rest,k(e);var t=this.stream.read();return null!==t&&(this.recvSinceLastCheck=!0,this.rest=_t.concat([this.rest,t]),this.recvFrame())}},$s.isFatalError=B,$s}var Wa,Ja={};function Za(){if(Wa)return Ja;Wa=1;var e=Ws();return Ja.plain=function(e,t){return{mechanism:"PLAIN",response:function(){return _t.from(["",e,t].join(String.fromCharCode(0)))},username:e,password:t}},Ja.amqplain=function(t,r){return{mechanism:"AMQPLAIN",response:function(){const n=_t.alloc(16384),i=e.encodeTable(n,{LOGIN:t,PASSWORD:r},0);return n.subarray(4,i)},username:t,password:r}},Ja.external=function(){return{mechanism:"EXTERNAL",response:function(){return _t.from("")}}},Ja}var Ya,Xa="0.10.8",ec=Is(Object.freeze({__proto__:null,default:{}})),tc=Is(Object.freeze({__proto__:null,default:{}}));function rc(){if(Ya)return Bs;Ya=1;var e=Cs(),t=zs,r=Ka().Connection,n=Fa.format,i=Za();function o(e,t){for(var r=Object.keys(e),n=r.length;n--;){var i=r[n];t[i]=e[i]}return t}var s={product:"amqplib",version:Xa,platform:n("Node.JS %s",Rr.version),information:"https://amqp-node.github.io/amqplib/",capabilities:{publisher_confirms:!0,exchange_exchange_bindings:!0,"basic.nack":!0,consumer_cancel_notify:!0,"connection.blocked":!0,authentication_failure_close:!0}};function a(e,r,n,i){e=e?t.unescape(e):"/";r=r||{};function a(e,t){return void 0===e?t:parseInt(e)}return{clientProperties:o(i,Object.create(s)),mechanism:n.mechanism,response:n.response(),locale:r.locale||"en_US",channelMax:a(r.channelMax,0),frameMax:a(r.frameMax,131072),heartbeat:a(r.heartbeat,0),virtualHost:e,capabilities:"",insist:0}}function c(e){var t="guest",r="guest";return""==e.username&&""==e.password||(t=e.username?unescape(e.username):"",r=e.password?unescape(e.password):""),i.plain(t,r)}return Bs.connect=function(t,n,s){var u=o(n||{},{});t=t||"amqp://localhost";var l,h,f=!!u.noDelay,d=u.timeout,p=!!u.keepAlive,g=u.keepAliveDelay||0,m=u.clientProperties||{};if("object"==typeof t){var y,w;l=(t.protocol||"amqp")+":",u.host=t.hostname,u.servername=u.servername||t.hostname,u.port=t.port||("amqp:"===l?5672:5671),null==t.username&&null==t.password?(y="guest",w="guest"):(y=t.username||"",w=t.password||"");var b={locale:t.locale,channelMax:t.channelMax,frameMax:t.frameMax,heartbeat:t.heartbeat};h=a(t.vhost,b,u.credentials||i.plain(y,w),m)}else{var v=e(t,!0);l=v.protocol,u.host=v.hostname,u.servername=u.servername||v.hostname,u.port=parseInt(v.port)||("amqp:"===l?5672:5671);var E=v.pathname?v.pathname.substr(1):null;h=a(E,v.query,u.credentials||c(v),m)}var I,_=!1;function A(){_=!0,I.setNoDelay(f),p&&I.setKeepAlive(p,g);var e=new r(I);e.open(h,function(t,r){d&&I.setTimeout(0),null===t?s(null,e):(I.end(),I.destroy(),s(t))})}if("amqp:"===l)I=ec.connect(u,A);else{if("amqps:"!==l)throw new Error("Expected amqp: or amqps: as the protocol; got "+l);I=tc.connect(u,A)}d&&I.setTimeout(d,function(){I.end(),I.destroy(),s(new Error("connect ETIMEDOUT"))}),I.once("error",function(e){_||s(e)})},Bs.credentialsFromUrl=c,Bs}var nc,ic,oc,sc,ac,cc={},uc={};function lc(){if(nc)return uc;nc=1;var e=Js(),t=qa().closeMessage,r=qa().inspect,n=qa().methodName,i=Ra,o=Da,s=Fa.format,a=Ga().IllegalOperationError,c=Ga().stackCapture;class u extends o{constructor(e){super(),this.connection=e,this.reply=null,this.pending=[],this.lwm=1,this.unconfirmed=[],this.on("ack",this.handleConfirm.bind(this,function(e){e&&e(null)})),this.on("nack",this.handleConfirm.bind(this,function(e){e&&e(new Error("message nacked"))})),this.on("close",function(){for(var e;e=this.unconfirmed.shift();)e&&e(new Error("channel closed"))}),this.handleMessage=f}setOptions(e){this.options=e}allocate(){return this.ch=this.connection.freshChannel(this,this.options),this}sendImmediately(e,t){return this.connection.sendMethod(this.ch,e,t)}sendOrEnqueue(e,t,r){this.reply?this.pending.push({method:e,fields:t,reply:r}):(i(0===this.pending.length),this.reply=r,this.sendImmediately(e,t))}sendMessage(t,r,n){return this.connection.sendMessage(this.ch,e.BasicPublish,t,e.BasicProperties,r,n)}_rpc(i,o,a,c){var u=this;this.sendOrEnqueue(i,o,function(o,l){if(null===o){if(l.id===a)return c(null,l);var h=n(a),f=new Error(s("Expected %s; got %s",h,r(l,!1)));return u.closeWithError(l.id,s("Expected %s; got %s",h,n(l.id)),e.constants.UNEXPECTED_FRAME,f),c(f)}if(o instanceof Error)return c(o);var d=(o.fields.classId<<16)+o.fields.methodId,p=(f=i===d?s("Operation failed: %s; %s",n(i),t(o)):s("Channel closed by server: %s",t(o)),new Error(f));return p.code=o.fields.replyCode,p.classId=o.fields.classId,p.methodId=o.fields.methodId,c(p)})}toClosed(e){this._rejectPending(),h(this,"Channel closed",e),this.accept=l("Channel closed",e),this.connection.releaseChannel(this.ch),this.emit("close")}toClosing(t,r){var n=this.sendImmediately.bind(this);h(this,"Channel closing",t),this.accept=function(t){if(t.id===e.ChannelCloseOk){r&&r();var i=c("ChannelCloseOk frame received");this.toClosed(i)}else t.id===e.ChannelClose&&n(e.ChannelCloseOk,{})}}_rejectPending(){function e(e){e(new Error("Channel ended, no reply will be forthcoming"))}var t;for(null!==this.reply&&e(this.reply),this.reply=null;t=this.pending.shift();)e(t.reply);this.pending=null}closeBecause(t,r,n){this.sendImmediately(e.ChannelClose,{replyText:t,replyCode:r,methodId:0,classId:0});var i=c("closeBecause called: "+t);this.toClosing(i,n)}closeWithError(t,r,n,i){var o=this;this.closeBecause(r,n,function(){i.code=n,t&&(i.classId=e.info(t).classId,i.methodId=e.info(t).methodId),o.emit("error",i)})}acceptMessageFrame(t){try{this.handleMessage=this.handleMessage(t)}catch(r){"string"==typeof r?this.closeWithError(t.id,r,e.constants.UNEXPECTED_FRAME,new Error(r)):r instanceof Error?this.closeWithError(t.id,"Error while processing message",e.constants.INTERNAL_ERROR,r):this.closeWithError(t.id,"Internal error while processing message",e.constants.INTERNAL_ERROR,new Error(r.toString()))}}handleConfirm(e,t){var r=t.deliveryTag;if(t.multiple){var n=this.unconfirmed.splice(0,r-this.lwm+1);this.lwm=r+1,n.forEach(e)}else{var i;if(r===this.lwm)for(i=this.unconfirmed.shift(),this.lwm++;null===this.unconfirmed[0];)this.unconfirmed.shift(),this.lwm++;else i=this.unconfirmed[r-this.lwm],this.unconfirmed[r-this.lwm]=null;e(i)}}pushConfirmCallback(e){this.unconfirmed.push(e||!1)}onBufferDrain(){this.emit("drain")}accept(r){switch(r.id){case void 0:case e.BasicDeliver:case e.BasicReturn:case e.BasicProperties:return this.acceptMessageFrame(r);case e.BasicAck:return this.emit("ack",r.fields);case e.BasicNack:return this.emit("nack",r.fields);case e.BasicCancel:return this.emit("cancel",r.fields);case e.ChannelClose:if(this.reply){var n=this.reply;this.reply=null,n(r)}var i="Channel closed by server: "+t(r);this.sendImmediately(e.ChannelCloseOk,{});var o=new Error(i);o.code=r.fields.replyCode,o.classId=r.fields.classId,o.methodId=r.fields.methodId,this.emit("error",o);var s=c(i);return void this.toClosed(s);case e.BasicFlow:return this.closeWithError(r.id,"Flow not implemented",e.constants.NOT_IMPLEMENTED,new Error("Flow not implemented"));default:n=this.reply;if(this.reply=null,this.pending.length>0){var a=this.pending.shift();this.reply=a.reply,this.sendImmediately(a.method,a.fields)}return n(null,r)}}}function l(e,t){return function(){throw new a(e,t)}}function h(e,t,r){e.sendImmediately=e.sendOrEnqueue=e.sendMessage=l(t,r)}function f(t){var n;if(t.id===e.BasicDeliver)n="delivery";else{if(t.id!==e.BasicReturn)throw s("Expected BasicDeliver or BasicReturn; got %s",r(t));n="return"}var i=this,o=t.fields;return d(function(e){e.fields=o,i.emit(n,e)})}function d(t){var r=0,n=0,i=null,o={fields:null,properties:null,content:null};return function(i){if(i.id===e.BasicProperties)return o.properties=i.fields,0===(r=n=i.size)?(o.content=_t.alloc(0),t(o),f):a;throw"Expected headers frame after delivery"};function a(e){if(e.content){var c=e.content.length;if(0===(n-=c))return null!==i?(i.push(e.content),o.content=_t.concat(i)):o.content=e.content,t(o),f;if(n<0)throw s("Too much content sent! Expected %d bytes",r);return null!==i?i.push(e.content):i=[e.content],a}throw"Expected content frame after headers"}}return uc.acceptMessage=d,uc.BaseChannel=class extends u{constructor(e){super(e),this.consumers=new Map}registerConsumer(e,t){this.consumers.set(e,t)}unregisterConsumer(e){this.consumers.delete(e)}dispatchMessage(e,t){var r=e.consumerTag,n=this.consumers.get(r);if(n)return n(t);throw new Error("Unknown consumer: "+r)}handleDelivery(e){return this.dispatchMessage(e.fields,e)}handleCancel(e){var t=this.dispatchMessage(e,null);return this.unregisterConsumer(e.consumerTag),t}},uc.Channel=u,uc}function hc(){if(sc)return cc;sc=1;const e=Da,t=Fa.promisify,r=Js(),{BaseChannel:n}=lc(),{acceptMessage:i}=lc(),o=function(){if(oc)return ic;function e(e,t,r){null!=r&&(e[t]=r)}oc=1;var t=Object.freeze({}),r={assertQueue:function(r,n){r=r||"",n=n||t;var i=Object.create(n.arguments||null);return e(i,"x-expires",n.expires),e(i,"x-message-ttl",n.messageTtl),e(i,"x-dead-letter-exchange",n.deadLetterExchange),e(i,"x-dead-letter-routing-key",n.deadLetterRoutingKey),e(i,"x-max-length",n.maxLength),e(i,"x-max-priority",n.maxPriority),e(i,"x-overflow",n.overflow),e(i,"x-queue-mode",n.queueMode),{queue:r,exclusive:!!n.exclusive,durable:void 0===n.durable||n.durable,autoDelete:!!n.autoDelete,arguments:i,passive:!1,ticket:0,nowait:!1}},checkQueue:function(e){return{queue:e,passive:!0,nowait:!1,durable:!0,autoDelete:!1,exclusive:!1,ticket:0}},deleteQueue:function(e,r){return{queue:e,ifUnused:!!(r=r||t).ifUnused,ifEmpty:!!r.ifEmpty,ticket:0,nowait:!1}},purgeQueue:function(e){return{queue:e,ticket:0,nowait:!1}},bindQueue:function(e,t,r,n){return{queue:e,exchange:t,routingKey:r,arguments:n,ticket:0,nowait:!1}},unbindQueue:function(e,t,r,n){return{queue:e,exchange:t,routingKey:r,arguments:n,ticket:0,nowait:!1}},assertExchange:function(r,n,i){i=i||t;var o=Object.create(i.arguments||null);return e(o,"alternate-exchange",i.alternateExchange),{exchange:r,ticket:0,type:n,passive:!1,durable:void 0===i.durable||i.durable,autoDelete:!!i.autoDelete,internal:!!i.internal,nowait:!1,arguments:o}},checkExchange:function(e){return{exchange:e,passive:!0,nowait:!1,durable:!0,internal:!1,type:"",autoDelete:!1,ticket:0}},deleteExchange:function(e,r){return{exchange:e,ifUnused:!!(r=r||t).ifUnused,ticket:0,nowait:!1}},bindExchange:function(e,t,r,n){return{source:t,destination:e,routingKey:r,arguments:n,ticket:0,nowait:!1}},unbindExchange:function(e,t,r,n){return{source:t,destination:e,routingKey:r,arguments:n,ticket:0,nowait:!1}},publish:function(r,n,i){function o(e){return void 0===e?void 0:Array.isArray(e)?e.map(String):[String(e)]}i=i||t;var s,a=Object.create(i.headers||null);e(a,"CC",o(i.CC)),e(a,"BCC",o(i.BCC)),void 0!==i.persistent?s=i.persistent?2:1:"number"==typeof i.deliveryMode?s=i.deliveryMode:i.deliveryMode&&(s=2);var c=i.expiration;return void 0!==c&&(c=c.toString()),{exchange:r,routingKey:n,mandatory:!!i.mandatory,immediate:!1,ticket:void 0,contentType:i.contentType,contentEncoding:i.contentEncoding,headers:a,deliveryMode:s,priority:i.priority,correlationId:i.correlationId,replyTo:i.replyTo,expiration:c,messageId:i.messageId,timestamp:i.timestamp,type:i.type,userId:i.userId,appId:i.appId,clusterId:void 0}},consume:function(r,n){n=n||t;var i=Object.create(n.arguments||null);return e(i,"x-priority",n.priority),{ticket:0,queue:r,consumerTag:n.consumerTag||"",noLocal:!!n.noLocal,noAck:!!n.noAck,exclusive:!!n.exclusive,nowait:!1,arguments:i}},cancel:function(e){return{consumerTag:e,nowait:!1}},get:function(e,r){return{ticket:0,queue:e,noAck:!!(r=r||t).noAck}},ack:function(e,t){return{deliveryTag:e,multiple:!!t}},nack:function(e,t,r){return{deliveryTag:e,multiple:!!t,requeue:void 0===r||r}},reject:function(e,t){return{deliveryTag:e,requeue:void 0===t||t}},prefetch:function(e,t){return{prefetchCount:e||0,prefetchSize:0,global:!!t}},recover:function(){return{requeue:!0}}};return ic=Object.freeze(r)}(),{inspect:s}=qa();class a extends n{constructor(e){super(e),this.on("delivery",this.handleDelivery.bind(this)),this.on("cancel",this.handleCancel.bind(this))}async rpc(e,r,n){return(await t(t=>this._rpc(e,r,n,t))()).fields}async open(){return(await this.allocate.bind(this)()).rpc(r.ChannelOpen,{outOfBand:""},r.ChannelOpenOk)}close(){return t(e=>this.closeBecause("Goodbye",r.constants.REPLY_SUCCESS,e))()}assertQueue(e,t){return this.rpc(r.QueueDeclare,o.assertQueue(e,t),r.QueueDeclareOk)}checkQueue(e){return this.rpc(r.QueueDeclare,o.checkQueue(e),r.QueueDeclareOk)}deleteQueue(e,t){return this.rpc(r.QueueDelete,o.deleteQueue(e,t),r.QueueDeleteOk)}purgeQueue(e){return this.rpc(r.QueuePurge,o.purgeQueue(e),r.QueuePurgeOk)}bindQueue(e,t,n,i){return this.rpc(r.QueueBind,o.bindQueue(e,t,n,i),r.QueueBindOk)}unbindQueue(e,t,n,i){return this.rpc(r.QueueUnbind,o.unbindQueue(e,t,n,i),r.QueueUnbindOk)}assertExchange(e,t,n){return this.rpc(r.ExchangeDeclare,o.assertExchange(e,t,n),r.ExchangeDeclareOk).then(t=>({exchange:e}))}checkExchange(e){return this.rpc(r.ExchangeDeclare,o.checkExchange(e),r.ExchangeDeclareOk)}deleteExchange(e,t){return this.rpc(r.ExchangeDelete,o.deleteExchange(e,t),r.ExchangeDeleteOk)}bindExchange(e,t,n,i){return this.rpc(r.ExchangeBind,o.bindExchange(e,t,n,i),r.ExchangeBindOk)}unbindExchange(e,t,n,i){return this.rpc(r.ExchangeUnbind,o.unbindExchange(e,t,n,i),r.ExchangeUnbindOk)}publish(e,t,r,n){const i=o.publish(e,t,n);return this.sendMessage(i,i,r)}sendToQueue(e,t,r){return this.publish("",e,t,r)}consume(e,t,n){const i=o.consume(e,n);return new Promise((e,n)=>{this._rpc(r.BasicConsume,i,r.BasicConsumeOk,(r,i)=>{if(r)return n(r);this.registerConsumer(i.fields.consumerTag,t),e(i.fields)})})}async cancel(e){await t(t=>{this._rpc(r.BasicCancel,o.cancel(e),r.BasicCancelOk,t)})().then(t=>(this.unregisterConsumer(e),t.fields))}get(e,t){const n=o.get(e,t);return new Promise((e,t)=>{this.sendOrEnqueue(r.BasicGet,n,(n,o)=>{if(n)return t(n);if(o.id===r.BasicGetEmpty)return e(!1);if(o.id===r.BasicGetOk){const t=o.fields;this.handleMessage=i(r=>{r.fields=t,e(r)})}else t(new Error(`Unexpected response to BasicGet: ${s(o)}`))})})}ack(e,t){this.sendImmediately(r.BasicAck,o.ack(e.fields.deliveryTag,t))}ackAll(){this.sendImmediately(r.BasicAck,o.ack(0,!0))}nack(e,t,n){this.sendImmediately(r.BasicNack,o.nack(e.fields.deliveryTag,t,n))}nackAll(e){this.sendImmediately(r.BasicNack,o.nack(0,!0,e))}reject(e,t){this.sendImmediately(r.BasicReject,o.reject(e.fields.deliveryTag,t))}recover(){return this.rpc(r.BasicRecover,o.recover(),r.BasicRecoverOk)}qos(e,t){return this.rpc(r.BasicQos,o.prefetch(e,t),r.BasicQosOk)}}a.prototype.prefetch=a.prototype.qos;class c extends a{publish(e,t,r,n,i){return this.pushConfirmCallback(i),super.publish(e,t,r,n)}sendToQueue(e,t,r,n){return this.publish("",e,t,r,n)}waitForConfirms(){const e=[],t=this.unconfirmed;if(t.forEach((r,n)=>{if(null!==r){const i=new Promise((e,i)=>{t[n]=t=>{r&&r(t),null===t?e():i(t)}});e.push(i)}}),!this.pending)for(var r;r=this.unconfirmed.shift();)r&&r(new Error("channel closed"));return Promise.all(e)}}return cc.ConfirmChannel=c,cc.Channel=a,cc.ChannelModel=class extends e{constructor(e){super(),this.connection=e,["error","close","blocked","unblocked"].forEach(t=>{e.on(t,this.emit.bind(this,t))})}close(){return t(this.connection.close.bind(this.connection))()}updateSecret(e,r){return t(this.connection._updateSecret.bind(this.connection))(e,r)}async createChannel(e){const t=new a(this.connection);return t.setOptions(e),await t.open(),t}async createConfirmChannel(e){const t=new c(this.connection);return t.setOptions(e),await t.open(),await t.rpc(r.ConfirmSelect,{nowait:!1},r.ConfirmSelectOk),t}},cc}!function(){if(ac)return ks;ac=1;var e=rc().connect,t=hc().ChannelModel,r=Fa.promisify;ks.connect=function(n,i){return r(function(t){return e(n,i,t)})().then(function(e){return new t(e)})},ks.credentials=Za(),ks.IllegalOperationError=Ga().IllegalOperationError}();class fc extends Qe{constructor(e={}){super(),this.config=e,this.name=this.constructor.name,this.enabled=!1!==e.enabled}async initialize(e){this.database=e,this.emit("initialized",{replicator:this.name})}async replicate(e,t,r,n){throw new Error(`replicate() method must be implemented by ${this.name}`)}async replicateBatch(e,t){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 dc,pc,gc,mc,yc,wc,bc,vc,Ec,Ic,_c,Ac,kc,Bc={};function xc(){if(pc)return dc;var e,t;pc=1;var r,n={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};function i(t){throw{name:"SyntaxError",message:t,at:e,text:r}}function o(n){return n&&n!==t&&i("Expected '"+n+"' instead of '"+t+"'"),t=r.charAt(e),e+=1,t}function s(){var e,r="";for("-"===t&&(r="-",o("-"));t>="0"&&t<="9";)r+=t,o();if("."===t)for(r+=".";o()&&t>="0"&&t<="9";)r+=t;if("e"===t||"E"===t)for(r+=t,o(),"-"!==t&&"+"!==t||(r+=t,o());t>="0"&&t<="9";)r+=t,o();return e=Number(r),isFinite(e)||i("Bad number"),e}function a(){var e,r,s,a="";if('"'===t)for(;o();){if('"'===t)return o(),a;if("\\"===t)if(o(),"u"===t){for(s=0,r=0;r<4&&(e=parseInt(o(),16),isFinite(e));r+=1)s=16*s+e;a+=String.fromCharCode(s)}else{if("string"!=typeof n[t])break;a+=n[t]}else a+=t}i("Bad string")}function c(){for(;t&&t<=" ";)o()}function u(){switch(c(),t){case"{":return function(){var e,r={};if("{"===t){if(o("{"),c(),"}"===t)return o("}"),r;for(;t;){if(e=a(),c(),o(":"),Object.prototype.hasOwnProperty.call(r,e)&&i('Duplicate key "'+e+'"'),r[e]=u(),c(),"}"===t)return o("}"),r;o(","),c()}}i("Bad object")}();case"[":return function(){var e=[];if("["===t){if(o("["),c(),"]"===t)return o("]"),e;for(;t;){if(e.push(u()),c(),"]"===t)return o("]"),e;o(","),c()}}i("Bad array")}();case'"':return a();case"-":return s();default:return t>="0"&&t<="9"?s():function(){switch(t){case"t":return o("t"),o("r"),o("u"),o("e"),!0;case"f":return o("f"),o("a"),o("l"),o("s"),o("e"),!1;case"n":return o("n"),o("u"),o("l"),o("l"),null;default:i("Unexpected '"+t+"'")}}()}}return dc=function(n,o){var s;return r=n,e=0,t=" ",s=u(),c(),t&&i("Syntax error"),"function"==typeof o?function e(t,r){var n,i,s=t[r];if(s&&"object"==typeof s)for(n in u)Object.prototype.hasOwnProperty.call(s,n)&&(void 0===(i=e(s,n))?delete s[n]:s[n]=i);return o.call(t,r,s)}({"":s},""):s},dc}function Sc(){if(mc)return gc;mc=1;var e,t,r,n=/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,i={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function o(e){return n.lastIndex=0,n.test(e)?'"'+e.replace(n,function(e){var t=i[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function s(n,i){var a,c,u,l,h,f=e,d=i[n];switch(d&&"object"==typeof d&&"function"==typeof d.toJSON&&(d=d.toJSON(n)),"function"==typeof r&&(d=r.call(i,n,d)),typeof d){case"string":return o(d);case"number":return isFinite(d)?String(d):"null";case"boolean":case"null":return String(d);case"object":if(!d)return"null";if(e+=t,h=[],"[object Array]"===Object.prototype.toString.apply(d)){for(l=d.length,a=0;a<l;a+=1)h[a]=s(a,d)||"null";return u=0===h.length?"[]":e?"[\n"+e+h.join(",\n"+e)+"\n"+f+"]":"["+h.join(",")+"]",e=f,u}if(r&&"object"==typeof r)for(l=r.length,a=0;a<l;a+=1)"string"==typeof(c=r[a])&&(u=s(c,d))&&h.push(o(c)+(e?": ":":")+u);else for(c in d)Object.prototype.hasOwnProperty.call(d,c)&&(u=s(c,d))&&h.push(o(c)+(e?": ":":")+u);return u=0===h.length?"{}":e?"{\n"+e+h.join(",\n"+e)+"\n"+f+"}":"{"+h.join(",")+"}",e=f,u}}return gc=function(n,i,o){var a;if(e="",t="","number"==typeof o)for(a=0;a<o;a+=1)t+=" ";else"string"==typeof o&&(t=o);if(r=i,i&&"function"!=typeof i&&("object"!=typeof i||"number"!=typeof i.length))throw new Error("JSON.stringify");return s("",{"":n})}}function Oc(){if(Ec)return vc;Ec=1;var e=Object.prototype.toString;return vc=function(t){var r=e.call(t),n="[object Arguments]"===r;return n||(n="[object Array]"!==r&&null!==t&&"object"==typeof t&&"number"==typeof t.length&&t.length>=0&&"[object Function]"===e.call(t.callee)),n}}function Uc(){if(_c)return Ic;var e;if(_c=1,!Object.keys){var t=Object.prototype.hasOwnProperty,r=Object.prototype.toString,n=Oc(),i=Object.prototype.propertyIsEnumerable,o=!i.call({toString:null},"toString"),s=i.call(function(){},"prototype"),a=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],c=function(e){var t=e.constructor;return t&&t.prototype===e},u={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},l=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!u["$"+e]&&t.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{c(window[e])}catch(e){return!0}}catch(e){return!0}return!1}();e=function(e){var i=null!==e&&"object"==typeof e,u="[object Function]"===r.call(e),h=n(e),f=i&&"[object String]"===r.call(e),d=[];if(!i&&!u&&!h)throw new TypeError("Object.keys called on a non-object");var p=s&&u;if(f&&e.length>0&&!t.call(e,0))for(var g=0;g<e.length;++g)d.push(String(g));if(h&&e.length>0)for(var m=0;m<e.length;++m)d.push(String(m));else for(var y in e)p&&"prototype"===y||!t.call(e,y)||d.push(String(y));if(o)for(var w=function(e){if("undefined"==typeof window||!l)return c(e);try{return c(e)}catch(e){return!1}}(e),b=0;b<a.length;++b)w&&"constructor"===a[b]||!t.call(e,a[b])||d.push(a[b]);return d}}return Ic=e}function Cc(){if(kc)return Ac;kc=1;var e=Array.prototype.slice,t=Oc(),r=Object.keys,n=r?function(e){return r(e)}:Uc(),i=Object.keys;return n.shim=function(){if(Object.keys){var r=function(){var e=Object.keys(arguments);return e&&e.length===arguments.length}(1,2);r||(Object.keys=function(r){return t(r)?i(e.call(r)):i(r)})}else Object.keys=n;return Object.keys||n},Ac=n}var Nc,Rc,Tc,Lc,Dc,jc,Mc,Pc,Fc,qc,Qc,zc,$c,Hc,Vc,Gc,Kc,Wc,Jc,Zc,Yc,Xc,eu,tu,ru,nu,iu,ou,su,au,cu,uu,lu,hu,fu,du,pu,gu,mu,yu,wu,bu,vu,Eu,Iu,_u,Au,ku,Bu,xu,Su,Ou,Uu,Cu,Nu,Ru,Tu,Lu,Du,ju,Mu,Pu,Fu,qu,Qu,zu,$u,Hu,Vu,Gu,Ku,Wu,Ju,Zu,Yu,Xu,el,tl,rl,nl,il,ol={exports:{}};function sl(){return Rc?Nc:(Rc=1,Nc=Object)}function al(){return Lc?Tc:(Lc=1,Tc=Error)}function cl(){return jc?Dc:(jc=1,Dc=EvalError)}function ul(){return Pc?Mc:(Pc=1,Mc=RangeError)}function ll(){return qc?Fc:(qc=1,Fc=ReferenceError)}function hl(){return zc?Qc:(zc=1,Qc=SyntaxError)}function fl(){return Hc?$c:(Hc=1,$c=TypeError)}function dl(){return Gc?Vc:(Gc=1,Vc=URIError)}function pl(){return Wc?Kc:(Wc=1,Kc=Math.abs)}function gl(){return Zc?Jc:(Zc=1,Jc=Math.floor)}function ml(){return Xc?Yc:(Xc=1,Yc=Math.max)}function yl(){return tu?eu:(tu=1,eu=Math.min)}function wl(){return nu?ru:(nu=1,ru=Math.pow)}function bl(){return ou?iu:(ou=1,iu=Math.round)}function vl(){if(uu)return cu;uu=1;var e=au?su:(au=1,su=Number.isNaN||function(e){return e!=e});return cu=function(t){return e(t)||0===t?t:t<0?-1:1}}function El(){if(du)return fu;du=1;var e=hu?lu:(hu=1,lu=Object.getOwnPropertyDescriptor);if(e)try{e([],"length")}catch(t){e=null}return fu=e}function Il(){if(gu)return pu;gu=1;var e=Object.defineProperty||!1;if(e)try{e({},"a",{value:1})}catch(t){e=!1}return pu=e}function _l(){if(bu)return wu;bu=1;var e="undefined"!=typeof Symbol&&Symbol,t=yu?mu:(yu=1,mu=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(var n in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var i=Object.getOwnPropertySymbols(e);if(1!==i.length||i[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var o=Object.getOwnPropertyDescriptor(e,t);if(42!==o.value||!0!==o.enumerable)return!1}return!0});return wu=function(){return"function"==typeof e&&("function"==typeof Symbol&&("symbol"==typeof e("foo")&&("symbol"==typeof Symbol("bar")&&t())))}}function Al(){return Eu?vu:(Eu=1,vu="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function kl(){return _u?Iu:(_u=1,Iu=sl().getPrototypeOf||null)}function Bl(){if(ku)return Au;ku=1;var e=Object.prototype.toString,t=Math.max,r=function(e,t){for(var r=[],n=0;n<e.length;n+=1)r[n]=e[n];for(var i=0;i<t.length;i+=1)r[i+e.length]=t[i];return r};return Au=function(n){var i=this;if("function"!=typeof i||"[object Function]"!==e.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var o,s=function(e,t){for(var r=[],n=t,i=0;n<e.length;n+=1,i+=1)r[i]=e[n];return r}(arguments,1),a=t(0,i.length-s.length),c=[],u=0;u<a;u++)c[u]="$"+u;if(o=Function("binder","return function ("+function(e,t){for(var r="",n=0;n<e.length;n+=1)r+=e[n],n+1<e.length&&(r+=t);return r}(c,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof o){var e=i.apply(this,r(s,arguments));return Object(e)===e?e:this}return i.apply(n,r(s,arguments))}),i.prototype){var l=function(){};l.prototype=i.prototype,o.prototype=new l,l.prototype=null}return o},Au}function xl(){if(xu)return Bu;xu=1;var e=Bl();return Bu=Function.prototype.bind||e}function Sl(){return Ou?Su:(Ou=1,Su=Function.prototype.call)}function Ol(){return Cu?Uu:(Cu=1,Uu=Function.prototype.apply)}function Ul(){if(Lu)return Tu;Lu=1;var e=xl(),t=Ol(),r=Sl(),n=Ru?Nu:(Ru=1,Nu="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return Tu=n||e.call(r,t)}function Cl(){if(ju)return Du;ju=1;var e=xl(),t=fl(),r=Sl(),n=Ul();return Du=function(i){if(i.length<1||"function"!=typeof i[0])throw new t("a function is required");return n(e,r,i)}}function Nl(){if(Pu)return Mu;Pu=1;var e,t=Cl(),r=El();try{e=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var n=!!e&&r&&r(Object.prototype,"__proto__"),i=Object,o=i.getPrototypeOf;return Mu=n&&"function"==typeof n.get?t([n.get]):"function"==typeof o&&function(e){return o(null==e?e:i(e))}}function Rl(){if(qu)return Fu;qu=1;var e=Al(),t=kl(),r=Nl();return Fu=e?function(t){return e(t)}:t?function(e){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("getProto: not an object");return t(e)}:r?function(e){return r(e)}:null}function Tl(){if(zu)return Qu;zu=1;var e=Function.prototype.call,t=Object.prototype.hasOwnProperty,r=xl();return Qu=r.call(e,t)}function Ll(){if(Hu)return $u;var e;Hu=1;var t=sl(),r=al(),n=cl(),i=ul(),o=ll(),s=hl(),a=fl(),c=dl(),u=pl(),l=gl(),h=ml(),f=yl(),d=wl(),p=bl(),g=vl(),m=Function,y=function(e){try{return m('"use strict"; return ('+e+").constructor;")()}catch(e){}},w=El(),b=Il(),v=function(){throw new a},E=w?function(){try{return v}catch(e){try{return w(arguments,"callee").get}catch(e){return v}}}():v,I=_l()(),_=Rl(),A=kl(),k=Al(),B=Ol(),x=Sl(),S={},O="undefined"!=typeof Uint8Array&&_?_(Uint8Array):e,U={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?e:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?e:ArrayBuffer,"%ArrayIteratorPrototype%":I&&_?_([][Symbol.iterator]()):e,"%AsyncFromSyncIteratorPrototype%":e,"%AsyncFunction%":S,"%AsyncGenerator%":S,"%AsyncGeneratorFunction%":S,"%AsyncIteratorPrototype%":S,"%Atomics%":"undefined"==typeof Atomics?e:Atomics,"%BigInt%":"undefined"==typeof BigInt?e:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?e:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?e:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?e:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":r,"%eval%":eval,"%EvalError%":n,"%Float16Array%":"undefined"==typeof Float16Array?e:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?e:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?e:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?e:FinalizationRegistry,"%Function%":m,"%GeneratorFunction%":S,"%Int8Array%":"undefined"==typeof Int8Array?e:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?e:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?e:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":I&&_?_(_([][Symbol.iterator]())):e,"%JSON%":"object"==typeof JSON?JSON:e,"%Map%":"undefined"==typeof Map?e:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&I&&_?_((new Map)[Symbol.iterator]()):e,"%Math%":Math,"%Number%":Number,"%Object%":t,"%Object.getOwnPropertyDescriptor%":w,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?e:Promise,"%Proxy%":"undefined"==typeof Proxy?e:Proxy,"%RangeError%":i,"%ReferenceError%":o,"%Reflect%":"undefined"==typeof Reflect?e:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?e:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&I&&_?_((new Set)[Symbol.iterator]()):e,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?e:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":I&&_?_(""[Symbol.iterator]()):e,"%Symbol%":I?Symbol:e,"%SyntaxError%":s,"%ThrowTypeError%":E,"%TypedArray%":O,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?e:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?e:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?e:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?e:Uint32Array,"%URIError%":c,"%WeakMap%":"undefined"==typeof WeakMap?e:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?e:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?e:WeakSet,"%Function.prototype.call%":x,"%Function.prototype.apply%":B,"%Object.defineProperty%":b,"%Object.getPrototypeOf%":A,"%Math.abs%":u,"%Math.floor%":l,"%Math.max%":h,"%Math.min%":f,"%Math.pow%":d,"%Math.round%":p,"%Math.sign%":g,"%Reflect.getPrototypeOf%":k};if(_)try{null.error}catch(e){var C=_(_(e));U["%Error.prototype%"]=C}var N=function e(t){var r;if("%AsyncFunction%"===t)r=y("async function () {}");else if("%GeneratorFunction%"===t)r=y("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=y("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&_&&(r=_(i.prototype))}return U[t]=r,r},R={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},T=xl(),L=Tl(),D=T.call(x,Array.prototype.concat),j=T.call(B,Array.prototype.splice),M=T.call(x,String.prototype.replace),P=T.call(x,String.prototype.slice),F=T.call(x,RegExp.prototype.exec),q=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,Q=/\\(\\)?/g,z=function(e,t){var r,n=e;if(L(R,n)&&(n="%"+(r=R[n])[0]+"%"),L(U,n)){var i=U[n];if(i===S&&(i=N(n)),void 0===i&&!t)throw new a("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:i}}throw new s("intrinsic "+e+" does not exist!")};return $u=function(e,t){if("string"!=typeof e||0===e.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new a('"allowMissing" argument must be a boolean');if(null===F(/^%?[^%]*%?$/,e))throw new s("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var r=function(e){var t=P(e,0,1),r=P(e,-1);if("%"===t&&"%"!==r)throw new s("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new s("invalid intrinsic syntax, expected opening `%`");var n=[];return M(e,q,function(e,t,r,i){n[n.length]=r?M(i,Q,"$1"):t||e}),n}(e),n=r.length>0?r[0]:"",i=z("%"+n+"%",t),o=i.name,c=i.value,u=!1,l=i.alias;l&&(n=l[0],j(r,D([0,1],l)));for(var h=1,f=!0;h<r.length;h+=1){var d=r[h],p=P(d,0,1),g=P(d,-1);if(('"'===p||"'"===p||"`"===p||'"'===g||"'"===g||"`"===g)&&p!==g)throw new s("property names with quotes must have matching quotes");if("constructor"!==d&&f||(u=!0),L(U,o="%"+(n+="."+d)+"%"))c=U[o];else if(null!=c){if(!(d in c)){if(!t)throw new a("base intrinsic for "+e+" exists, but the property is not available.");return}if(w&&h+1>=r.length){var m=w(c,d);c=(f=!!m)&&"get"in m&&!("originalValue"in m.get)?m.get:c[d]}else f=L(c,d),c=c[d];f&&!u&&(U[o]=c)}}return c},$u}function Dl(){if(Gu)return Vu;Gu=1;var e=Il(),t=hl(),r=fl(),n=El();return Vu=function(i,o,s){if(!i||"object"!=typeof i&&"function"!=typeof i)throw new r("`obj` must be an object or a function`");if("string"!=typeof o&&"symbol"!=typeof o)throw new r("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new r("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new r("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new r("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new r("`loose`, if provided, must be a boolean");var a=arguments.length>3?arguments[3]:null,c=arguments.length>4?arguments[4]:null,u=arguments.length>5?arguments[5]:null,l=arguments.length>6&&arguments[6],h=!!n&&n(i,o);if(e)e(i,o,{configurable:null===u&&h?h.configurable:!u,enumerable:null===a&&h?h.enumerable:!a,value:s,writable:null===c&&h?h.writable:!c});else{if(!l&&(a||c||u))throw new t("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");i[o]=s}},Vu}function jl(){if(Wu)return Ku;Wu=1;var e=Il(),t=function(){return!!e};return t.hasArrayLengthDefineBug=function(){if(!e)return null;try{return 1!==e([],"length",{value:1}).length}catch(e){return!0}},Ku=t}function Ml(){if(Zu)return Ju;Zu=1;var e=Ll(),t=Dl(),r=jl()(),n=El(),i=fl(),o=e("%Math.floor%");return Ju=function(e,s){if("function"!=typeof e)throw new i("`fn` is not a function");if("number"!=typeof s||s<0||s>4294967295||o(s)!==s)throw new i("`length` must be a positive 32-bit integer");var a=arguments.length>2&&!!arguments[2],c=!0,u=!0;if("length"in e&&n){var l=n(e,"length");l&&!l.configurable&&(c=!1),l&&!l.writable&&(u=!1)}return(c||u||!a)&&(r?t(e,"length",s,!0,!0):t(e,"length",s)),e},Ju}function Pl(){if(Xu)return Yu;Xu=1;var e=xl(),t=Ol(),r=Ul();return Yu=function(){return r(e,t,arguments)},Yu}function Fl(){return el||(el=1,function(e){var t=Ml(),r=Il(),n=Cl(),i=Pl();e.exports=function(e){var r=n(arguments),i=e.length-(arguments.length-1);return t(r,1+(i>0?i:0),!0)},r?r(e.exports,"apply",{value:i}):e.exports.apply=i}(ol)),ol.exports}function ql(){if(rl)return tl;rl=1;var e=Ll(),t=Cl(),r=t([e("%String.prototype.indexOf%")]);return tl=function(n,i){var o=e(n,!!i);return"function"==typeof o&&r(n,".prototype.")>-1?t([o]):o}}var Ql,zl=function(){if(il)return nl;il=1;var e=("undefined"!=typeof JSON?JSON:(yc||(yc=1,Bc.parse=xc(),Bc.stringify=Sc()),Bc)).stringify,t=function(){if(bc)return wc;bc=1;var e={}.toString;return wc=Array.isArray||function(t){return"[object Array]"==e.call(t)}}(),r=Cc(),n=Fl(),i=ql(),o=i("Array.prototype.join"),s=i("Array.prototype.indexOf"),a=i("Array.prototype.splice"),c=i("Array.prototype.sort"),u=function(e,t){for(var r="",n=0;n<e;n+=1)r+=t;return r},l=function(e,t,r){return r};return nl=function(i){var h=arguments.length>1?arguments[1]:void 0,f=h&&h.space||"";"number"==typeof f&&(f=u(f," "));var d=!!h&&"boolean"==typeof h.cycles&&h.cycles,p=h&&h.replacer?n(h.replacer):l;if(h&&void 0!==h.collapseEmpty&&"boolean"!=typeof h.collapseEmpty)throw new TypeError("`collapseEmpty` must be a boolean, if provided");var g=!!h&&h.collapseEmpty,m="function"==typeof h?h:h&&h.cmp,y=m&&function(e){var t=m.length>2&&function(t){return e[t]};return function(r,n){return m({key:r,value:e[r]},{key:n,value:e[n]},t?{__proto__:null,get:t}:void 0)}},w=[];return function n(i,l,h,m){var b=f?"\n"+u(m,f):"",v=f?": ":":";if(h&&h.toJSON&&"function"==typeof h.toJSON&&(h=h.toJSON()),void 0!==(h=p(i,l,h))){if("object"!=typeof h||null===h)return e(h);var E=function(e,t){return g&&0===e.length?t:("[]"===t?"[":"{")+o(e,",")+b+("[]"===t?"]":"}")};if(t(h)){for(var I=[],_=0;_<h.length;_++){var A=n(h,_,h[_],m+1)||e(null);I[I.length]=b+f+A}return E(I,"[]")}if(-1!==s(w,h)){if(d)return e("__cycle__");throw new TypeError("Converting circular structure to JSON")}w[w.length]=h;var k=c(r(h),y&&y(h));for(I=[],_=0;_<k.length;_++){var B=n(h,l=k[_],h[l],m+1);if(B){var x=e(l)+v+B;I[I.length]=b+f+x}}return a(w,s(w,h),1),E(I,"{}")}}({"":i},"",i,0)},nl}(),$l=Es(zl);function Hl(e,t,r,n){return new(r||(r=Promise))(function(t,i){function o(e){try{a(n.next(e))}catch(e){i(e)}}function s(e){try{a(n.throw(e))}catch(e){i(e)}}function a(e){var n;e.done?t(e.value):(n=e.value,n instanceof r?n:new r(function(e){e(n)})).then(o,s)}a((n=n.apply(e,[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class Vl{constructor(){this.mutex=Promise.resolve()}lock(){let e=()=>{};return this.mutex=this.mutex.then(()=>new Promise(e)),new Promise(t=>{e=t})}dispatch(e){return Hl(this,0,void 0,function*(){const t=yield this.lock();try{return yield Promise.resolve(e())}finally{t()}})}}const Gl="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:ct,Kl=null!==(Ql=Gl.Buffer)&&void 0!==Ql?Ql:null,Wl=Gl.TextEncoder?new Gl.TextEncoder:null;function Jl(e,t){return(15&e)+(e>>6|e>>3&8)<<4|(15&t)+(t>>6|t>>3&8)}const Zl="a".charCodeAt(0)-10,Yl="0".charCodeAt(0);function Xl(e,t,r){let n=0;for(let i=0;i<r;i++){let r=t[i]>>>4;e[n++]=r>9?r+Zl:r+Yl,r=15&t[i],e[n++]=r>9?r+Zl:r+Yl}return String.fromCharCode.apply(null,e)}const eh=null!==Kl?e=>{if("string"==typeof e){const t=Kl.from(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.length)}if(Kl.isBuffer(e))return new Uint8Array(e.buffer,e.byteOffset,e.length);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")}:e=>{if("string"==typeof e)return Wl.encode(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Invalid data type!")},th="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",rh=new Uint8Array(256);for(let e=0;e<64;e++)rh[th.charCodeAt(e)]=e;function nh(e){const t=function(e){let t=Math.floor(.75*e.length);const r=e.length;return"="===e[r-1]&&(t-=1,"="===e[r-2]&&(t-=1)),t}(e),r=e.length,n=new Uint8Array(t);let i=0;for(let t=0;t<r;t+=4){const r=rh[e.charCodeAt(t)],o=rh[e.charCodeAt(t+1)],s=rh[e.charCodeAt(t+2)],a=rh[e.charCodeAt(t+3)];n[i]=r<<2|o>>4,i+=1,n[i]=(15&o)<<4|s>>2,i+=1,n[i]=(3&s)<<6|63&a,i+=1}return n}const ih=16384,oh=new Vl,sh=new Map;function ah(e,t){return Hl(this,0,void 0,function*(){let r=null,n=null,i=!1;if("undefined"==typeof WebAssembly)throw new Error("WebAssembly is not supported in this environment!");const o=()=>new DataView(r.exports.memory.buffer).getUint32(r.exports.STATE_SIZE,!0),s=oh.dispatch(()=>Hl(this,0,void 0,function*(){if(!sh.has(e.name)){const t=nh(e.data),r=WebAssembly.compile(t);sh.set(e.name,r)}const t=yield sh.get(e.name);r=yield WebAssembly.instantiate(t,{})})),a=(e=null)=>{i=!0,r.exports.Hash_Init(e)},c=e=>{if(!i)throw new Error("update() called before init()");(e=>{let t=0;for(;t<e.length;){const i=e.subarray(t,t+ih);t+=i.length,n.set(i),r.exports.Hash_Update(i.length)}})(eh(e))},u=new Uint8Array(2*t),l=(e,o=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,r.exports.Hash_Final(o),"binary"===e?n.slice(0,t):Xl(u,n,t)},h=e=>"string"==typeof e?e.length<4096:e.byteLength<ih;let f=h;switch(e.name){case"argon2":case"scrypt":f=()=>!0;break;case"blake2b":case"blake2s":f=(e,t)=>t<=512&&h(e);break;case"blake3":f=(e,t)=>0===t&&h(e);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":f=()=>!1}return yield(()=>Hl(this,0,void 0,function*(){r||(yield s);const e=r.exports.Hash_GetBuffer(),t=r.exports.memory.buffer;n=new Uint8Array(t,e,ih)}))(),{getMemory:()=>n,writeMemory:(e,t=0)=>{n.set(e,t)},getExports:()=>r.exports,setMemorySize:e=>{r.exports.Hash_SetMemorySize(e);const t=r.exports.Hash_GetBuffer(),i=r.exports.memory.buffer;n=new Uint8Array(i,t,e)},init:a,update:c,digest:l,save:()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");const t=r.exports.Hash_GetState(),n=o(),s=r.exports.memory.buffer,a=new Uint8Array(s,t,n),c=new Uint8Array(4+n);return function(e,t){const r=t.length>>1;for(let n=0;n<r;n++){const r=n<<1;e[n]=Jl(t.charCodeAt(r),t.charCodeAt(r+1))}}(c,e.hash),c.set(a,4),c},load:t=>{if(!(t instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");const n=r.exports.Hash_GetState(),s=o(),a=4+s,c=r.exports.memory.buffer;if(t.length!==a)throw new Error(`Bad state length (expected ${a} bytes, got ${t.length})`);if(!function(e,t){if(e.length!==2*t.length)return!1;for(let r=0;r<t.length;r++){const n=r<<1;if(t[r]!==Jl(e.charCodeAt(n),e.charCodeAt(n+1)))return!1}return!0}(e.hash,t.subarray(0,4)))throw new Error("This state was written by an incompatible hash implementation");const u=t.subarray(4);new Uint8Array(c,n,s).set(u),i=!0},calculate:(e,i=null,o=null)=>{if(!f(e,i))return a(i),c(e),l("hex",o);const s=eh(e);return n.set(s),r.exports.Hash_Calculate(s.length,i,o),Xl(u,n,t)},hashLength:t}})}new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl;var ch={name:"md5",data:"AGFzbQEAAAABEgRgAAF/YAAAYAF/AGACf38BfwMIBwABAgMBAAIFBAEBAgIGDgJ/AUGgigULfwBBgAgLB3AIBm1lbW9yeQIADkhhc2hfR2V0QnVmZmVyAAAJSGFzaF9Jbml0AAELSGFzaF9VcGRhdGUAAgpIYXNoX0ZpbmFsAAQNSGFzaF9HZXRTdGF0ZQAFDkhhc2hfQ2FsY3VsYXRlAAYKU1RBVEVfU0laRQMBCoMaBwUAQYAJCy0AQQBC/rnrxemOlZkQNwKQiQFBAEKBxpS6lvHq5m83AoiJAUEAQgA3AoCJAQu+BQEHf0EAQQAoAoCJASIBIABqQf////8BcSICNgKAiQFBAEEAKAKEiQEgAiABSWogAEEddmo2AoSJAQJAAkACQAJAAkACQCABQT9xIgMNAEGACSEEDAELIABBwAAgA2siBUkNASAFQQNxIQZBACEBAkAgA0E/c0EDSQ0AIANBgIkBaiEEIAVB/ABxIQdBACEBA0AgBCABaiICQRhqIAFBgAlqLQAAOgAAIAJBGWogAUGBCWotAAA6AAAgAkEaaiABQYIJai0AADoAACACQRtqIAFBgwlqLQAAOgAAIAcgAUEEaiIBRw0ACwsCQCAGRQ0AIANBmIkBaiECA0AgAiABaiABQYAJai0AADoAACABQQFqIQEgBkF/aiIGDQALC0GYiQFBwAAQAxogACAFayEAIAVBgAlqIQQLIABBwABPDQEgACECDAILIABFDQIgAEEDcSEGQQAhAQJAIABBBEkNACADQYCJAWohBCAAQXxxIQBBACEBA0AgBCABaiICQRhqIAFBgAlqLQAAOgAAIAJBGWogAUGBCWotAAA6AAAgAkEaaiABQYIJai0AADoAACACQRtqIAFBgwlqLQAAOgAAIAAgAUEEaiIBRw0ACwsgBkUNAiADQZiJAWohAgNAIAIgAWogAUGACWotAAA6AAAgAUEBaiEBIAZBf2oiBg0ADAMLCyAAQT9xIQIgBCAAQUBxEAMhBAsgAkUNACACQQNxIQZBACEBAkAgAkEESQ0AIAJBPHEhAEEAIQEDQCABQZiJAWogBCABaiICLQAAOgAAIAFBmYkBaiACQQFqLQAAOgAAIAFBmokBaiACQQJqLQAAOgAAIAFBm4kBaiACQQNqLQAAOgAAIAAgAUEEaiIBRw0ACwsgBkUNAANAIAFBmIkBaiAEIAFqLQAAOgAAIAFBAWohASAGQX9qIgYNAAsLC4cQARl/QQAoApSJASECQQAoApCJASEDQQAoAoyJASEEQQAoAoiJASEFA0AgACgCCCIGIAAoAhgiByAAKAIoIgggACgCOCIJIAAoAjwiCiAAKAIMIgsgACgCHCIMIAAoAiwiDSAMIAsgCiANIAkgCCAHIAMgBmogAiAAKAIEIg5qIAUgBCACIANzcSACc2ogACgCACIPakH4yKq7fWpBB3cgBGoiECAEIANzcSADc2pB1u6exn5qQQx3IBBqIhEgECAEc3EgBHNqQdvhgaECakERdyARaiISaiAAKAIUIhMgEWogACgCECIUIBBqIAQgC2ogEiARIBBzcSAQc2pB7p33jXxqQRZ3IBJqIhAgEiARc3EgEXNqQa+f8Kt/akEHdyAQaiIRIBAgEnNxIBJzakGqjJ+8BGpBDHcgEWoiEiARIBBzcSAQc2pBk4zBwXpqQRF3IBJqIhVqIAAoAiQiFiASaiAAKAIgIhcgEWogDCAQaiAVIBIgEXNxIBFzakGBqppqakEWdyAVaiIQIBUgEnNxIBJzakHYsYLMBmpBB3cgEGoiESAQIBVzcSAVc2pBr++T2nhqQQx3IBFqIhIgESAQc3EgEHNqQbG3fWpBEXcgEmoiFWogACgCNCIYIBJqIAAoAjAiGSARaiANIBBqIBUgEiARc3EgEXNqQb6v88p4akEWdyAVaiIQIBUgEnNxIBJzakGiosDcBmpBB3cgEGoiESAQIBVzcSAVc2pBk+PhbGpBDHcgEWoiFSARIBBzcSAQc2pBjofls3pqQRF3IBVqIhJqIAcgFWogDiARaiAKIBBqIBIgFSARc3EgEXNqQaGQ0M0EakEWdyASaiIQIBJzIBVxIBJzakHiyviwf2pBBXcgEGoiESAQcyAScSAQc2pBwOaCgnxqQQl3IBFqIhIgEXMgEHEgEXNqQdG0+bICakEOdyASaiIVaiAIIBJqIBMgEWogDyAQaiAVIBJzIBFxIBJzakGqj9vNfmpBFHcgFWoiECAVcyAScSAVc2pB3aC8sX1qQQV3IBBqIhEgEHMgFXEgEHNqQdOokBJqQQl3IBFqIhIgEXMgEHEgEXNqQYHNh8V9akEOdyASaiIVaiAJIBJqIBYgEWogFCAQaiAVIBJzIBFxIBJzakHI98++fmpBFHcgFWoiECAVcyAScSAVc2pB5puHjwJqQQV3IBBqIhEgEHMgFXEgEHNqQdaP3Jl8akEJdyARaiISIBFzIBBxIBFzakGHm9Smf2pBDncgEmoiFWogBiASaiAYIBFqIBcgEGogFSAScyARcSASc2pB7anoqgRqQRR3IBVqIhAgFXMgEnEgFXNqQYXSj896akEFdyAQaiIRIBBzIBVxIBBzakH4x75nakEJdyARaiISIBFzIBBxIBFzakHZhby7BmpBDncgEmoiFWogFyASaiATIBFqIBkgEGogFSAScyARcSASc2pBipmp6XhqQRR3IBVqIhAgFXMiFSASc2pBwvJoakEEdyAQaiIRIBVzakGB7ce7eGpBC3cgEWoiEiARcyIaIBBzakGiwvXsBmpBEHcgEmoiFWogFCASaiAOIBFqIAkgEGogFSAac2pBjPCUb2pBF3cgFWoiECAVcyIVIBJzakHE1PulempBBHcgEGoiESAVc2pBqZ/73gRqQQt3IBFqIhIgEXMiCSAQc2pB4JbttX9qQRB3IBJqIhVqIA8gEmogGCARaiAIIBBqIBUgCXNqQfD4/vV7akEXdyAVaiIQIBVzIhUgEnNqQcb97cQCakEEdyAQaiIRIBVzakH6z4TVfmpBC3cgEWoiEiARcyIIIBBzakGF4bynfWpBEHcgEmoiFWogGSASaiAWIBFqIAcgEGogFSAIc2pBhbqgJGpBF3cgFWoiESAVcyIQIBJzakG5oNPOfWpBBHcgEWoiEiAQc2pB5bPutn5qQQt3IBJqIhUgEnMiByARc2pB+PmJ/QFqQRB3IBVqIhBqIAwgFWogDyASaiAGIBFqIBAgB3NqQeWssaV8akEXdyAQaiIRIBVBf3NyIBBzakHExKShf2pBBncgEWoiEiAQQX9zciARc2pBl/+rmQRqQQp3IBJqIhAgEUF/c3IgEnNqQafH0Nx6akEPdyAQaiIVaiALIBBqIBkgEmogEyARaiAVIBJBf3NyIBBzakG5wM5kakEVdyAVaiIRIBBBf3NyIBVzakHDs+2qBmpBBncgEWoiECAVQX9zciARc2pBkpmz+HhqQQp3IBBqIhIgEUF/c3IgEHNqQf3ov39qQQ93IBJqIhVqIAogEmogFyAQaiAOIBFqIBUgEEF/c3IgEnNqQdG7kax4akEVdyAVaiIQIBJBf3NyIBVzakHP/KH9BmpBBncgEGoiESAVQX9zciAQc2pB4M2zcWpBCncgEWoiEiAQQX9zciARc2pBlIaFmHpqQQ93IBJqIhVqIA0gEmogFCARaiAYIBBqIBUgEUF/c3IgEnNqQaGjoPAEakEVdyAVaiIQIBJBf3NyIBVzakGC/c26f2pBBncgEGoiESAVQX9zciAQc2pBteTr6XtqQQp3IBFqIhIgEEF/c3IgEXNqQbul39YCakEPdyASaiIVIARqIBYgEGogFSARQX9zciASc2pBkaeb3H5qQRV3aiEEIBUgA2ohAyASIAJqIQIgESAFaiEFIABBwABqIQAgAUFAaiIBDQALQQAgAjYClIkBQQAgAzYCkIkBQQAgBDYCjIkBQQAgBTYCiIkBIAALyAMBBX9BACgCgIkBQT9xIgBBmIkBakGAAToAACAAQQFqIQECQAJAAkACQCAAQT9zIgJBB0sNACACRQ0BIAFBmIkBakEAOgAAIAJBAUYNASAAQZqJAWpBADoAACACQQJGDQEgAEGbiQFqQQA6AAAgAkEDRg0BIABBnIkBakEAOgAAIAJBBEYNASAAQZ2JAWpBADoAACACQQVGDQEgAEGeiQFqQQA6AAAgAkEGRg0BIABBn4kBakEAOgAADAELIAJBCEYNAkE2IABrIgMhBAJAIAJBA3EiAEUNAEEAIABrIQRBACEAA0AgAEHPiQFqQQA6AAAgBCAAQX9qIgBHDQALIAMgAGohBAsgA0EDSQ0CDAELQZiJAUHAABADGkEAIQFBNyEECyABQYCJAWohAEF/IQIDQCAAIARqQRVqQQA2AAAgAEF8aiEAIAQgAkEEaiICRw0ACwtBAEEAKAKEiQE2AtSJAUEAQQAoAoCJASIAQRV2OgDTiQFBACAAQQ12OgDSiQFBACAAQQV2OgDRiQFBACAAQQN0IgA6ANCJAUEAIAA2AoCJAUGYiQFBwAAQAxpBAEEAKQKIiQE3A4AJQQBBACkCkIkBNwOICQsGAEGAiQELMwBBAEL+uevF6Y6VmRA3ApCJAUEAQoHGlLqW8ermbzcCiIkBQQBCADcCgIkBIAAQAhAECwsLAQBBgAgLBJgAAAA=",hash:"e6508e4b"};const uh=new Vl;let lh=null;function hh(e){if(null===lh)return function(e,t,r){return Hl(this,0,void 0,function*(){const n=yield e.lock(),i=yield ah(t,r);return n(),i})}(uh,ch,16).then(t=>(lh=t,lh.calculate(e)));try{const t=lh.calculate(e);return Promise.resolve(t)}catch(e){return Promise.reject(e)}}new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl,new Vl;const fh="us-east-1",dh="https://s3.us-east-1.amazonaws.com";class ph{constructor(e){let t;const[r,n,i]=G(()=>new URL(e));if(!r)throw new Se("Invalid connection string: "+e,{original:n,input:e});t=i,this.region=fh,"s3:"===t.protocol?this.defineFromS3(t):this.defineFromCustomUri(t);for(const[e,r]of t.searchParams.entries())this[e]=r}defineFromS3(e){const[t,r,n]=K(()=>decodeURIComponent(e.hostname));if(!t)throw new Se("Invalid bucket in connection string",{original:r,input:e.hostname});this.bucket=n||"s3db";const[i,o,s]=K(()=>decodeURIComponent(e.username));if(!i)throw new Se("Invalid accessKeyId in connection string",{original:o,input:e.username});this.accessKeyId=s;const[a,c,u]=K(()=>decodeURIComponent(e.password));if(!a)throw new Se("Invalid secretAccessKey in connection string",{original:c,input:e.password});if(this.secretAccessKey=u,this.endpoint=dh,["/","",null].includes(e.pathname))this.keyPrefix="";else{let[,...t]=e.pathname.split("/");this.keyPrefix=[...t||[]].join("/")}}defineFromCustomUri(e){this.forcePathStyle=!0,this.endpoint=e.origin;const[t,r,n]=K(()=>decodeURIComponent(e.username));if(!t)throw new Se("Invalid accessKeyId in connection string",{original:r,input:e.username});this.accessKeyId=n;const[i,o,s]=K(()=>decodeURIComponent(e.password));if(!i)throw new Se("Invalid secretAccessKey in connection string",{original:o,input:e.password});if(this.secretAccessKey=s,["/","",null].includes(e.pathname))this.bucket="s3db",this.keyPrefix="";else{let[,t,...r]=e.pathname.split("/");if(t){const[e,r,n]=K(()=>decodeURIComponent(t));if(!e)throw new Se("Invalid bucket in connection string",{original:r,input:t});this.bucket=n}else this.bucket="s3db";this.keyPrefix=[...r||[]].join("/")}}}class gh extends Qe{constructor({verbose:e=!1,id:t=null,AwsS3Client:r,connectionString:n,parallelism:i=10}){super(),this.verbose=e,this.id=t??Me(),this.parallelism=i,this.config=new ph(n),this.client=r||this.createClient()}createClient(){let e={region:this.config.region,endpoint:this.config.endpoint};this.config.forcePathStyle&&(e.forcePathStyle=!0),this.config.accessKeyId&&(e.credentials={accessKeyId:this.config.accessKeyId,secretAccessKey:this.config.secretAccessKey});const t=new y(e);return t.middlewareStack.add((e,t)=>async r=>{if("DeleteObjectsCommand"===t.commandName){const e=r.request.body;if(e&&"string"==typeof e){const t=Buffer.from(await hh(e),"hex").toString("base64");r.request.headers["Content-MD5"]=t}}return e(r)},{step:"build",name:"addContentMd5ForDeleteObjects",priority:"high"}),t}async sendCommand(e){this.emit("command.request",e.constructor.name,e.input);const[t,r,n]=await G(()=>this.client.send(e));if(!t){throw xe(r,{bucket:this.config.bucket,key:e.input&&e.input.Key,commandName:e.constructor.name,commandInput:e.input})}return this.emit("command.response",e.constructor.name,n,e.input),n}async putObject({key:e,metadata:t,contentType:r,body:n,contentEncoding:i,contentLength:o}){const s="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";s&&ot.join(s,e);const a={};if(t)for(const[e,r]of Object.entries(t)){a[String(e).replace(/[^a-zA-Z0-9\-_]/g,"_")]=String(r)}const c={Bucket:this.config.bucket,Key:s?ot.join(s,e):e,Metadata:a,Body:n||Buffer.alloc(0)};let u,l;void 0!==r&&(c.ContentType=r),void 0!==i&&(c.ContentEncoding=i),void 0!==o&&(c.ContentLength=o);try{return u=await this.sendCommand(new w(c)),u}catch(t){throw l=t,xe(t,{bucket:this.config.bucket,key:e,commandName:"PutObjectCommand",commandInput:c})}finally{this.emit("putObject",l||u,{key:e,metadata:t,contentType:r,body:n,contentEncoding:i,contentLength:o})}}async getObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:t?ot.join(t,e):e};let n,i;try{return n=await this.sendCommand(new b(r)),n}catch(t){throw i=t,xe(t,{bucket:this.config.bucket,key:e,commandName:"GetObjectCommand",commandInput:r})}finally{this.emit("getObject",i||n,{key:e})}}async headObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:t?ot.join(t,e):e};let n,i;try{return n=await this.sendCommand(new v(r)),n}catch(t){throw i=t,xe(t,{bucket:this.config.bucket,key:e,commandName:"HeadObjectCommand",commandInput:r})}finally{this.emit("headObject",i||n,{key:e})}}async copyObject({from:e,to:t}){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?ot.join(this.config.keyPrefix,t):t,CopySource:ot.join(this.config.bucket,this.config.keyPrefix?ot.join(this.config.keyPrefix,e):e)};let n,i;try{return n=await this.sendCommand(new E(r)),n}catch(e){throw i=e,xe(e,{bucket:this.config.bucket,key:t,commandName:"CopyObjectCommand",commandInput:r})}finally{this.emit("copyObject",i||n,{from:e,to:t})}}async exists(e){const[t,r]=await G(()=>this.headObject(e));if(t)return!0;if("NoSuchKey"===r.name||"NotFound"===r.name)return!1;throw r}async deleteObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";t&&ot.join(t,e);const r={Bucket:this.config.bucket,Key:t?ot.join(t,e):e};let n,i;try{return n=await this.sendCommand(new I(r)),n}catch(t){throw i=t,xe(t,{bucket:this.config.bucket,key:e,commandName:"DeleteObjectCommand",commandInput:r})}finally{this.emit("deleteObject",i||n,{key:e})}}async deleteObjects(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r=n(e,1e3),{results:i,errors:o}=await m.for(r).withConcurrency(this.parallelism).process(async e=>{for(const r of e)t&&ot.join(t,r),this.config.bucket,await this.exists(r);const r={Bucket:this.config.bucket,Delete:{Objects:e.map(e=>({Key:t?ot.join(t,e):e}))}};let n;const[i,o,s]=await G(()=>this.sendCommand(new _(r)));if(!i)throw o;return n=s,n&&n.Errors&&n.Errors.length,n&&n.Deleted&&(n.Deleted.length,e.length),n}),s={deleted:i,notFound:o};return this.emit("deleteObjects",s,e),s}async deleteAll({prefix:e}={}){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,n=0;do{const i=new A({Bucket:this.config.bucket,Prefix:t?ot.join(t,e||""):e||"",ContinuationToken:r}),o=await this.client.send(i);if(o.Contents&&o.Contents.length>0){const t=new _({Bucket:this.config.bucket,Delete:{Objects:o.Contents.map(e=>({Key:e.Key}))}}),r=await this.client.send(t),i=r.Deleted?r.Deleted.length:0;n+=i,this.emit("deleteAll",{prefix:e,batch:i,total:n})}r=o.IsTruncated?o.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:e,totalDeleted:n}),n}async moveObject({from:e,to:t}){const[r,n]=await G(async()=>{await this.copyObject({from:e,to:t}),await this.deleteObject(e)});if(!r)throw new ke("Unknown error in moveObject",{bucket:this.config.bucket,from:e,to:t,original:n});return!0}async listObjects({prefix:e,maxKeys:t=1e3,continuationToken:r}={}){const n={Bucket:this.config.bucket,MaxKeys:t,ContinuationToken:r,Prefix:this.config.keyPrefix?ot.join(this.config.keyPrefix,e||""):e||""},[i,o,s]=await G(()=>this.sendCommand(new A(n)));if(!i)throw new ke("Unknown error in listObjects",{prefix:e,bucket:this.config.bucket,original:o});return this.emit("listObjects",s,n),s}async count({prefix:e}={}){let t,r=0,n=!0;for(;n;){const i={prefix:e,continuationToken:t},o=await this.listObjects(i);r+=o.KeyCount||0,n=o.IsTruncated||!1,t=o.NextContinuationToken}return this.emit("count",r,{prefix:e}),r}async getAllKeys({prefix:e}={}){let t,r=[],n=!0;for(;n;){const i={prefix:e,continuationToken:t},o=await this.listObjects(i);o.Contents&&(r=r.concat(o.Contents.map(e=>e.Key))),n=o.IsTruncated||!1,t=o.NextContinuationToken}return this.config.keyPrefix&&(r=r.map(e=>e.replace(this.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e)),this.emit("getAllKeys",r,{prefix:e}),r}async getContinuationTokenAfterOffset(e={}){const{prefix:t,offset:r=1e3}=e;if(0===r)return null;let n,i=!0,o=0;for(;i;){const e={prefix:t,maxKeys:r<1e3?r:r-o>1e3?1e3:r-o,continuationToken:n},s=await this.listObjects(e);if(s.Contents&&(o+=s.Contents.length),i=s.IsTruncated||!1,n=s.NextContinuationToken,o>=r)break}return this.emit("getContinuationTokenAfterOffset",n||null,e),n||null}async getKeysPage(e={}){const{prefix:t,offset:r=0,amount:n=100}=e;let i,o=[],s=!0;if(r>0&&(i=await this.getContinuationTokenAfterOffset({prefix:t,offset:r}),!i))return this.emit("getKeysPage",[],e),[];for(;s;){const e={prefix:t,continuationToken:i},r=await this.listObjects(e);if(r.Contents&&(o=o.concat(r.Contents.map(e=>e.Key))),s=r.IsTruncated||!1,i=r.NextContinuationToken,o.length>=n){o=o.slice(0,n);break}}return this.config.keyPrefix&&(o=o.map(e=>e.replace(this.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e)),this.emit("getKeysPage",o,e),o}async moveAllObjects({prefixFrom:e,prefixTo:t}){const r=await this.getAllKeys({prefix:e}),{results:n,errors:i}=await m.for(r).withConcurrency(this.parallelism).process(async r=>{const n=r.replace(e,t),[i,o]=await G(async()=>{await this.moveObject({from:r,to:n})});if(!i)throw new ke("Unknown error in moveAllObjects",{bucket:this.config.bucket,from:r,to:n,original:o});return n});if(this.emit("moveAllObjects",{results:n,errors:i},{prefixFrom:e,prefixTo:t}),i.length>0)throw new Error("Some objects could not be moved");return n}}async function mh(e,t,r){if(!this.passphrase)return t.push(new ge("Missing configuration for secrets encryption.",{actual:e,type:"encryptionKeyMissing",suggestion:"Provide a passphrase for secret encryption."})),e;const[n,i,o]=await G(()=>Le(String(e),this.passphrase));return n?o:(t.push(new ge("Problem encrypting secret.",{actual:e,type:"encryptionProblem",error:i,suggestion:"Check the passphrase and input value."})),e)}async function yh(e,t,r){if(o(e))return e;const[n,i,s]=K(()=>JSON.stringify(e));if(!n)throw new ge("Failed to stringify JSON",{original:i,input:e});return s}class wh extends x{constructor({options:e,passphrase:t,autoEncrypt:r=!0}={}){super(i({},{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}}},e)),this.passphrase=t,this.autoEncrypt=r,this.alias("secret",{type:"string",custom:this.autoEncrypt?mh: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?mh:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?mh:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?yh:void 0})}}const bh=new Proxy(wh,{instance:null,construct(e,t){return this.instance||(this.instance=new e(...t)),this.instance}});const vh={trim:e=>null==e?e:e.trim(),encrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,n,i]=await G(()=>Le(e,t));return r?i:e},decrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,n,i]=await G(()=>De(e,t));return r?"null"===i?null:"undefined"!==i?i:void 0:e},toString:e=>null==e?e:String(e),fromArray:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>"string"==typeof e?e.replace(/\\/g,"\\\\").replace(new RegExp(`\\${t}`,"g"),`\\${t}`):String(e)).join(t)},toArray:(e,{separator:t})=>{if(Array.isArray(e))return e;if(null==e)return e;if(""===e)return[];const r=[];let n="",i=0;const o=String(e);for(;i<o.length;)"\\"===o[i]&&i+1<o.length?(n+=o[i+1],i+=2):o[i]===t?(r.push(n),n="",i++):(n+=o[i],i++);return r.push(n),r},toJSON:e=>{if(null===e)return null;if(void 0===e)return;if("string"==typeof e){const[t,r,n]=K(()=>JSON.parse(e));return e}const[t,r,n]=K(()=>JSON.stringify(e));return t?n:e},fromJSON:e=>{if(null===e)return null;if(void 0===e)return;if("string"!=typeof e)return e;if(""===e)return"";const[t,r,n]=K(()=>JSON.parse(e));return t?n:e},toNumber:e=>o(e)?e.includes(".")?parseFloat(e):parseInt(e):e,toBool:e=>[!0,1,"true","1","yes","y"].includes(e),fromBool:e=>[!0,1,"true","1","yes","y"].includes(e)?"1":"0",fromBase62:e=>{if(null==e||""===e)return e;if("number"==typeof e)return e;if("string"==typeof e){const t=ue(e);return isNaN(t)?void 0:t}},toBase62:e=>{if(null==e||""===e)return e;if("number"==typeof e)return ce(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:ce(t)}return e},fromBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return e;if("string"==typeof e){const t=he(e);return isNaN(t)?void 0:t}},toBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return le(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:le(t)}return e},fromArrayOfNumbers:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>{if("number"==typeof e&&!isNaN(e))return ce(e);const t=Number(e);return isNaN(t)?"":ce(t)}).join(t)},toArrayOfNumbers:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:ue(e));if(null==e)return e;if(""===e)return[];const r=String(e),n=[];let i="",o=0;for(;o<r.length;)"\\"===r[o]&&o+1<r.length?(i+=r[o+1],o+=2):r[o]===t?(n.push(i),i="",o++):(i+=r[o],o++);return n.push(i),n.map(e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e){const t=ue(e);return isNaN(t)?NaN:t}return NaN})},fromArrayOfDecimals:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>{if("number"==typeof e&&!isNaN(e))return le(e);const t=Number(e);return isNaN(t)?"":le(t)}).join(t)},toArrayOfDecimals:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:he(e));if(null==e)return e;if(""===e)return[];const r=String(e),n=[];let i="",o=0;for(;o<r.length;)"\\"===r[o]&&o+1<r.length?(i+=r[o+1],o+=2):r[o]===t?(n.push(i),i="",o++):(i+=r[o],o++);return n.push(i),n.map(e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e){const t=he(e);return isNaN(t)?NaN:t}return NaN})}};class Eh{constructor(e){const{map:t,name:r,attributes:n,passphrase:o,version:c=1,options:u={}}=e;this.name=r,this.version=c,this.attributes=n||{},this.passphrase=o??"secret",this.options=i({},this.defaultOptions(),u),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const l=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new bh({autoEncrypt:!1}).compile(i({$$async:!0},l)),this.options.generateAutoHooks&&this.generateAutoHooks(),s(t)){const e=k(this.attributes,{safe:!0}),t=Object.keys(e).filter(e=>!e.includes("$$")),r=this.extractObjectKeys(this.attributes),n=[...new Set([...t,...r])],{mapping:i,reversedMapping:o}=function(e){const t={},r={};return e.forEach((e,n)=>{const i=ce(n);t[e]=i,r[i]=e}),{mapping:t,reversedMapping:r}}(n);this.map=i,this.reversedMap=o}else this.map=t,this.reversedMap=a(t)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(e,t,r){this.options.hooks[e][t]||(this.options.hooks[e][t]=[]),this.options.hooks[e][t]=c([...this.options.hooks[e][t],r])}extractObjectKeys(e,t=""){const r=[];for(const[n,i]of Object.entries(e)){if(n.startsWith("$$"))continue;const e=t?`${t}.${n}`:n;"object"!=typeof i||null===i||Array.isArray(i)||(r.push(e),"object"===i.$$type&&r.push(...this.extractObjectKeys(i,e)))}return r}generateAutoHooks(){const e=k(u(this.attributes),{safe:!0});for(const[t,r]of Object.entries(e))if(r.includes("array")){if(r.includes("items:string"))this.addHook("beforeMap",t,"fromArray"),this.addHook("afterUnmap",t,"toArray");else if(r.includes("items:number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",t,"fromArrayOfNumbers"),this.addHook("afterUnmap",t,"toArrayOfNumbers")):(this.addHook("beforeMap",t,"fromArrayOfDecimals"),this.addHook("afterUnmap",t,"toArrayOfDecimals"))}}else if(r.includes("secret"))this.options.autoEncrypt&&this.addHook("beforeMap",t,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",t,"decrypt");else{if(r.includes("number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",t,"toBase62"),this.addHook("afterUnmap",t,"fromBase62")):(this.addHook("beforeMap",t,"toBase62Decimal"),this.addHook("afterUnmap",t,"fromBase62Decimal"));continue}r.includes("boolean")?(this.addHook("beforeMap",t,"fromBool"),this.addHook("afterUnmap",t,"toBool")):(r.includes("json")||"object"===r||r.includes("object"))&&(this.addHook("beforeMap",t,"toJSON"),this.addHook("afterUnmap",t,"fromJSON"))}}static import(e){let{map:t,name:r,options:n,version:i,attributes:s}=o(e)?JSON.parse(e):e;const[a,c,u]=K(()=>Eh._importAttributes(s));if(!a)throw new Ue("Failed to import schema attributes",{original:c,input:s});s=u;return new Eh({map:t,name:r,options:n,version:i,attributes:s})}static _importAttributes(e){if("string"==typeof e){const[t,r,n]=K(()=>JSON.parse(e));if(t&&"object"==typeof n&&null!==n){const[t,r,i]=K(()=>Eh._importAttributes(n));if(!t)throw new Ue("Failed to parse nested schema attribute",{original:r,input:e});return i}return e}if(Array.isArray(e)){const[t,r,n]=K(()=>e.map(e=>Eh._importAttributes(e)));if(!t)throw new Ue("Failed to import array schema attributes",{original:r,input:e});return n}if("object"==typeof e&&null!==e){const t={};for(const[r,n]of Object.entries(e)){const[e,i,o]=K(()=>Eh._importAttributes(n));if(!e)throw new Ue("Failed to import object schema attribute",{original:i,key:r,input:n});t[r]=o}return t}return e}export(){return{version:this.version,name:this.name,options:this.options,attributes:this._exportAttributes(this.attributes),map:this.map}}_exportAttributes(e){if("string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>this._exportAttributes(e));if("object"==typeof e&&null!==e){const t={};for(const[r,n]of Object.entries(e))t[r]=this._exportAttributes(n);return t}return e}async applyHooksActions(e,t){const r=u(e);for(const[e,n]of Object.entries(this.options.hooks[t]))for(const t of n){const n=l(r,e);void 0!==n&&"function"==typeof vh[t]&&h(r,e,await vh[t](n,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}return r}async validate(e,{mutateOriginal:t=!1}={}){let r=t?e:u(e);return await this.validator(r)}async mapper(e){let t=u(e);t=await this.applyHooksActions(t,"beforeMap");const r=k(t,{safe:!0}),n={_v:this.version+""};for(const[e,t]of Object.entries(r)){const r=this.map[e]||e,i=this.getAttributeDefinition(e);"number"==typeof t&&"string"==typeof i&&i.includes("number")?n[r]=ce(t):"string"==typeof t?"[object Object]"===t?n[r]="{}":(t.startsWith("{")||t.startsWith("["),n[r]=t):Array.isArray(t)||"object"==typeof t&&null!==t?n[r]=JSON.stringify(t):n[r]=t}return await this.applyHooksActions(n,"afterMap"),n}async unmapper(e,t){let r=u(e);delete r._v,r=await this.applyHooksActions(r,"beforeUnmap");const n=t?a(t):this.reversedMap,i={};for(const[e,t]of Object.entries(r)){const r=n&&n[e]?n[e]:e;let o=t;const s=this.getAttributeDefinition(r);if("string"!=typeof s||!s.includes("number")||s.includes("array")||s.includes("decimal")){if("string"==typeof t)if("[object Object]"===t)o={};else if(t.startsWith("{")||t.startsWith("[")){const[e,r,n]=K(()=>JSON.parse(t));e&&(o=n)}}else"string"==typeof o&&""!==o?o=ue(o):"number"==typeof o||(o=void 0);if(this.attributes&&"string"==typeof s&&s.includes("array"))if(Array.isArray(o));else if("string"==typeof o&&o.trim().startsWith("[")){const[e,t,r]=K(()=>JSON.parse(o));e&&Array.isArray(r)&&(o=r)}else o=vh.toArray(o,{separator:this.options.arraySeparator});if(this.options.hooks&&this.options.hooks.afterUnmap&&this.options.hooks.afterUnmap[r])for(const e of this.options.hooks.afterUnmap[r])"function"==typeof vh[e]&&(o=await vh[e](o,{passphrase:this.passphrase,separator:this.options.arraySeparator}));i[r]=o}await this.applyHooksActions(i,"afterUnmap");const o=B(i);for(const[t,r]of Object.entries(e))t.startsWith("$")&&(o[t]=r);return o}getAttributeDefinition(e){const t=e.split(".");let r=this.attributes;for(const e of t){if(!r)return;r=r[e]}return r}preprocessAttributesForValidation(e){const t={};for(const[r,n]of Object.entries(e))if("object"!=typeof n||null===n||Array.isArray(n))t[r]=n;else{const e=n.$$type&&n.$$type.includes("required"),i=n.$$type&&n.$$type.includes("optional"),o={type:"object",properties:this.preprocessAttributesForValidation(n),strict:!1};e||(i||this.allNestedObjectsOptional)&&(o.optional=!0),t[r]=o}return t}}class Ih extends Qe{constructor({resource:e}){super(),this.resource=e,this.client=e.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(e){this.controller=e,this.continuationToken=null,this.closeNextIteration=!1}async _pull(e){if(this.closeNextIteration)return void e.close();const t=await this.client.listObjects({prefix:`resource=${this.resource.name}`,continuationToken:this.continuationToken}),r=t?.Contents.map(e=>e.Key).map(e=>e.replace(this.client.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e).map(e=>e.replace(`resource=${this.resource.name}/id=`,""));this.continuationToken=t.NextContinuationToken,this.enqueue(r),t.IsTruncated||(this.closeNextIteration=!0)}enqueue(e){e.forEach(e=>{this.controller.enqueue(e),this.emit("id",e)})}_cancel(e){}}class _h extends Ih{enqueue(e){this.controller.enqueue(e),this.emit("page",e)}}class Ah extends Qe{constructor({resource:e,batchSize:t=10,concurrency:r=5}){if(super(),!e)throw new Error("Resource is required for ResourceReader");this.resource=e,this.client=e.client,this.batchSize=t,this.concurrency=r,this.input=new _h({resource:this.resource}),this.transform=new ai({objectMode:!0,transform:this._transform.bind(this)}),this.input.on("data",e=>{this.transform.write(e)}),this.input.on("end",()=>{this.transform.end()}),this.input.on("error",e=>{this.emit("error",e)}),this.transform.on("data",e=>{this.emit("data",e)}),this.transform.on("end",()=>{this.emit("end")}),this.transform.on("error",e=>{this.emit("error",e)})}build(){return this}async _transform(e,t,r){const[n,i]=await G(async()=>{await m.for(e).withConcurrency(this.concurrency).handleError(async(e,t)=>{this.emit("error",e,t)}).process(async e=>{const t=await this.resource.get(e);return this.push(t),t})});r(i)}resume(){this.input.resume()}}class kh extends Qe{constructor({resource:e,batchSize:t=10,concurrency:r=5}){super(),this.resource=e,this.client=e.client,this.batchSize=t,this.concurrency=r,this.buffer=[],this.writing=!1,this.writable=new Vn({objectMode:!0,write:this._write.bind(this)}),this.writable.on("finish",()=>{this.emit("finish")}),this.writable.on("error",e=>{this.emit("error",e)})}build(){return this}write(e){return this.buffer.push(e),this._maybeWrite().catch(e=>{this.emit("error",e)}),!0}end(){this.ended=!0,this._maybeWrite().catch(e=>{this.emit("error",e)})}async _maybeWrite(){if(!this.writing&&(0!==this.buffer.length||this.ended)){for(this.writing=!0;this.buffer.length>0;){const e=this.buffer.splice(0,this.batchSize),[t,r]=await G(async()=>{await m.for(e).withConcurrency(this.concurrency).handleError(async(e,t)=>{this.emit("error",e,t)}).process(async e=>{const[t,r,n]=await G(async()=>await this.resource.insert(e));return t?n:(this.emit("error",r,e),null)})});t||this.emit("error",r)}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(e,t,r){r()}}function Bh(e){return new Promise((t,r)=>{if(!e)return r(new Error("streamToString: stream is undefined"));const n=[];e.on("data",e=>n.push(e)),e.on("error",r),e.on("end",()=>t(Buffer.concat(n).toString("utf-8")))})}class xh extends Qe{constructor(e={}){super(),this._instanceId=Math.random().toString(36).slice(2,8);const t=function(e){const t=[];e.name?"string"!=typeof e.name?t.push("Resource 'name' must be a string"):""===e.name.trim()&&t.push("Resource 'name' cannot be empty"):t.push("Resource 'name' is required");e.client||t.push("S3 'client' is required");e.attributes?"object"!=typeof e.attributes||Array.isArray(e.attributes)?t.push("Resource 'attributes' must be an object"):0===Object.keys(e.attributes).length&&t.push("Resource 'attributes' cannot be empty"):t.push("Resource 'attributes' are required");void 0!==e.version&&"string"!=typeof e.version&&t.push("Resource 'version' must be a string");void 0!==e.behavior&&"string"!=typeof e.behavior&&t.push("Resource 'behavior' must be a string");void 0!==e.passphrase&&"string"!=typeof e.passphrase&&t.push("Resource 'passphrase' must be a string");void 0!==e.parallelism&&("number"==typeof e.parallelism&&Number.isInteger(e.parallelism)?e.parallelism<1&&t.push("Resource 'parallelism' must be greater than 0"):t.push("Resource 'parallelism' must be an integer"));void 0===e.observers||Array.isArray(e.observers)||t.push("Resource 'observers' must be an array");const r=["cache","autoDecrypt","timestamps","paranoid","allNestedObjectsOptional"];for(const n of r)void 0!==e[n]&&"boolean"!=typeof e[n]&&t.push(`Resource '${n}' must be a boolean`);void 0!==e.idGenerator&&("function"!=typeof e.idGenerator&&"number"!=typeof e.idGenerator?t.push("Resource 'idGenerator' must be a function or a number (size)"):"number"==typeof e.idGenerator&&e.idGenerator<=0&&t.push("Resource 'idGenerator' size must be greater than 0"));void 0!==e.idSize&&("number"==typeof e.idSize&&Number.isInteger(e.idSize)?e.idSize<=0&&t.push("Resource 'idSize' must be greater than 0"):t.push("Resource 'idSize' must be an integer"));if(void 0!==e.partitions)if("object"!=typeof e.partitions||Array.isArray(e.partitions))t.push("Resource 'partitions' must be an object");else for(const[r,n]of Object.entries(e.partitions))if("object"!=typeof n||Array.isArray(n))t.push(`Partition '${r}' must be an object`);else if(n.fields)if("object"!=typeof n.fields||Array.isArray(n.fields))t.push(`Partition '${r}.fields' must be an object`);else for(const[e,i]of Object.entries(n.fields))"string"!=typeof i&&t.push(`Partition '${r}.fields.${e}' must be a string`);else t.push(`Partition '${r}' must have a 'fields' property`);if(void 0!==e.hooks)if("object"!=typeof e.hooks||Array.isArray(e.hooks))t.push("Resource 'hooks' must be an object");else{const r=["beforeInsert","afterInsert","beforeUpdate","afterUpdate","beforeDelete","afterDelete"];for(const[n,i]of Object.entries(e.hooks))if(r.includes(n))if(Array.isArray(i))for(let e=0;e<i.length;e++){const t=i[e];if("function"==typeof t);else if("string"==typeof t)continue}else t.push(`Resource 'hooks.${n}' must be an array`);else t.push(`Invalid hook event '${n}'. Valid events: ${r.join(", ")}`)}return{isValid:0===t.length,errors:t}}(e);if(!t.isValid)throw new Ce(`Invalid Resource ${e.name} configuration`,{resourceName:e.name,validation:t.errors,operation:"constructor",suggestion:"Check resource config and attributes."});const{name:r,client:n,version:i="1",attributes:o={},behavior:s=oe,passphrase:a="secret",parallelism:c=10,observers:u=[],cache:l=!1,autoDecrypt:h=!0,timestamps:f=!1,partitions:d={},paranoid:p=!0,allNestedObjectsOptional:g=!0,hooks:m={},idGenerator:y,idSize:w=22,versioningEnabled:b=!1}=e;if(this.name=r,this.client=n,this.version=i,this.behavior=s,this.observers=u,this.parallelism=c,this.passphrase=a??"secret",this.versioningEnabled=b,this.idGenerator=this.configureIdGenerator(y,w),this.config={cache:l,hooks:m,paranoid:p,timestamps:f,partitions:d,autoDecrypt:h,allNestedObjectsOptional:g},this.hooks={beforeInsert:[],afterInsert:[],beforeUpdate:[],afterUpdate:[],beforeDelete:[],afterDelete:[]},this.attributes=o||{},this.map=e.map,this.applyConfiguration({map:this.map}),m)for(const[e,t]of Object.entries(m))if(Array.isArray(t)&&this.hooks[e])for(const r of t)"function"==typeof r&&this.hooks[e].push(r.bind(this));this._initMiddleware()}configureIdGenerator(r,n){return"function"==typeof r?r:"number"==typeof r&&r>0?e(t,r):"number"==typeof n&&n>0&&22!==n?e(t,n):Me}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 e=this.schema.export();return e.behavior=this.behavior,e.timestamps=this.config.timestamps,e.partitions=this.config.partitions||{},e.paranoid=this.config.paranoid,e.allNestedObjectsOptional=this.config.allNestedObjectsOptional,e.autoDecrypt=this.config.autoDecrypt,e.cache=this.config.cache,e.hooks=this.hooks,e.map=this.map,e}applyConfiguration({map:e}={}){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 Eh({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:this.version,options:{autoDecrypt:this.config.autoDecrypt,allNestedObjectsOptional:this.config.allNestedObjectsOptional},map:e||this.map}),this.validatePartitions()}updateAttributes(e){const t=this.attributes;return this.attributes=e,this.applyConfiguration({map:this.schema?.map}),{oldAttributes:t,newAttributes:e}}addHook(e,t){this.hooks[e]&&this.hooks[e].push(t.bind(this))}async executeHooks(e,t){if(!this.hooks[e])return t;let r=t;for(const t of this.hooks[e])r=await t(r);return r}setupPartitionHooks(){if(!this.config.partitions)return;const e=this.config.partitions;0!==Object.keys(e).length&&(this.hooks.afterInsert||(this.hooks.afterInsert=[]),this.hooks.afterInsert.push(async e=>(await this.createPartitionReferences(e),e)),this.hooks.afterDelete||(this.hooks.afterDelete=[]),this.hooks.afterDelete.push(async e=>(await this.deletePartitionReferences(e),e)))}async validate(e){const t={original:u(e),isValid:!1,errors:[]},r=await this.schema.validate(e,{mutateOriginal:!1});return!0===r?t.isValid=!0:t.errors=r,t.data=e,t}validatePartitions(){if(!this.config.partitions)return;const e=this.config.partitions;if(0===Object.keys(e).length)return;const t=Object.keys(this.attributes||{});for(const[r,n]of Object.entries(e))if(n.fields)for(const e of Object.keys(n.fields))if(!this.fieldExistsInAttributes(e))throw new Ne(`Partition '${r}' uses field '${e}' which does not exist in resource attributes. Available fields: ${t.join(", ")}.`,{resourceName:this.name,partitionName:r,fieldName:e,availableFields:t,operation:"validatePartitions"})}fieldExistsInAttributes(e){if(e.startsWith("_"))return!0;if(!e.includes("."))return Object.keys(this.attributes||{}).includes(e);const t=e.split(".");let r=this.attributes||{};for(const e of t){if(!r||"object"!=typeof r||!(e in r))return!1;r=r[e]}return!0}applyPartitionRule(e,t){if(null==e)return e;let r=e;if("string"==typeof t&&t.includes("maxlength:")){const e=t.match(/maxlength:(\d+)/);if(e){const t=parseInt(e[1]);"string"==typeof r&&r.length>t&&(r=r.substring(0,t))}}if(t.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 e=new Date(r);isNaN(e.getTime())||(r=e.toISOString().split("T")[0])}return r}getResourceKey(e){return it("resource="+this.name,"data",`id=${e}`)}getPartitionKey({partitionName:e,id:t,data:r}){if(!this.config.partitions||!this.config.partitions[e])throw new Ne(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"getPartitionKey"});const n=this.config.partitions[e],i=[],o=Object.entries(n.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of o){const n=this.getNestedFieldValue(r,e),o=this.applyPartitionRule(n,t);if(null==o)return null;i.push(`${e}=${o}`)}if(0===i.length)return null;const s=t||r?.id;return s?it(`resource=${this.name}`,`partition=${e}`,...i,`id=${s}`):null}getNestedFieldValue(e,t){if(!t.includes("."))return e[t];const r=t.split(".");let n=e;for(const e of r){if(!n||"object"!=typeof n||!(e in n))return;n=n[e]}return n}calculateContentLength(e){return e?Buffer.isBuffer(e)?e.length:"string"==typeof e?Buffer.byteLength(e,"utf8"):"object"==typeof e?Buffer.byteLength(JSON.stringify(e),"utf8"):Buffer.byteLength(String(e),"utf8"):0}async insert({id:e,...t}){if(await this.exists(e))throw new Error(`Resource with id '${e}' already exists`);this.getResourceKey(e||"(auto)"),this.options.timestamps&&(t.createdAt=(new Date).toISOString(),t.updatedAt=(new Date).toISOString());const r={id:e,...this.applyDefaults(t)},n=await this.executeHooks("beforeInsert",r),i=Object.keys(n).filter(e=>!(e in r)||n[e]!==r[e]),o={};for(const e of i)o[e]=n[e];const{errors:s,isValid:a,data:c}=await this.validate(n);if(!a){const e=s&&s.length&&s[0].message?s[0].message:"Insert failed";throw new Ae({bucket:this.client.config.bucket,resourceName:this.name,attributes:n,validation:s,message:e})}const{id:u,...l}=c;Object.assign(l,o);const h=u||e||this.idGenerator(),f=await this.schema.mapper(l);f._v=String(this.version);const d=ne(this.behavior),{mappedData:p,body:g}=await d.handleInsert({resource:this,data:l,mappedData:f,originalData:r}),m=p,y=this.getResourceKey(h);let w;if(g&&""!==g){const[e,t]=await G(()=>Promise.resolve(JSON.parse(g)));e&&(w="application/json")}if("body-only"===this.behavior&&(!g||""===g))throw new Error(`[Resource.insert] Tentativa de gravar objeto sem body! Dados: id=${h}, resource=${this.name}`);const[b,v,E]=await G(()=>this.client.putObject({key:y,body:g,contentType:w,metadata:m}));if(!b){const e=v&&v.message?v.message:"";if(e.includes("metadata headers exceed")||e.includes("Insert failed")){const e=R(m),t=D({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:h}}),r=e-t;throw v.totalSize=e,v.limit=2047,v.effectiveLimit=t,v.excess=r,new Ce("metadata headers exceed",{resourceName:this.name,operation:"insert",id:h,totalSize:e,effectiveLimit:t,excess:r,suggestion:"Reduce metadata size or number of fields."})}throw xe(v,{bucket:this.client.config.bucket,key:y,resourceName:this.name,operation:"insert",id:h})}let I=await this.composeFullObjectFromWrite({id:h,metadata:m,body:g,behavior:this.behavior});const _=await this.executeHooks("afterInsert",I);return this.emit("insert",{...I,$before:{...r},$after:{..._}}),_}async get(e){if(f(e))throw new Error("id cannot be an object");if(s(e))throw new Error("id cannot be empty");const t=this.getResourceKey(e),[r,n,i]=await G(()=>this.client.getObject(t));if(!r)throw xe(n,{bucket:this.client.config.bucket,key:t,resourceName:this.name,operation:"get",id:e});if(0===i.ContentLength){const r=new Error(`No such key: ${t} [bucket:${this.client.config.bucket}]`);throw r.name="NoSuchKey",xe(r,{bucket:this.client.config.bucket,key:t,resourceName:this.name,operation:"get",id:e})}const o=i.Metadata?._v||this.version,a="string"==typeof o&&o.startsWith("v")?o.slice(1):o,c=await this.getSchemaForVersion(a);let u=await c.unmapper(i.Metadata);const l=ne(this.behavior);let h="";if(i.ContentLength>0){const[e,r,n]=await G(()=>this.client.getObject(t));h=e?await Bh(n.Body):""}const{metadata:d}=await l.handleGet({resource:this,metadata:u,body:h});let p=await this.composeFullObjectFromWrite({id:e,metadata:d,body:h,behavior:this.behavior});p._contentLength=i.ContentLength,p._lastModified=i.LastModified,p._hasContent=i.ContentLength>0,p._mimeType=i.ContentType||null,p._v=a,i.VersionId&&(p._versionId=i.VersionId),i.Expiration&&(p._expiresAt=i.Expiration),p._definitionHash=this.getDefinitionHash(),a!==this.version&&(p=await this.applyVersionMapping(p,a,this.version)),this.emit("get",p);return p}async exists(e){const t=this.getResourceKey(e),[r,n]=await G(()=>this.client.headObject(t));return r}async update(e,t){if(s(e))throw new Error("id cannot be empty");if(!await this.exists(e))throw new Error(`Resource with id '${e}' does not exist`);const r=await this.get(e),n=u(t);let o=u(r);for(const[e,t]of Object.entries(n))if(e.includes(".")){let r=o;const n=e.split(".");for(let e=0;e<n.length-1;e++)"object"==typeof r[n[e]]&&null!==r[n[e]]||(r[n[e]]={}),r=r[n[e]];r[n[n.length-1]]=u(t)}else"object"!=typeof t||null===t||Array.isArray(t)?o[e]=u(t):o[e]=i({},o[e],t);if(this.config.timestamps){const e=(new Date).toISOString();o.updatedAt=e,o.metadata||(o.metadata={}),o.metadata.updatedAt=e}const a=await this.executeHooks("beforeUpdate",u(o)),c={...r,...a,id:e},{isValid:l,errors:h,data:f}=await this.validate(u(c));if(!l)throw new Ae({bucket:this.client.config.bucket,resourceName:this.name,attributes:a,validation:h,message:"validation: "+(h&&h.length?JSON.stringify(h):"unknown")});await this.schema.mapper(f);const d=ne(this.behavior),p=await this.schema.mapper({...r,...a});p._v=String(this.version),await d.handleUpdate({resource:this,id:e,data:{...r,...a},mappedData:p,originalData:{...n,id:e}});const{id:g,...m}=f,y={...r,id:e},w={...m,id:e};await this.handlePartitionReferenceUpdates(y,w);const b=await this.schema.mapper(m);b._v=String(this.version);const v=ne(this.behavior),{mappedData:E,body:I}=await v.handleUpdate({resource:this,id:e,data:m,mappedData:b,originalData:{...n,id:e}}),_=E,A=this.getResourceKey(e);let k,B=I;if(""===I&&"body-overflow"!==this.behavior){const[e,t,r]=await G(()=>this.client.getObject(A));if(e&&r.ContentLength>0){const e=Buffer.from(await r.Body.transformToByteArray()),t=e.toString(),[n,i]=await G(()=>Promise.resolve(JSON.parse(t)));n||(B=e,k=r.ContentType)}}let x=k;if(B&&""!==B&&!x){const[e,t]=await G(()=>Promise.resolve(JSON.parse(B)));e&&(x="application/json")}this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(e,r);const[S,O]=await G(()=>this.client.putObject({key:A,body:B,contentType:x,metadata:_}));if(!S&&O&&O.message&&O.message.includes("metadata headers exceed")){const t=R(_),r=D({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:e}}),n=t-r;throw O.totalSize=t,O.limit=2047,O.effectiveLimit=r,O.excess=n,this.emit("exceedsLimit",{operation:"update",totalSize:t,limit:2047,effectiveLimit:r,excess:n,data:m}),new Ce("metadata headers exceed",{resourceName:this.name,operation:"update",id:e,totalSize:t,effectiveLimit:r,excess:n,suggestion:"Reduce metadata size or number of fields."})}if(!S)throw xe(O,{bucket:this.client.config.bucket,key:A,resourceName:this.name,operation:"update",id:e});const U=await this.composeFullObjectFromWrite({id:e,metadata:_,body:B,behavior:this.behavior}),C=await this.executeHooks("afterUpdate",U);return this.emit("update",{...U,$before:{...r},$after:{...C}}),C}async delete(e){if(s(e))throw new Error("id cannot be empty");let t,r=null;const[n,i,o]=await G(()=>this.get(e));n?t=o:(t={id:e},r=i),await this.executeHooks("beforeDelete",t);const a=this.getResourceKey(e),[c,u,l]=await G(()=>this.client.deleteObject(a));if(this.emit("delete",{...t,$before:{...t},$after:null}),r)throw xe(r,{bucket:this.client.config.bucket,key:a,resourceName:this.name,operation:"delete",id:e});if(!c)throw xe(u,{key:a,resourceName:this.name,operation:"delete",id:e});return await this.executeHooks("afterDelete",t),l}async upsert({id:e,...t}){return await this.exists(e)?this.update(e,t):this.insert({id:e,...t})}async count({partition:e=null,partitionValues:t={}}={}){let r;if(e&&Object.keys(t).length>0){const n=this.config.partitions[e];if(!n)throw new Ne(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"count"});const i=[],o=Object.entries(n.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,r]of o){const n=t[e];if(null!=n){const t=this.applyPartitionRule(n,r);i.push(`${e}=${t}`)}}r=i.length>0?`resource=${this.name}/partition=${e}/${i.join("/")}`:`resource=${this.name}/partition=${e}`}else r=`resource=${this.name}/data`;const n=await this.client.count({prefix:r});return this.emit("count",n),n}async insertMany(e){const{results:t}=await m.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,t),this.observers.map(r=>r.emit("error",this.name,e,t))}).process(async e=>await this.insert(e));return this.emit("insertMany",e.length),t}async deleteMany(e){const t=n(e.map(e=>this.getResourceKey(e)),1e3);e.map(e=>this.getResourceKey(e));const{results:r}=await m.for(t).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,t),this.observers.map(r=>r.emit("error",this.name,e,t))}).process(async e=>{const t=await this.client.deleteObjects(e);return e.forEach(e=>{const t=e.split("/").find(e=>e.startsWith("id=")),r=t?t.replace("id=",""):null;r&&(this.emit("deleted",r),this.observers.map(e=>e.emit("deleted",this.name,r)))}),t});return this.emit("deleteMany",e.length),r}async deleteAll(){if(!1!==this.config.paranoid)throw new Ce("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 e=`resource=${this.name}/data`,t=await this.client.deleteAll({prefix:e});return this.emit("deleteAll",{version:this.version,prefix:e,deletedCount:t}),{deletedCount:t,version:this.version}}async deleteAllData(){if(!1!==this.config.paranoid)throw new Ce("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 e=`resource=${this.name}`,t=await this.client.deleteAll({prefix:e});return this.emit("deleteAllData",{resource:this.name,prefix:e,deletedCount:t}),{deletedCount:t,resource:this.name}}async listIds({partition:e=null,partitionValues:t={},limit:r,offset:n=0}={}){let i;if(e&&Object.keys(t).length>0){if(!this.config.partitions||!this.config.partitions[e])throw new Ne(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"listIds"});const r=this.config.partitions[e],n=[],o=Object.entries(r.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,r]of o){const i=t[e];if(null!=i){const t=this.applyPartitionRule(i,r);n.push(`${e}=${t}`)}}i=n.length>0?`resource=${this.name}/partition=${e}/${n.join("/")}`:`resource=${this.name}/partition=${e}`}else i=`resource=${this.name}/data`;const o=(await this.client.getKeysPage({prefix:i,offset:n,amount:r||1e3})).map(e=>{const t=e.split("/").find(e=>e.startsWith("id="));return t?t.replace("id=",""):null}).filter(Boolean);return this.emit("listIds",o.length),o}async list({partition:e=null,partitionValues:t={},limit:r,offset:n=0}={}){const[i,o,s]=await G(async()=>e?await this.listPartition({partition:e,partitionValues:t,limit:r,offset:n}):await this.listMain({limit:r,offset:n}));return i?s:this.handleListError(o,{partition:e,partitionValues:t})}async listMain({limit:e,offset:t=0}){const[r,n,i]=await G(()=>this.listIds({limit:e,offset:t}));if(!r)throw n;const o=await this.processListResults(i,"main");return this.emit("list",{count:o.length,errors:0}),o}async listPartition({partition:e,partitionValues:t,limit:r,offset:n=0}){if(!this.config.partitions?.[e])return this.emit("list",{partition:e,partitionValues:t,count:0,errors:0}),[];const i=this.config.partitions[e],o=this.buildPartitionPrefix(e,i,t),[s,a,c]=await G(()=>this.client.getAllKeys({prefix:o}));if(!s)throw a;const u=this.extractIdsFromKeys(c).slice(n),l=r?u.slice(0,r):u,h=await this.processPartitionResults(l,e,i,c);return this.emit("list",{partition:e,partitionValues:t,count:h.length,errors:0}),h}buildPartitionPrefix(e,t,r){const n=[],i=Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of i){const i=r[e];if(null!=i){const r=this.applyPartitionRule(i,t);n.push(`${e}=${r}`)}}return n.length>0?`resource=${this.name}/partition=${e}/${n.join("/")}`:`resource=${this.name}/partition=${e}`}extractIdsFromKeys(e){return e.map(e=>{const t=e.split("/").find(e=>e.startsWith("id="));return t?t.replace("id=",""):null}).filter(Boolean)}async processListResults(e,t="main"){const{results:r,errors:n}=await m.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content))}).process(async e=>{const[r,n,i]=await G(()=>this.get(e));return r?i:this.handleResourceError(n,e,t)});return this.emit("list",{count:r.length,errors:0}),r}async processPartitionResults(e,t,r,n){const i=Object.entries(r.fields).sort(([e],[t])=>e.localeCompare(t)),{results:o,errors:s}=await m.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content))}).process(async e=>{const[r,o,s]=await G(async()=>{const r=this.extractPartitionValuesFromKey(e,n,i);return await this.getFromPartition({id:e,partitionName:t,partitionValues:r})});return r?s:this.handleResourceError(o,e,"partition")});return o.filter(e=>null!==e)}extractPartitionValuesFromKey(e,t,r){const n=t.find(t=>t.includes(`id=${e}`));if(!n)throw new Ne(`Partition key not found for ID ${e}`,{resourceName:this.name,id:e,operation:"extractPartitionValuesFromKey"});const i=n.split("/"),o={};for(const[e]of r){const t=i.find(t=>t.startsWith(`${e}=`));if(t){const r=t.replace(`${e}=`,"");o[e]=r}}return o}handleResourceError(e,t,r){if(e.message.includes("Cipher job failed")||e.message.includes("OperationError"))return{id:t,_decryptionFailed:!0,_error:e.message,..."partition"===r&&{_partition:r}};throw e}handleListError(e,{partition:t,partitionValues:r}){return e.message.includes("Partition '")&&e.message.includes("' not found"),this.emit("list",{partition:t,partitionValues:r,count:0,errors:1}),[]}async getMany(e){const{results:t,errors:r}=await m.for(e).withConcurrency(this.client.parallelism).handleError(async(e,t)=>(this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content)),{id:t,_error:e.message,_decryptionFailed:e.message.includes("Cipher job failed")||e.message.includes("OperationError")})).process(async e=>{const[t,r,n]=await G(()=>this.get(e));if(t)return n;if(r.message.includes("Cipher job failed")||r.message.includes("OperationError"))return{id:e,_decryptionFailed:!0,_error:r.message};throw r});return this.emit("getMany",e.length),t}async getAll(){const[e,t,r]=await G(()=>this.listIds());if(!e)throw t;const n=[];for(const e of r){const[t,r,i]=await G(()=>this.get(e));t&&n.push(i)}return n}async page({offset:e=0,size:t=100,partition:r=null,partitionValues:n={},skipCount:i=!1}={}){const[o,s,a]=await G(async()=>{let o=null,s=null;if(!i){const[e,i,a]=await G(()=>this.count({partition:r,partitionValues:n}));e?(o=a,s=Math.ceil(o/t)):(o=null,s=null)}const a=Math.floor(e/t);let c=[];if(t<=0)c=[];else{const[i,o,s]=await G(()=>this.list({partition:r,partitionValues:n,limit:t,offset:e}));c=i?s:[]}const u={items:c,totalItems:o,page:a,pageSize:t,totalPages:s,hasMore:c.length===t&&e+t<(o||1/0),_debug:{requestedSize:t,requestedOffset:e,actualItemsReturned:c.length,skipCount:i,hasTotalItems:null!==o}};return this.emit("page",u),u});return o?a:{items:[],totalItems:null,page:Math.floor(e/t),pageSize:t,totalPages:null,_debug:{requestedSize:t,requestedOffset:e,actualItemsReturned:0,skipCount:i,hasTotalItems:!1,error:s.message}}}readable(){return new Ah({resource:this}).build()}writable(){return new kh({resource:this}).build()}async setContent({id:e,buffer:t,contentType:r="application/octet-stream"}){const[n,i,o]=await G(()=>this.get(e));if(!n||!o)throw new Ce(`Resource with id '${e}' not found`,{resourceName:this.name,id:e,operation:"setContent"});const s={...o,_hasContent:!0,_contentLength:t.length,_mimeType:r},a=await this.schema.mapper(s),[c,u]=await G(()=>this.client.putObject({key:this.getResourceKey(e),metadata:a,body:t,contentType:r}));if(!c)throw u;return this.emit("setContent",{id:e,contentType:r,contentLength:t.length}),s}async content(e){const t=this.getResourceKey(e),[r,n,i]=await G(()=>this.client.getObject(t));if(!r){if("NoSuchKey"===n.name)return{buffer:null,contentType:null};throw n}const o=Buffer.from(await i.Body.transformToByteArray()),s=i.ContentType||null;return this.emit("content",e,o.length,s),{buffer:o,contentType:s}}async hasContent(e){const t=this.getResourceKey(e),[r,n,i]=await G(()=>this.client.headObject(t));return!!r&&i.ContentLength>0}async deleteContent(e){const t=this.getResourceKey(e),[r,n,i]=await G(()=>this.client.headObject(t));if(!r)throw n;const o=i.Metadata||{},[s,a,c]=await G(()=>this.client.putObject({key:t,body:"",metadata:o}));if(!s)throw a;return this.emit("deleteContent",e),c}getDefinitionHash(){const e={attributes:this.attributes,behavior:this.behavior},t=$l(e);return`sha256:${g("sha256").update(t).digest("hex")}`}extractVersionFromKey(e){const t=e.split("/").find(e=>e.startsWith("v="));return t?t.replace("v=",""):null}async getSchemaForVersion(e){if(e===this.version)return this.schema;const[t,r,n]=await G(()=>Promise.resolve(new Eh({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:e,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})));return t?n:this.schema}async createPartitionReferences(e){const t=this.config.partitions;if(t&&0!==Object.keys(t).length)for(const[r,n]of Object.entries(t)){const t=this.getPartitionKey({partitionName:r,id:e.id,data:e});if(t){const e={_v:String(this.version)};await this.client.putObject({key:t,metadata:e,body:"",contentType:void 0})}}}async deletePartitionReferences(e){const t=this.config.partitions;if(!t||0===Object.keys(t).length)return;const r=[];for(const[n,i]of Object.entries(t)){const t=this.getPartitionKey({partitionName:n,id:e.id,data:e});t&&r.push(t)}if(r.length>0){const[e,t]=await G(()=>this.client.deleteObjects(r))}}async query(e={},{limit:t=100,offset:r=0,partition:n=null,partitionValues:i={}}={}){if(0===Object.keys(e).length)return await this.list({partition:n,partitionValues:i,limit:t,offset:r});const o=[];let s=r;const a=Math.min(t,50);for(;o.length<t;){const t=await this.list({partition:n,partitionValues:i,limit:a,offset:s});if(0===t.length)break;const r=t.filter(t=>Object.entries(e).every(([e,r])=>t[e]===r));if(o.push(...r),s+=a,t.length<a)break}return o.slice(0,t)}async handlePartitionReferenceUpdates(e,t){const r=this.config.partitions;if(!r||0===Object.keys(r).length)return;for(const[n,i]of Object.entries(r)){const[r,o]=await G(()=>this.handlePartitionReferenceUpdate(n,i,e,t))}const n=t.id||e.id;for(const[e,i]of Object.entries(r)){const r=`resource=${this.name}/partition=${e}`;let i=[];const[o,s,a]=await G(()=>this.client.getAllKeys({prefix:r}));if(!o)continue;i=a;const c=this.getPartitionKey({partitionName:e,id:n,data:t});for(const e of i)if(e.endsWith(`/id=${n}`)&&e!==c){const[t,r]=await G(()=>this.client.deleteObject(e))}}}async handlePartitionReferenceUpdate(e,t,r,n){const i=n.id||r.id,o=this.getPartitionKey({partitionName:e,id:i,data:r}),s=this.getPartitionKey({partitionName:e,id:i,data:n});if(o!==s){if(o){const[e,t]=await G(async()=>{await this.client.deleteObject(o)})}if(s){const[e,t]=await G(async()=>{const e={_v:String(this.version)};await this.client.putObject({key:s,metadata:e,body:"",contentType:void 0})})}}else if(s){const[e,t]=await G(async()=>{const e={_v:String(this.version)};await this.client.putObject({key:s,metadata:e,body:"",contentType:void 0})})}}async updatePartitionReferences(e){const t=this.config.partitions;if(t&&0!==Object.keys(t).length)for(const[r,n]of Object.entries(t)){if(!n||!n.fields||"object"!=typeof n.fields)continue;const t=this.getPartitionKey({partitionName:r,id:e.id,data:e});if(t){const e={_v:String(this.version)},[r,n]=await G(async()=>{await this.client.putObject({key:t,metadata:e,body:"",contentType:void 0})})}}}async getFromPartition({id:e,partitionName:t,partitionValues:r={}}){if(!this.config.partitions||!this.config.partitions[t])throw new Ne(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"getFromPartition"});const n=this.config.partitions[t],i=[],o=Object.entries(n.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of o){const n=r[e];if(null!=n){const r=this.applyPartitionRule(n,t);i.push(`${e}=${r}`)}}if(0===i.length)throw new Ne(`No partition values provided for partition '${t}'`,{resourceName:this.name,partitionName:t,operation:"getFromPartition"});const s=it(`resource=${this.name}`,`partition=${t}`,...i,`id=${e}`),[a,c]=await G(async()=>{await this.client.headObject(s)});if(!a)throw new Ce(`Resource with id '${e}' not found in partition '${t}'`,{resourceName:this.name,id:e,partitionName:t,operation:"getFromPartition"});const u=await this.get(e);return u._partition=t,u._partitionValues=r,this.emit("getFromPartition",u),u}async createHistoricalVersion(e,t){const r=it(`resource=${this.name}`,"historical",`id=${e}`),n={...t,_v:t._v||this.version,_historicalTimestamp:(new Date).toISOString()},i=await this.schema.mapper(n),o=ne(this.behavior),{mappedData:s,body:a}=await o.handleInsert({resource:this,data:n,mappedData:i}),c={...s,_v:t._v||this.version,_historicalTimestamp:n._historicalTimestamp};let u;if(a&&""!==a){const[e,t]=await G(()=>Promise.resolve(JSON.parse(a)));e&&(u="application/json")}await this.client.putObject({key:r,metadata:c,body:a,contentType:u})}async applyVersionMapping(e,t,r){if(t===r)return e;return{...e,_v:r,_originalVersion:t,_versionMapped:!0}}async composeFullObjectFromWrite({id:e,metadata:t,body:r,behavior:n}){const i={};t&&"true"===t.$truncated&&(i.$truncated="true"),t&&"true"===t.$overflow&&(i.$overflow="true");let o={};const[s,a,c]=await G(()=>this.schema.unmapper(t));o=s?c:t;const u=e=>{if(!e||"object"!=typeof e)return e;const t={};for(const[r,n]of Object.entries(e))r.startsWith("_")||(t[r]=n);return t},l=e=>{if("object"==typeof e&&null!==e)return e;if("string"==typeof e){if("[object Object]"===e)return{};if(e.startsWith("{")||e.startsWith("[")){const[t,r,n]=K(()=>JSON.parse(e));return t?n:e}return e}return e};if("body-overflow"===n){const n=t&&"true"===t.$overflow;let i={};if(n&&r){const[e,t,n]=await G(()=>Promise.resolve(JSON.parse(r)));if(e){const[e,t,r]=await G(()=>this.schema.unmapper(n));i=e?r:{}}}const s={...o,...i,id:e};Object.keys(s).forEach(e=>{s[e]=l(s[e])});const a=u(s);return n&&(a.$overflow="true"),a}if("body-only"===n){const[n,i,o]=await G(()=>Promise.resolve(r?JSON.parse(r):{}));let s=this.schema.map;if(t&&t._map){const[e,r,n]=await G(()=>Promise.resolve("string"==typeof t._map?JSON.parse(t._map):t._map));s=e?n:this.schema.map}const[a,c,u]=await G(()=>this.schema.unmapper(o,s)),h=a?{...u,id:e}:{id:e};return Object.keys(h).forEach(e=>{h[e]=l(h[e])}),h}const h={...o,id:e};Object.keys(h).forEach(e=>{h[e]=l(h[e])});const f=u(h);return i.$truncated&&(f.$truncated=i.$truncated),i.$overflow&&(f.$overflow=i.$overflow),f}emit(e,...t){return super.emit(e,...t)}async replace(e,t){await this.delete(e),await new Promise(e=>setTimeout(e,100));const r=Date.now();for(;Date.now()-r<5e3;){if(!await this.exists(e))break;await new Promise(e=>setTimeout(e,50))}try{return await this.insert({...t,id:e})}catch(r){if(r&&r.message&&r.message.includes("already exists")){return await this.update(e,t)}throw r}}_initMiddleware(){this._middlewares=new Map,this._middlewareMethods=["get","list","listIds","getAll","count","page","insert","update","delete","deleteMany","exists","getMany"];for(const e of this._middlewareMethods)this._middlewares.set(e,[]),this[`_original_${e}`]||(this[`_original_${e}`]=this[e].bind(this),this[e]=async(...t)=>{const r={resource:this,args:t,method:e};let n=-1;const i=this._middlewares.get(e),o=async t=>{if(t<=n)throw new Error("next() called multiple times");return n=t,t<i.length?await i[t](r,()=>o(t+1)):await this[`_original_${e}`](...r.args)};return await o(0)})}useMiddleware(e,t){if(this._middlewares||this._initMiddleware(),!this._middlewares.has(e))throw new Ce(`No such method for middleware: ${e}`,{operation:"useMiddleware",method:e});this._middlewares.get(e).push(t)}applyDefaults(e){const t={...e};for(const[e,r]of Object.entries(this.attributes))if(void 0===t[e]&&"string"==typeof r&&r.includes("default:")){const n=r.match(/default:([^|]+)/);if(n){let i=n[1];r.includes("boolean")?i="true"===i:r.includes("number")&&(i=Number(i)),t[e]=i}}return t}}class Sh extends Qe{constructor(e){super(),this.version="1",this.s3dbVersion=(()=>{const[e,t,r]=G(()=>"7.0.0");return e?r:"latest"})(),this.resources={},this.savedMetadata=null,this.options=e,this.verbose=e.verbose||!1,this.parallelism=parseInt(e.parallelism+"")||10,this.plugins=e.plugins||[],this.pluginList=e.plugins||[],this.cache=e.cache,this.passphrase=e.passphrase||"secret",this.versioningEnabled=e.versioningEnabled||!1;let t=e.connectionString;if(!t&&(e.bucket||e.accessKeyId||e.secretAccessKey)){const{bucket:r,region:n,accessKeyId:i,secretAccessKey:o,endpoint:s,forcePathStyle:a}=e;if(s){const e=new URL(s);i&&(e.username=encodeURIComponent(i)),o&&(e.password=encodeURIComponent(o)),e.pathname=`/${r||"s3db"}`,a&&e.searchParams.set("forcePathStyle","true"),t=e.toString()}else if(i&&o){const e=new URLSearchParams;e.set("region",n||"us-east-1"),a&&e.set("forcePathStyle","true"),t=`s3://${encodeURIComponent(i)}:${encodeURIComponent(o)}@${r||"s3db"}?${e.toString()}`}}this.client=e.client||new gh({verbose:this.verbose,parallelism:this.parallelism,connectionString:t}),this.bucket=this.client.bucket,this.keyPrefix=this.client.keyPrefix,this._exitListenerRegistered||(this._exitListenerRegistered=!0,process.on("exit",async()=>{if(this.isConnected())try{await this.disconnect()}catch(e){}}))}async connect(){await this.startPlugins();let e=null;if(await this.client.exists("s3db.json")){const t=await this.client.getObject("s3db.json");e=JSON.parse(await Bh(t?.Body))}else e=this.blankMetadataStructure(),await this.uploadMetadataFile();this.savedMetadata=e;const t=this.detectDefinitionChanges(e);for(const[t,r]of Object.entries(e.resources||{})){const e=r.currentVersion||"v0",n=r.versions?.[e];n&&(this.resources[t]=new xh({name:t,client:this.client,database:this,version:e,attributes:n.attributes,behavior:n.behavior||"user-managed",parallelism:this.parallelism,passphrase:this.passphrase,observers:[this],cache:this.cache,timestamps:void 0!==n.timestamps&&n.timestamps,partitions:r.partitions||n.partitions||{},paranoid:void 0===n.paranoid||n.paranoid,allNestedObjectsOptional:void 0===n.allNestedObjectsOptional||n.allNestedObjectsOptional,autoDecrypt:void 0===n.autoDecrypt||n.autoDecrypt,hooks:n.hooks||{},versioningEnabled:this.versioningEnabled,map:n.map}))}t.length>0&&this.emit("resourceDefinitionsChanged",{changes:t,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(e){const t=[];for(const[r,n]of Object.entries(this.resources)){const i=this.generateDefinitionHash(n.export()),o=e.resources?.[r];if(o){const e=o.currentVersion||"v0",n=o.versions?.[e],s=n?.hash;s!==i&&t.push({type:"changed",resourceName:r,currentHash:i,savedHash:s,fromVersion:e,toVersion:this.getNextVersion(o.versions)})}else t.push({type:"new",resourceName:r,currentHash:i,savedHash:null})}for(const[r,n]of Object.entries(e.resources||{}))if(!this.resources[r]){const e=n.currentVersion||"v0",i=n.versions?.[e];t.push({type:"deleted",resourceName:r,currentHash:null,savedHash:i?.hash,deletedVersion:e})}return t}generateDefinitionHash(e,t=void 0){const r={...e.attributes};e.timestamps&&(delete r.createdAt,delete r.updatedAt);const n={attributes:r,behavior:t||e.behavior||"user-managed",partitions:e.partitions||{}},i=$l(n);return`sha256:${g("sha256").update(i).digest("hex")}`}getNextVersion(e={}){const t=Object.keys(e).filter(e=>e.startsWith("v")).map(e=>parseInt(e.substring(1))).filter(e=>!isNaN(e));return`v${(t.length>0?Math.max(...t):-1)+1}`}async startPlugins(){const e=this;if(!s(this.pluginList)){const t=this.pluginList.map(e=>d(e)?new e(this):e),r=t.map(async t=>{t.beforeSetup&&await t.beforeSetup(),await t.setup(e),t.afterSetup&&await t.afterSetup()});await Promise.all(r);const n=t.map(async e=>{e.beforeStart&&await e.beforeStart(),await e.start(),e.afterStart&&await e.afterStart()});await Promise.all(n)}}async usePlugin(e,t=null){const r=t||e.constructor.name.replace("Plugin","").toLowerCase();return this.plugins[r]=e,this.isConnected()&&(await e.setup(this),await e.start()),e}async uploadMetadataFile(){const e={version:this.version,s3dbVersion:this.s3dbVersion,lastUpdated:(new Date).toISOString(),resources:{}};Object.entries(this.resources).forEach(([t,r])=>{const n=r.export(),i=this.generateDefinitionHash(n),o=this.savedMetadata?.resources?.[t],s=o?.currentVersion||"v0",a=o?.versions?.[s];let c,u;a&&a.hash===i?(c=s,u=!1):(c=this.getNextVersion(o?.versions),u=!0),e.resources[t]={currentVersion:c,partitions:r.config.partitions||{},versions:{...o?.versions,[c]:{hash:i,attributes:n.attributes,behavior:n.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:u?(new Date).toISOString():a?.createdAt}}},r.version!==c&&(r.version=c,r.emit("versionUpdated",{oldVersion:s,newVersion:c}))}),await this.client.putObject({key:"s3db.json",body:JSON.stringify(e,null,2),contentType:"application/json"}),this.savedMetadata=e,this.emit("metadataUploaded",e)}blankMetadataStructure(){return{version:"1",s3dbVersion:this.s3dbVersion,resources:{}}}resourceExists(e){return!!this.resources[e]}resourceExistsWithSameHash({name:e,attributes:t,behavior:r="user-managed",partitions:n={},options:i={}}){if(!this.resources[e])return{exists:!1,sameHash:!1,hash:null};const o=this.resources[e],s=this.generateDefinitionHash(o.export()),a=new xh({name:e,attributes:t,behavior:r,partitions:n,client:this.client,version:o.version,passphrase:this.passphrase,versioningEnabled:this.versioningEnabled,...i}),c=this.generateDefinitionHash(a.export());return{exists:!0,sameHash:s===c,hash:c,existingHash:s}}async createResource({name:e,attributes:t,behavior:r="user-managed",hooks:n,...i}){if(this.resources[e]){const o=this.resources[e];if(Object.assign(o.config,{cache:this.cache,...i}),r&&(o.behavior=r),o.versioningEnabled=this.versioningEnabled,o.updateAttributes(t),n)for(const[e,t]of Object.entries(n))if(Array.isArray(t)&&o.hooks[e])for(const r of t)"function"==typeof r&&o.hooks[e].push(r.bind(o));const s=this.generateDefinitionHash(o.export(),o.behavior),a=this.savedMetadata?.resources?.[e],c=a?.currentVersion||"v0",u=a?.versions?.[c];return u&&u.hash===s||await this.uploadMetadataFile(),this.emit("s3db.resourceUpdated",e),o}const o=this.savedMetadata?.resources?.[e],s=o?.currentVersion||"v0",a=new xh({name:e,client:this.client,version:void 0!==i.version?i.version:s,attributes:t,behavior:r,parallelism:this.parallelism,passphrase:void 0!==i.passphrase?i.passphrase:this.passphrase,observers:[this],cache:void 0!==i.cache?i.cache:this.cache,timestamps:void 0!==i.timestamps&&i.timestamps,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:n||{},versioningEnabled:this.versioningEnabled,map:i.map,idGenerator:i.idGenerator,idSize:i.idSize});return a.database=this,this.resources[e]=a,await this.uploadMetadataFile(),this.emit("s3db.resourceCreated",e),a}resource(e){return this.resources[e]?this.resources[e]:Promise.reject(`resource ${e} does not exist`)}async listResources(){return Object.keys(this.resources).map(e=>({name:e}))}async getResource(e){if(!this.resources[e])throw new be({bucket:this.client.config.bucket,resourceName:e,id:e});return this.resources[e]}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 e of this.pluginList)e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners();const e=this.pluginList.map(async e=>{try{e&&"function"==typeof e.stop&&await e.stop()}catch(e){}});await Promise.all(e)}if(this.resources&&Object.keys(this.resources).length>0){for(const[e,t]of Object.entries(this.resources))try{t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners(),t._pluginWrappers&&t._pluginWrappers.clear(),t._pluginMiddlewares&&(t._pluginMiddlewares={}),t.observers&&Array.isArray(t.observers)&&(t.observers=[])}catch(e){}Object.keys(this.resources).forEach(e=>delete this.resources[e])}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(e){}}}class Oh extends Sh{}function Uh(e){return"string"==typeof e?e.trim().toLowerCase():e}const Ch={s3db:class extends fc{constructor(e={},t=[],r=null){super(e),this.instanceId=Math.random().toString(36).slice(2,10),this.client=r,this.connectionString=e.connectionString;let n=t;if(t)if(Array.isArray(t)){n={};for(const e of t)"string"==typeof e&&(n[Uh(e)]=e)}else"string"==typeof t&&(n[Uh(t)]=t);else n={};this.resourcesMap=this._normalizeResources(n)}_normalizeResources(e){if(!e)return{};if(Array.isArray(e)){const t={};for(const r of e)"string"==typeof r?t[Uh(r)]=r:Array.isArray(r)&&"string"==typeof r[0]?t[Uh(r[0])]=r:"object"==typeof r&&r.resource&&(t[Uh(r.resource)]={...r});return t}if("object"==typeof e){const t={};for(const[r,n]of Object.entries(e)){const e=Uh(r);"string"==typeof n?t[e]=n:Array.isArray(n)?t[e]=n.map(e=>"string"==typeof e||"function"==typeof e?e:"object"==typeof e&&e.resource?{...e}:e):"function"==typeof n?t[e]=n:"object"==typeof n&&n.resource&&(t[e]={...n})}return t}if("function"==typeof e)return e;if("string"==typeof e){return{[Uh(e)]:e}}return{}}validateConfig(){const e=[];return this.client||this.connectionString||e.push("You must provide a client or a connectionString"),(!this.resourcesMap||"object"==typeof this.resourcesMap&&0===Object.keys(this.resourcesMap).length)&&e.push("You must provide a resources map or array"),{isValid:0===e.length,errors:e}}async initialize(e){try{if(await super.initialize(e),this.client)this.targetDatabase=this.client;else{if(!this.connectionString)throw new Error("S3dbReplicator: No client or connectionString provided");{const e={connectionString:this.connectionString,region:this.region,keyPrefix:this.keyPrefix,verbose:this.config.verbose||!1};this.targetDatabase=new Oh(e),await this.targetDatabase.connect()}}this.emit("connected",{replicator:this.name,target:this.connectionString||"client-provided"})}catch(e){throw e}}async replicate({resource:e,operation:t,data:r,id:n}){const i=Uh(e),o=this._resolveDestResource(i,r),s=this._getDestResourceObj(o),a=this._applyTransformer(i,r);let c;if("insert"===t)c=await s.insert(a);else if("update"===t)c=await s.update(n,a);else{if("delete"!==t)throw new Error(`Invalid operation: ${t}. Supported operations are: insert, update, delete`);c=await s.delete(n)}return c}_applyTransformer(e,t){const r=Uh(e),n=this.resourcesMap[r];let i;return n?(Array.isArray(n)&&"function"==typeof n[1]?i=n[1](t):"function"==typeof n?i=n(t):"object"==typeof n?"function"==typeof n.transform?i=n.transform(t):"function"==typeof n.transformer&&(i=n.transformer(t)):i=t,i&&t&&t.id&&!i.id&&(i.id=t.id),!i&&t&&(i=t),i):t}_resolveDestResource(e,t){const r=Uh(e),n=this.resourcesMap[r];if(!n)return e;if(Array.isArray(n)){if("string"==typeof n[0])return n[0];if("object"==typeof n[0]&&n[0].resource)return n[0].resource;if("function"==typeof n[0])return e}return"string"==typeof n?n:"function"==typeof n?e:"object"==typeof n&&n.resource?n.resource:e}_getDestResourceObj(e){if(!this.client||!this.client.resources)return null;const t=Object.keys(this.client.resources),r=Uh(e),n=t.find(e=>Uh(e)===r);if(!n)throw new Error(`[S3dbReplicator] Destination resource not found: ${e}. Available: ${t.join(", ")}`);return this.client.resources[n]}async replicateBatch(e,t){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const r=[],n=[];for(const i of t){const[t,o,s]=await G(()=>this.replicate({resource:e,operation:i.operation,id:i.id,data:i.data,beforeData:i.beforeData}));t?r.push(s):n.push({id:i.id,error:o.message})}return this.emit("batch_replicated",{replicator:this.name,resourceName:e,total:t.length,successful:r.length,errors:n.length}),{success:0===n.length,results:r,errors:n,total:t.length}}async testConnection(){const[e,t]=await G(async()=>(this.targetDatabase||await this.initialize(this.database),await this.targetDatabase.listResources(),!0));return!!e||(this.emit("connection_error",{replicator:this.name,error:t.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(e,t){const r=Uh(e),n=this.resourcesMap[r];if(!n)return!1;if(!t)return!0;if(Array.isArray(n)){for(const e of n)if("object"==typeof e&&e.resource){if(!e.actions||!Array.isArray(e.actions))return!0;if(e.actions.includes(t))return!0}else if("string"==typeof e||"function"==typeof e)return!0;return!1}return"object"==typeof n&&n.resource?!n.actions||!Array.isArray(n.actions)||n.actions.includes(t):"string"==typeof n||"function"==typeof n}},sqs:class extends fc{constructor(e={},t=[],r=null){if(super(e),this.resources=t,this.client=r,this.queueUrl=e.queueUrl,this.queues=e.queues||{},this.defaultQueue=e.defaultQueue||e.defaultQueueUrl||e.queueUrlDefault,this.region=e.region||"us-east-1",this.sqsClient=r||null,this.messageGroupId=e.messageGroupId,this.deduplicationId=e.deduplicationId,t&&"object"==typeof t)for(const[e,r]of Object.entries(t))r.queueUrl&&(this.queues[e]=r.queueUrl)}validateConfig(){const e=[];return this.queueUrl||0!==Object.keys(this.queues).length||this.defaultQueue||this.resourceQueueMap||e.push("Either queueUrl, queues object, defaultQueue, or resourceQueueMap must be provided"),{isValid:0===e.length,errors:e}}getQueueUrlsForResource(e){if(this.resourceQueueMap&&this.resourceQueueMap[e])return this.resourceQueueMap[e];if(this.queues[e])return[this.queues[e]];if(this.queueUrl)return[this.queueUrl];if(this.defaultQueue)return[this.defaultQueue];throw new Error(`No queue URL found for resource '${e}'`)}_applyTransformer(e,t){const r=this.resources[e];let n=t;return r?("function"==typeof r.transform?n=r.transform(t):"function"==typeof r.transformer&&(n=r.transformer(t)),n||t):t}createMessage(e,t,r,n,i=null){const o={resource:e,action:t,timestamp:(new Date).toISOString(),source:"s3db-replicator"};switch(t){case"insert":case"delete":default:return{...o,data:r};case"update":return{...o,before:i,data:r}}}async initialize(e,t){if(await super.initialize(e),!this.sqsClient){const[e,r,n]=await G(()=>import("@aws-sdk/client-sqs"));if(!e)throw this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{SQSClient:i}=n;this.sqsClient=t||new i({region:this.region,credentials:this.config.credentials}),this.emit("initialized",{replicator:this.name,queueUrl:this.queueUrl,queues:this.queues,defaultQueue:this.defaultQueue})}}async replicate(e,t,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const[o,s,a]=await G(async()=>{const{SendMessageCommand:o}=await import("@aws-sdk/client-sqs"),s=this.getQueueUrlsForResource(e),a=this._applyTransformer(e,r),c=this.createMessage(e,t,a,n,i),u=[];for(const r of s){const i=new o({QueueUrl:r,MessageBody:JSON.stringify(c),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${e}:${t}:${n}`:void 0}),s=await this.sqsClient.send(i);u.push({queueUrl:r,messageId:s.MessageId}),this.emit("replicated",{replicator:this.name,resource:e,operation:t,id:n,queueUrl:r,messageId:s.MessageId,success:!0})}return{success:!0,results:u}});return o?a:(this.emit("replicator_error",{replicator:this.name,resource:e,operation:t,id:n,error:s.message}),{success:!1,error:s.message})}async replicateBatch(e,t){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const[r,n,i]=await G(async()=>{const{SendMessageBatchCommand:r}=await import("@aws-sdk/client-sqs"),n=this.getQueueUrlsForResource(e),i=[];for(let e=0;e<t.length;e+=10)i.push(t.slice(e,e+10));const o=[],s=[];for(const t of i){const[i,a]=await G(async()=>{const i=t.map((t,r)=>({Id:`${t.id}-${r}`,MessageBody:JSON.stringify(this.createMessage(e,t.operation,t.data,t.id,t.beforeData)),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${e}:${t.operation}:${t.id}`:void 0})),s=new r({QueueUrl:n[0],Entries:i}),a=await this.sqsClient.send(s);o.push(a)});if(!i&&(s.push({batch:t.length,error:a.message}),a.message&&(a.message.includes("Batch error")||a.message.includes("Connection")||a.message.includes("Network"))))throw a}return this.emit("batch_replicated",{replicator:this.name,resource:e,queueUrl:n[0],total:t.length,successful:o.length,errors:s.length}),{success:0===s.length,results:o,errors:s,total:t.length,queueUrl:n[0]}});if(r)return i;const o=n?.message||n||"Unknown error";return this.emit("batch_replicator_error",{replicator:this.name,resource:e,error:o}),{success:!1,error:o}}async testConnection(){const[e,t]=await G(async()=>{this.sqsClient||await this.initialize(this.database);const{GetQueueAttributesCommand:e}=await import("@aws-sdk/client-sqs"),t=new e({QueueUrl:this.queueUrl,AttributeNames:["QueueArn"]});return await this.sqsClient.send(t),!0});return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.sqsClient,queueUrl:this.queueUrl,region:this.region,resources:this.resources,totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.sqsClient&&this.sqsClient.destroy(),await super.cleanup()}shouldReplicateResource(e){return this.resourceQueueMap&&Object.keys(this.resourceQueueMap).includes(e)||this.queues&&Object.keys(this.queues).includes(e)||!(!this.defaultQueue&&!this.queueUrl)||this.resources&&Object.keys(this.resources).includes(e)||!1}},bigquery:class extends fc{constructor(e={},t={}){super(e),this.projectId=e.projectId,this.datasetId=e.datasetId,this.bigqueryClient=null,this.credentials=e.credentials,this.location=e.location||"US",this.logTable=e.logTable,this.resources=this.parseResourcesConfig(t)}parseResourcesConfig(e){const t={};for(const[r,n]of Object.entries(e))"string"==typeof n?t[r]=[{table:n,actions:["insert"]}]:Array.isArray(n)?t[r]=n.map(e=>"string"==typeof e?{table:e,actions:["insert"]}:{table:e.table,actions:e.actions||["insert"]}):"object"==typeof n&&(t[r]=[{table:n.table,actions:n.actions||["insert"]}]);return t}validateConfig(){const e=[];this.projectId||e.push("projectId is required"),this.datasetId||e.push("datasetId is required"),0===Object.keys(this.resources).length&&e.push("At least one resource must be configured");for(const[t,r]of Object.entries(this.resources))for(const n of r){n.table||e.push(`Table name is required for resource '${t}'`),Array.isArray(n.actions)&&0!==n.actions.length||e.push(`Actions array is required for resource '${t}'`);const r=["insert","update","delete"],i=n.actions.filter(e=>!r.includes(e));i.length>0&&e.push(`Invalid actions for resource '${t}': ${i.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}async initialize(e){await super.initialize(e);const[t,r,n]=await G(()=>import("@google-cloud/bigquery"));if(!t)throw this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{BigQuery:i}=n;this.bigqueryClient=new i({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(e){return this.resources.hasOwnProperty(e)}shouldReplicateAction(e,t){return!!this.resources[e]&&this.resources[e].some(e=>e.actions.includes(t))}getTablesForResource(e,t){return this.resources[e]?this.resources[e].filter(e=>e.actions.includes(t)).map(e=>e.table):[]}async replicate(e,t,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(e,t))return{skipped:!0,reason:"action_not_included"};const o=this.getTablesForResource(e,t);if(0===o.length)return{skipped:!0,reason:"no_tables_for_action"};const s=[],a=[],[c,u,l]=await G(async()=>{const i=this.bigqueryClient.dataset(this.datasetId);for(const e of o){const[o,c]=await G(async()=>{const o=i.table(e);let a;if("insert"===t){const e={...r};a=await o.insert([e])}else if("update"===t){const t=Object.keys(r).filter(e=>"id"!==e),i=t.map(e=>`${e}=@${e}`).join(", "),o={id:n};t.forEach(e=>{o[e]=r[e]});const s=`UPDATE \`${this.projectId}.${this.datasetId}.${e}\` SET ${i} WHERE id=@id`,[c]=await this.bigqueryClient.createQueryJob({query:s,params:o});await c.getQueryResults(),a=[c]}else{if("delete"!==t)throw new Error(`Unsupported operation: ${t}`);{const t=`DELETE FROM \`${this.projectId}.${this.datasetId}.${e}\` WHERE id=@id`,[r]=await this.bigqueryClient.createQueryJob({query:t,params:{id:n}});await r.getQueryResults(),a=[r]}}s.push({table:e,success:!0,jobId:a[0]?.id})});o||a.push({table:e,error:c.message})}if(this.logTable){const[o,s]=await G(async()=>{const o=i.table(this.logTable);await o.insert([{resource_name:e,operation:t,record_id:n,data:JSON.stringify(r),timestamp:(new Date).toISOString(),source:"s3db-replicator"}])})}const c=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:e,operation:t,id:n,tables:o,results:s,errors:a,success:c}),{success:c,results:s,errors:a,tables:o}});return c?l:(this.emit("replicator_error",{replicator:this.name,resourceName:e,operation:t,id:n,error:u.message}),{success:!1,error:u.message})}async replicateBatch(e,t){const r=[],n=[];for(const i of t){const[t,o,s]=await G(()=>this.replicate(e,i.operation,i.data,i.id,i.beforeData));t?r.push(s):n.push({id:i.id,error:o.message})}return{success:0===n.length,results:r,errors:n}}async testConnection(){const[e,t]=await G(async()=>{this.bigqueryClient||await this.initialize();const e=this.bigqueryClient.dataset(this.datasetId);return await e.getMetadata(),!0});return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async cleanup(){}getStatus(){return{...super.getStatus(),projectId:this.projectId,datasetId:this.datasetId,resources:this.resources,logTable:this.logTable}}},postgres:class extends fc{constructor(e={},t={}){super(e),this.connectionString=e.connectionString,this.host=e.host,this.port=e.port||5432,this.database=e.database,this.user=e.user,this.password=e.password,this.client=null,this.ssl=e.ssl,this.logTable=e.logTable,this.resources=this.parseResourcesConfig(t)}parseResourcesConfig(e){const t={};for(const[r,n]of Object.entries(e))"string"==typeof n?t[r]=[{table:n,actions:["insert"]}]:Array.isArray(n)?t[r]=n.map(e=>"string"==typeof e?{table:e,actions:["insert"]}:{table:e.table,actions:e.actions||["insert"]}):"object"==typeof n&&(t[r]=[{table:n.table,actions:n.actions||["insert"]}]);return t}validateConfig(){const e=[];this.connectionString||this.host&&this.database||e.push("Either connectionString or host+database must be provided"),0===Object.keys(this.resources).length&&e.push("At least one resource must be configured");for(const[t,r]of Object.entries(this.resources))for(const n of r){n.table||e.push(`Table name is required for resource '${t}'`),Array.isArray(n.actions)&&0!==n.actions.length||e.push(`Actions array is required for resource '${t}'`);const r=["insert","update","delete"],i=n.actions.filter(e=>!r.includes(e));i.length>0&&e.push(`Invalid actions for resource '${t}': ${i.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}async initialize(e){await super.initialize(e);const[t,r,n]=await G(()=>import("pg"));if(!t)throw this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{Client:i}=n,o=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 i(o),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 e=`\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(e)}shouldReplicateResource(e){return this.resources.hasOwnProperty(e)}shouldReplicateAction(e,t){return!!this.resources[e]&&this.resources[e].some(e=>e.actions.includes(t))}getTablesForResource(e,t){return this.resources[e]?this.resources[e].filter(e=>e.actions.includes(t)).map(e=>e.table):[]}async replicate(e,t,r,n,i=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(e,t))return{skipped:!0,reason:"action_not_included"};const o=this.getTablesForResource(e,t);if(0===o.length)return{skipped:!0,reason:"no_tables_for_action"};const s=[],a=[],[c,u,l]=await G(async()=>{for(const e of o){const[i,o]=await G(async()=>{let i;if("insert"===t){const t=Object.keys(r),n=t.map(e=>r[e]),o=t.map(e=>`"${e}"`).join(", "),s=t.map((e,t)=>`$${t+1}`).join(", "),a=`INSERT INTO ${e} (${o}) VALUES (${s}) ON CONFLICT (id) DO NOTHING RETURNING *`;i=await this.client.query(a,n)}else if("update"===t){const t=Object.keys(r).filter(e=>"id"!==e),o=t.map((e,t)=>`"${e}"=$${t+1}`).join(", "),s=t.map(e=>r[e]);s.push(n);const a=`UPDATE ${e} SET ${o} WHERE id=$${t.length+1} RETURNING *`;i=await this.client.query(a,s)}else{if("delete"!==t)throw new Error(`Unsupported operation: ${t}`);{const t=`DELETE FROM ${e} WHERE id=$1 RETURNING *`;i=await this.client.query(t,[n])}}s.push({table:e,success:!0,rows:i.rows,rowCount:i.rowCount})});i||a.push({table:e,error:o.message})}if(this.logTable){const[i,o]=await G(async()=>{await this.client.query(`INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,[e,t,n,JSON.stringify(r),(new Date).toISOString(),"s3db-replicator"])})}const i=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:e,operation:t,id:n,tables:o,results:s,errors:a,success:i}),{success:i,results:s,errors:a,tables:o}});return c?l:(this.emit("replicator_error",{replicator:this.name,resourceName:e,operation:t,id:n,error:u.message}),{success:!1,error:u.message})}async replicateBatch(e,t){const r=[],n=[];for(const i of t){const[t,o,s]=await G(()=>this.replicate(e,i.operation,i.data,i.id,i.beforeData));t?r.push(s):n.push({id:i.id,error:o.message})}return{success:0===n.length,results:r,errors:n}}async testConnection(){const[e,t]=await G(async()=>(this.client||await this.initialize(),await this.client.query("SELECT 1"),!0));return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async cleanup(){this.client&&await this.client.end()}getStatus(){return{...super.getStatus(),database:this.database||"postgres",resources:this.resources,logTable:this.logTable}}}};function Nh(e,t={},r=[],n=null){const i=Ch[e];if(!i)throw new Error(`Unknown replicator driver: ${e}. Available drivers: ${Object.keys(Ch).join(", ")}`);return new i(t,r,n)}function Rh(e){return"string"==typeof e?e.trim().toLowerCase():e}class Th extends We{constructor(e={}){if(super(),e.verbose&&console.log("[PLUGIN][CONSTRUCTOR] ReplicatorPlugin constructor called"),e.verbose&&console.log("[PLUGIN][constructor] New ReplicatorPlugin instance created with config:",e),!e.replicators||!Array.isArray(e.replicators))throw new Error("ReplicatorPlugin: replicators array is required");for(const t of e.replicators)if(!t.driver)throw new Error("ReplicatorPlugin: each replicator must have a driver");this.config={verbose:e.verbose??!1,persistReplicatorLog:e.persistReplicatorLog??!1,replicatorLogResource:e.replicatorLogResource??"replicator_logs",replicators:e.replicators||[]},this.replicators=[],this.queue=[],this.isProcessing=!1,this.stats={totalOperations:0,totalErrors:0,lastError:null},this._installedListeners=[]}async decompressData(e){return e}filterInternalFields(e){if(!e||"object"!=typeof e)return e;const t={};for(const[r,n]of Object.entries(e))r.startsWith("_")||"$overflow"===r||"$before"===r||"$after"===r||(t[r]=n);return t}installEventListeners(e){const t=this;t.config.verbose&&console.log("[PLUGIN] installEventListeners called for:",e&&e.name,{hasDatabase:!!e.database,sameDatabase:e.database===t.database,alreadyInstalled:e._replicatorListenersInstalled,resourceObj:e,resourceObjId:e&&e.id,resourceObjType:typeof e,resourceObjIs:e&&Object.is(e,t.database.resources&&t.database.resources[e.name]),resourceObjEq:e===(t.database.resources&&t.database.resources[e.name])}),e&&e.name!==t.config.replicatorLogResource&&e.database&&e.database===t.database&&(e._replicatorListenersInstalled||(e._replicatorListenersInstalled=!0,this._installedListeners.push(e),t.config.verbose&&console.log(`[PLUGIN] installEventListeners INSTALLED for resource: ${e&&e.name}`),e.on("insert",async r=>{t.config.verbose&&console.log("[PLUGIN] Listener INSERT on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})));try{const n=await t.getCompleteData(e,r);t.config.verbose&&console.log(`[PLUGIN] Listener INSERT completeData for ${e.name} id=${r&&r.id}:`,n),await t.processReplicatorEvent(e.name,"insert",r.id,n,null)}catch(n){t.config.verbose&&console.error(`[PLUGIN] Listener INSERT error on ${e.name} id=${r&&r.id}:`,n)}}),e.on("update",async r=>{console.log("[PLUGIN][Listener][UPDATE][START] triggered for resource:",e.name,"data:",r);const n=r&&r.$before;t.config.verbose&&console.log("[PLUGIN] Listener UPDATE on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})),"data:",r,"beforeData:",n);try{let i;const[o,s,a]=await G(()=>e.get(r.id));i=o&&a?a:r,await t.processReplicatorEvent(e.name,"update",r.id,i,n)}catch(n){t.config.verbose&&console.error(`[PLUGIN] Listener UPDATE erro em ${e.name} id=${r&&r.id}:`,n)}}),e.on("delete",async(r,n)=>{t.config.verbose&&console.log("[PLUGIN] Listener DELETE on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})));try{await t.processReplicatorEvent(e.name,"delete",r.id,null,n)}catch(n){t.config.verbose&&console.error(`[PLUGIN] Listener DELETE erro em ${e.name} id=${r&&r.id}:`,n)}}),t.config.verbose&&console.log(`[PLUGIN] Listeners instalados para resource: ${e&&e.name} (insert: ${e.listenerCount("insert")}, update: ${e.listenerCount("update")}, delete: ${e.listenerCount("delete")})`)))}async getCompleteData(e,t){const[r,n,i]=await G(()=>e.get(t.id));return r?i:t}async setup(e){if(console.log("[PLUGIN][SETUP] setup called"),this.config.verbose&&console.log("[PLUGIN][setup] called with database:",e&&e.name),this.database=e,this.config.persistReplicatorLog){let t=e.resources[Rh(this.config.replicatorLogResource)];t||(t=await e.createResource({name:this.config.replicatorLogResource,behavior:"truncate-data",attributes:{id:"string|required",resource:"string|required",action:"string|required",data:"object",timestamp:"number|required",createdAt:"string|required"},partitions:{byDate:{fields:{createdAt:"string|maxlength:10"}}}}),this.config.verbose&&console.log("[PLUGIN] Log resource created:",this.config.replicatorLogResource,!!t)),e.resources[Rh(this.config.replicatorLogResource)]=t,this.replicatorLog=t,this.config.verbose&&console.log("[PLUGIN] Log resource created and registered:",this.config.replicatorLogResource,!!e.resources[Rh(this.config.replicatorLogResource)]),"function"==typeof e.uploadMetadataFile&&(await e.uploadMetadataFile(),this.config.verbose&&console.log("[PLUGIN] uploadMetadataFile called. database.resources keys:",Object.keys(e.resources)))}this.config.replicators&&this.config.replicators.length>0&&0===this.replicators.length&&(await this.initializeReplicators(),console.log("[PLUGIN][SETUP] after initializeReplicators, replicators.length:",this.replicators.length),this.config.verbose&&console.log("[PLUGIN][setup] After initializeReplicators, replicators.length:",this.replicators.length,this.replicators.map(e=>({id:e.id,driver:e.driver}))));for(const t in e.resources)Rh(t)!==Rh(this.config.replicatorLogResource)&&this.installEventListeners(e.resources[t]);e.on("connected",()=>{for(const t in e.resources)Rh(t)!==Rh(this.config.replicatorLogResource)&&this.installEventListeners(e.resources[t])});const t=e.createResource.bind(e);e.createResource=async e=>{this.config.verbose&&console.log("[PLUGIN] createResource proxy called for:",e&&e.name);const r=await t(e);return r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r),r},e.on("s3db.resourceCreated",t=>{const r=e.resources[t];r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r)}),e.on("s3db.resourceUpdated",t=>{const r=e.resources[t];r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r)})}async initializeReplicators(){console.log("[PLUGIN][INIT] initializeReplicators called");for(const e of this.config.replicators)try{console.log("[PLUGIN][INIT] processing replicatorConfig:",e);const t=e.driver,r=e.resources,n=Nh(t,e,r,e.client);n?(await n.initialize(this.database),this.replicators.push({id:Math.random().toString(36).slice(2),driver:t,config:e,resources:r,instance:n}),console.log("[PLUGIN][INIT] pushed replicator:",t,r)):console.log("[PLUGIN][INIT] createReplicator returned null/undefined for driver:",t)}catch(e){console.error("[PLUGIN][INIT] Error creating replicator:",e)}}async start(){}async stop(){}async processReplicatorEvent(e,t,r,n,i=null){if(this.config.verbose&&(console.log("[PLUGIN][processReplicatorEvent] replicators.length:",this.replicators.length,this.replicators.map(e=>({id:e.id,driver:e.driver}))),console.log(`[PLUGIN][processReplicatorEvent] operation: ${t}, resource: ${e}, recordId: ${r}, data:`,n,"beforeData:",i)),this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: resource=${e} op=${t} id=${r} data=`,n),this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: resource=${e} op=${t} replicators=${this.replicators.length}`),0===this.replicators.length)return void(this.config.verbose&&console.log("[PLUGIN] No replicators registered"));const o=this.replicators.filter(r=>{const n=r.instance.shouldReplicateResource(e,t);return this.config.verbose&&console.log(`[PLUGIN] Replicator ${r.driver} shouldReplicateResource(${e}, ${t}):`,n),n});if(this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: applicableReplicators for resource=${e}:`,o.map(e=>e.driver)),0===o.length)return void(this.config.verbose&&console.log("[PLUGIN] No applicable replicators for resource",e));const s=this.filterInternalFields(p(n)?n:{raw:n}),a=i?this.filterInternalFields(p(i)?i:{raw:i}):null,c={id:`repl-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e,operation:t,recordId:r,data:s,beforeData:a,timestamp:(new Date).toISOString(),attempts:0},u=await this.logreplicator(c),[l,h,f]=await G(async()=>this.processreplicatorItem(c));l?(u&&await this.updatereplicatorLog(u,{status:f.success?"success":"failed",attempts:1,error:f.success?"":JSON.stringify(f.results)}),this.stats.totalOperations++,f.success?this.stats.successfulOperations++:this.stats.failedOperations++):(u&&await this.updatereplicatorLog(u,{status:"failed",attempts:1,error:h.message}),this.stats.failedOperations++)}async processreplicatorItem(e){this.config.verbose&&console.log("[PLUGIN][processreplicatorItem] called with item:",e);const t=this.replicators.filter(t=>{const r=t.instance.shouldReplicateResource(e.resourceName,e.operation);return this.config.verbose&&console.log(`[PLUGIN] processreplicatorItem: Replicator ${t.driver} shouldReplicateResource(${e.resourceName}, ${e.operation}):`,r),r});if(this.config.verbose&&console.log(`[PLUGIN] processreplicatorItem: applicableReplicators for resource=${e.resourceName}:`,t.map(e=>e.driver)),0===t.length)return this.config.verbose&&console.log("[PLUGIN] processreplicatorItem: No applicable replicators for resource",e.resourceName),{success:!0,skipped:!0,reason:"no_applicable_replicators"};const r=[];for(const n of t){let t,i,o;this.config.verbose&&console.log("[PLUGIN] processReplicatorItem",{resource:e.resourceName,operation:e.operation,data:e.data,beforeData:e.beforeData,replicator:n.instance?.constructor?.name}),n.instance&&n.instance.constructor&&"S3dbReplicator"===n.instance.constructor.name?[i,o,t]=await G(()=>n.instance.replicate({resource:e.resourceName,operation:e.operation,data:e.data,id:e.recordId,beforeData:e.beforeData})):[i,o,t]=await G(()=>n.instance.replicate(e.resourceName,e.operation,e.data,e.recordId,e.beforeData)),r.push({replicatorId:n.id,driver:n.driver,success:t&&t.success,error:t&&t.error,skipped:t&&t.skipped})}return{success:r.every(e=>e.success||e.skipped),results:r}}async logreplicator(e){const t=this.replicatorLog||this.database.resources[Rh(this.config.replicatorLogResource)];if(!t)return this.config.verbose&&console.error("[PLUGIN] replicator log resource not found!"),this.database&&(this.config.verbose&&console.warn("[PLUGIN] database.resources keys:",Object.keys(this.database.resources)),this.database.options&&this.database.options.connectionString&&this.config.verbose&&console.warn("[PLUGIN] database connectionString:",this.database.options.connectionString)),void this.emit("replicator.log.failed",{error:"replicator log resource not found",item:e});const r={id:e.id||`repl-${Date.now()}-${Math.random().toString(36).slice(2)}`,resource:e.resource||e.resourceName||"",action:e.operation||e.action||"",data:e.data||{},timestamp:"number"==typeof e.timestamp?e.timestamp:Date.now(),createdAt:e.createdAt||(new Date).toISOString().slice(0,10)};try{await t.insert(r)}catch(t){this.config.verbose&&console.error("[PLUGIN] Error writing to replicator log:",t),this.emit("replicator.log.failed",{error:t,item:e})}}async updatereplicatorLog(e,t){if(!this.replicatorLog)return;const[r,n]=await G(async()=>{await this.replicatorLog.update(e,{...t,lastAttempt:(new Date).toISOString()})});r||this.emit("replicator.updateLog.failed",{error:n.message,logId:e,updates:t})}async getreplicatorStats(){const e=await Promise.all(this.replicators.map(async e=>{const t=await e.instance.getStatus();return{id:e.id,driver:e.driver,config:e.config,status:t}}));return{replicators:e,queue:{length:this.queue.length,isProcessing:this.isProcessing},stats:this.stats,lastSync:this.stats.lastSync}}async getreplicatorLogs(e={}){if(!this.replicatorLog)return[];const{resourceName:t,operation:r,status:n,limit:i=100,offset:o=0}=e;let s={};t&&(s.resourceName=t),r&&(s.operation=r),n&&(s.status=n);return(await this.replicatorLog.list(s)).slice(o,o+i)}async retryFailedreplicators(){if(!this.replicatorLog)return{retried:0};const e=await this.replicatorLog.list({status:"failed"});let t=0;for(const r of e){const[e,n]=await G(async()=>{await this.processReplicatorEvent(r.resourceName,r.operation,r.recordId,r.data)});e?t++:this.config.verbose&&console.error("Failed to retry replicator:",n)}return{retried:t}}async syncAllData(e){const t=this.replicators.find(t=>t.id===e);if(!t)throw new Error(`Replicator not found: ${e}`);this.stats.lastSync=(new Date).toISOString();for(const r in this.database.resources)if(Rh(r)!==Rh("replicator_logs")&&t.instance.shouldReplicateResource(r)){this.emit("replicator.sync.resource",{resourceName:r,replicatorId:e});const n=this.database.resources[r],i=await n.getAll();for(const e of i)await t.instance.replicate(r,"insert",e,e.id)}this.emit("replicator.sync.completed",{replicatorId:e,stats:this.stats})}async cleanup(){if(this.config.verbose&&console.log("[PLUGIN][CLEANUP] Cleaning up ReplicatorPlugin"),this._installedListeners&&Array.isArray(this._installedListeners)){for(const e of this._installedListeners)e&&"function"==typeof e.removeAllListeners&&(e.removeAllListeners("insert"),e.removeAllListeners("update"),e.removeAllListeners("delete")),e._replicatorListenersInstalled=!1;this._installedListeners=[]}if(this.database&&"function"==typeof this.database.removeAllListeners&&this.database.removeAllListeners(),this.replicators&&Array.isArray(this.replicators)){for(const e of this.replicators)e.instance&&"function"==typeof e.instance.cleanup&&await e.instance.cleanup();this.replicators=[]}this.queue=[],this.isProcessing=!1,this.stats={totalOperations:0,totalErrors:0,lastError:null},this.config.verbose&&console.log("[PLUGIN][CLEANUP] ReplicatorPlugin cleanup complete")}}export{ie as AVAILABLE_BEHAVIORS,Ze as AuditPlugin,me as AuthenticationError,fe as BaseError,ms as CachePlugin,gh as Client,ph as ConnectionString,Se as ConnectionStringError,ys as CostsPlugin,Oe as CryptoError,oe as DEFAULT_BEHAVIOR,Sh as Database,pe as DatabaseError,we as EncryptionError,Be as ErrorMap,ws as FullTextPlugin,Ae as InvalidResourceItem,bs as MetricsPlugin,_e as MissingMetadata,ve as NoSuchBucket,Ee as NoSuchKey,Ie as NotFound,Ne as PartitionError,ye as PermissionError,We as Plugin,Je as PluginObject,Th as ReplicatorPlugin,xh as Resource,Ce as ResourceError,_h as ResourceIdsPageReader,Ih as ResourceIdsReader,be as ResourceNotFound,Ah as ResourceReader,kh as ResourceWriter,dh as S3_DEFAULT_ENDPOINT,fh as S3_DEFAULT_REGION,Oh as S3db,de as S3dbError,Eh as Schema,vh as SchemaActions,Ue as SchemaError,ke as UnknownError,ge as ValidationError,wh as Validator,bh as ValidatorManager,re as behaviors,U as calculateAttributeNamesSize,N as calculateAttributeSizes,D as calculateEffectiveLimit,L as calculateSystemOverhead,R as calculateTotalSize,O as calculateUTF8Bytes,ue as decode,he as decodeDecimal,De as decrypt,Oh as default,ce as encode,le as encodeDecimal,Le as encrypt,ne as getBehavior,T as getSizeBreakdown,Me as idGenerator,xe as mapAwsError,Pe as passwordGenerator,Te as sha256,Bh as streamToString,C as transformValue,G as tryFn,K as tryFnSync};
|
|
1
|
+
import{customAlphabet as e,urlAlphabet as t}from"nanoid";import r from"zlib";import{PromisePool as i}from"@supercharge/promise-pool";import{ReadableStream as s}from"node:stream/web";import"amqplib";import{chunk as n,merge as o,isString as a,isEmpty as c,invert as u,uniq as l,cloneDeep as h,get as f,set as d,isObject as p,isFunction as g,isPlainObject as m}from"lodash-es";import{createHash as y}from"crypto";import b from"json-stable-stringify";import{S3Client as w,PutObjectCommand as v,GetObjectCommand as O,HeadObjectCommand as k,CopyObjectCommand as S,DeleteObjectCommand as _,DeleteObjectsCommand as R,ListObjectsV2Command as j}from"@aws-sdk/client-s3";import{flatten as N,unflatten as I}from"flat";import E from"fastest-validator";function A(e){"string"!=typeof e&&(e=String(e));let t=0;for(let r=0;r<e.length;r++){const i=e.codePointAt(r);i<=127?t+=1:i<=2047?t+=2:i<=65535?t+=3:i<=1114111&&(t+=4,i>65535&&r++)}return t}function D(e){let t=0;for(const r of Object.keys(e))t+=A(r);return t}function x(e){return null==e?"":"boolean"==typeof e?e?"1":"0":"number"==typeof e?String(e):"string"==typeof e?e:Array.isArray(e)?0===e.length?"[]":e.map(e=>String(e)).join("|"):"object"==typeof e?JSON.stringify(e):String(e)}function P(e){const t={};for(const[r,i]of Object.entries(e)){const e=A(x(i));t[r]=e}return t}function C(e){const t=P(e);return Object.values(t).reduce((e,t)=>e+t,0)+D(e)}function T(e){const t=P(e),r=D(e),i=Object.values(t).reduce((e,t)=>e+t,0),s=i+r,n=Object.entries(t).sort(([,e],[,t])=>t-e).map(([e,t])=>({attribute:e,size:t,percentage:(t/s*100).toFixed(2)+"%"}));return{total:s,valueSizes:t,namesSize:r,valueTotal:i,breakdown:n,detailedBreakdown:{values:i,names:r,total:s}}}function L(e={}){const{version:t="1",timestamps:r=!1,id:i=""}=e,s={_v:String(t)};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[e,t]of Object.entries(s))n[e]=t;return C(n)}function $(e={}){const{s3Limit:t=2048,systemConfig:r={}}=e;return t-L(r)}const M=2047;var U=Object.freeze({__proto__:null,S3_METADATA_LIMIT_BYTES:M,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:async function({resource:e,data:t,mappedData:r,originalData:i}){const s=C(r),n=$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.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:e,id:t,data:r,mappedData:i,originalData:s}){const n=C(i),o=$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}});if(n>o)throw new Error(`S3 metadata size exceeds 2KB limit. Current size: ${n} bytes, effective limit: ${o} bytes, absolute limit: 2047 bytes`);return{mappedData:i,body:JSON.stringify(i)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){const s=C(i),n=$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}});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 q=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:async function({resource:e,data:t,mappedData:r,originalData:i}){const s=C(r);return s>$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}})&&e.emit("exceedsLimit",{operation:"insert",totalSize:s,limit:2047,excess:s-2047,data:i||t}),{mappedData:r,body:JSON.stringify(t)}},handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){const n=C(i);return n>$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}})&&e.emit("exceedsLimit",{operation:"update",id:t,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){const n=C(i);return n>$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t}})&&e.emit("exceedsLimit",{operation:"upsert",id:t,totalSize:n,limit:2047,excess:n-2047,data:s||r}),{mappedData:i,body:JSON.stringify(r)}}});const F="$truncated",B="true",z=A(F)+A(B);async function V({resource:e,data:t,mappedData:r,originalData:i}){const s=$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),n=P(r),o=Object.entries(n).sort(([,e],[,t])=>e-t),a={};let c=0,u=!1;r._v&&(a._v=r._v,c+=n._v);for(const[e,t]of o){if("_v"===e)continue;const i=r[e];if(!(c+(t+(u?0:z))<=s)){const t=s-c-(u?0:z);if(t>0){const r=K(i,t);a[e]=r,u=!0,c+=A(r)}else a[e]="",u=!0;break}a[e]=i,c+=t}let l=C(a)+(u?z:0);for(;l>s;){const e=Object.keys(a).filter(e=>"_v"!==e&&"$truncated"!==e);if(0===e.length)break;a[e[e.length-1]]="",l=C(a)+z,u=!0}return u&&(a[F]=B),{mappedData:a,body:JSON.stringify(r)}}function K(e,t){if("string"==typeof e)return H(e,t);if("object"==typeof e&&null!==e){return H(JSON.stringify(e),t)}return H(String(e),t)}function H(e,t){const r=new TextEncoder;let i=r.encode(e);if(i.length<=t)return e;let s=e.length;for(;s>0;){const n=e.substring(0,s);if(i=r.encode(n),i.length<=t)return n;s--}return""}var W=Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){return{metadata:t,body:r}},handleInsert:V,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){return V({resource:e,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return V({resource:e,data:r,mappedData:i})}});function G(e){if(null==e){const e=new Error("fnOrPromise cannot be null or undefined");return e.stack=(new Error).stack,[!1,e,void 0]}if("function"==typeof e)try{const t=e();return null==t?[!0,null,t]:"function"==typeof t.then?t.then(e=>[!0,null,e]).catch(e=>{if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}):[!0,null,t]}catch(e){if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}return"function"==typeof e.then?Promise.resolve(e).then(e=>[!0,null,e]).catch(e=>{if(e instanceof Error&&Object.isExtensible(e)){const t=Object.getOwnPropertyDescriptor(e,"stack");if(t&&t.writable&&t.configurable&&e.hasOwnProperty("stack"))try{e.stack=(new Error).stack}catch(e){}}return[!1,e,void 0]}):[!0,null,e]}function J(e){try{return[!0,null,e()]}catch(e){return[!1,e,null]}}const Y="$overflow",Q="true",X=A(Y)+A(Q);async function Z({resource:e,data:t,mappedData:r,originalData:i}){const s=$({s3Limit:M,systemConfig:{version:e.version,timestamps:e.config.timestamps,id:t.id}}),n=P(r),o=Object.entries(n).sort(([,e],[,t])=>e-t),a={},c={};let u=0,l=!1;r._v&&(a._v=r._v,u+=n._v);let h=s;for(const[e,t]of o)"_v"!==e&&(!l&&u+t>s&&(h-=X,l=!0),!l&&u+t<=h?(a[e]=r[e],u+=t):(c[e]=r[e],l=!0));l&&(a[Y]=Q);const f=Object.keys(c).length>0;let d=f?JSON.stringify(c):"";return f||(d="{}"),{mappedData:a,body:d}}async function ee({resource:e,data:t,mappedData:r}){const i={_v:r._v||String(e.version)};i._map=JSON.stringify(e.schema.map);return{mappedData:i,body:JSON.stringify(r)}}const te={"user-managed":q,"enforce-limits":U,"truncate-data":W,"body-overflow":Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){let i={};if(r&&""!==r.trim()){const[e,t,s]=J(()=>JSON.parse(r));i=e?s:{}}const s={...i,...t};return delete s.$overflow,{metadata:s,body:r}},handleInsert:Z,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i,originalData:s}){return Z({resource:e,data:r,mappedData:i,originalData:s})},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return Z({resource:e,data:r,mappedData:i})}}),"body-only":Object.freeze({__proto__:null,handleGet:async function({resource:e,metadata:t,body:r}){let i={};if(r&&""!==r.trim()){const[e,t,s]=J(()=>JSON.parse(r));i=e?s:{}}return{metadata:{...i,...t},body:r}},handleInsert:ee,handleUpdate:async function({resource:e,id:t,data:r,mappedData:i}){const s={_v:i._v||String(e.version)};return s._map=JSON.stringify(e.schema.map),{mappedData:s,body:JSON.stringify(i)}},handleUpsert:async function({resource:e,id:t,data:r,mappedData:i}){return ee({resource:e,data:r,mappedData:i})}})};function re(e){const t=te[e];if(!t)throw new Error(`Unknown behavior: ${e}. Available behaviors: ${Object.keys(te).join(", ")}`);return t}const ie=Object.keys(te),se="user-managed",ne="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",oe=Object.fromEntries([...ne].map((e,t)=>[e,t])),ae=e=>{if("number"!=typeof e||isNaN(e))return"undefined";if(!isFinite(e))return"undefined";if(0===e)return ne[0];if(e<0)return"-"+ae(-Math.floor(e));e=Math.floor(e);let t="";for(;e;)t=ne[e%62]+t,e=Math.floor(e/62);return t},ce=e=>{if("string"!=typeof e)return NaN;if(""===e)return 0;let t=!1;"-"===e[0]&&(t=!0,e=e.slice(1));let r=0;for(let t=0;t<e.length;t++){const i=oe[e[t]];if(void 0===i)return NaN;r=62*r+i}return t?-r:r},ue=e=>{if("number"!=typeof e||isNaN(e))return"undefined";if(!isFinite(e))return"undefined";const t=e<0;e=Math.abs(e);const[r,i]=e.toString().split("."),s=ae(Number(r));return i?(t?"-":"")+s+"."+i:(t?"-":"")+s},le=e=>{if("string"!=typeof e)return NaN;let t=!1;"-"===e[0]&&(t=!0,e=e.slice(1));const[r,i]=e.split("."),s=ce(r);if(isNaN(s))return NaN;const n=i?Number(s+"."+i):s;return t?-n:n};class he extends Error{constructor({verbose:e,bucket:t,key:r,message:i,code:s,statusCode:n,requestId:o,awsMessage:a,original:c,commandName:u,commandInput:l,metadata:h,suggestion:f,...d}){e&&(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=t,this.key=r,this.thrownAt=new Date,this.code=s,this.statusCode=n,this.requestId=o,this.awsMessage=a,this.original=c,this.commandName=u,this.commandInput=l,this.metadata=h,this.suggestion=f,this.data={bucket:t,key:r,...d,verbose:e,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 fe extends he{constructor(e,t={}){let r,i,s,n,o,a;t.original&&(o=t.original,r=o.code||o.Code||o.name,i=o.statusCode||o.$metadata&&o.$metadata.httpStatusCode,s=o.requestId||o.$metadata&&o.$metadata.requestId,n=o.message,a=o.$metadata?{...o.$metadata}:void 0),super({message:e,...t,code:r,statusCode:i,requestId:s,awsMessage:n,original:o,metadata:a})}}class de extends fe{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class pe extends fe{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class ge extends fe{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class me extends fe{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class ye extends fe{constructor(e,t={}){super(e,t),Object.assign(this,t)}}class be extends fe{constructor({bucket:e,resourceName:t,id:r,original:i,...s}){if("string"!=typeof r)throw new Error("id must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");if("string"!=typeof t)throw new Error("resourceName must be a string");super(`Resource not found: ${t}/${r} [bucket:${e}]`,{bucket:e,resourceName:t,id:r,original:i,...s})}}class we extends fe{constructor({bucket:e,original:t,...r}){if("string"!=typeof e)throw new Error("bucket must be a string");super(`Bucket does not exists [bucket:${e}]`,{bucket:e,original:t,...r})}}class ve extends fe{constructor({bucket:e,key:t,resourceName:r,id:i,original:s,...n}){if("string"!=typeof t)throw new Error("key must be a string");if("string"!=typeof e)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: ${t} [bucket:${e}]`,{bucket:e,key:t,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class Oe extends fe{constructor({bucket:e,key:t,resourceName:r,id:i,original:s,...n}){if("string"!=typeof t)throw new Error("key must be a string");if("string"!=typeof e)throw new Error("bucket must be a string");super(`Not found: ${t} [bucket:${e}]`,{bucket:e,key:t,resourceName:r,id:i,original:s,...n}),this.resourceName=r,this.id=i}}class ke extends fe{constructor({bucket:e,original:t,...r}){if("string"!=typeof e)throw new Error("bucket must be a string");super(`Missing metadata for bucket [bucket:${e}]`,{bucket:e,original:t,...r})}}class Se extends fe{constructor({bucket:e,resourceName:t,attributes:r,validation:i,message:s,original:n,...o}){if("string"!=typeof e)throw new Error("bucket must be a string");if("string"!=typeof t)throw new Error("resourceName must be a string");super(s||`Validation error: This item is not valid. Resource=${t} [bucket:${e}].\n${JSON.stringify(i,null,2)}`,{bucket:e,resourceName:t,attributes:r,validation:i,original:n,...o})}}class _e extends fe{}const Re={NotFound:Oe,NoSuchKey:ve,UnknownError:_e,NoSuchBucket:we,MissingMetadata:ke,InvalidResourceItem:Se};function je(e,t={}){const r=e.code||e.Code||e.name,i=e.$metadata?{...e.$metadata}:void 0,s=t.commandName,n=t.commandInput;let o;return"NoSuchKey"===r||"NotFound"===r?(o="Check if the key exists in the specified bucket and if your credentials have permission.",new ve({...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"NoSuchBucket"===r?(o="Check if the bucket exists and if your credentials have permission.",new we({...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"AccessDenied"===r||403===e.statusCode||"Forbidden"===r?(o="Check your credentials and bucket policy.",new me("Access denied",{...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"ValidationError"===r||400===e.statusCode?(o="Check the request parameters and payload.",new pe("Validation error",{...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):"MissingMetadata"===r?(o="Check if the object metadata is present and valid.",new ke({...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o})):(o="Check the error details and AWS documentation.",new _e("Unknown error",{...t,original:e,metadata:i,commandName:s,commandInput:n,suggestion:o}))}class Ne extends fe{constructor(e,t={}){super(e,{...t,suggestion:"Check the connection string format and credentials."})}}class Ie extends fe{constructor(e,t={}){super(e,{...t,suggestion:"Check if the crypto library is available and input is valid."})}}class Ee extends fe{constructor(e,t={}){super(e,{...t,suggestion:"Check schema definition and input data."})}}class Ae extends fe{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check resource configuration, attributes, and operation context."}),Object.assign(this,t)}}class De extends fe{constructor(e,t={}){super(e,{...t,suggestion:t.suggestion||"Check partition definition, fields, and input values."})}}async function xe(){let e;if("undefined"!=typeof process){const[t,r,i]=await G(async()=>{const{webcrypto:e}=await import("crypto");return e});if(!t)throw new Ie("Crypto API not available",{original:r,context:"dynamicCrypto"});e=i}else"undefined"!=typeof window&&(e=window.crypto);if(!e)throw new Ie("Could not load any crypto library",{context:"dynamicCrypto"});return e}async function Pe(e){const[t,r,i]=await G(xe);if(!t)throw new Ie("Crypto API not available",{original:r});const s=(new TextEncoder).encode(e),[n,o,a]=await G(()=>i.subtle.digest("SHA-256",s));if(!n)throw new Ie("SHA-256 digest failed",{original:o,input:e});return Array.from(new Uint8Array(a)).map(e=>e.toString(16).padStart(2,"0")).join("")}async function Ce(e,t){const[r,i,s]=await G(xe);if(!r)throw new Ie("Crypto API not available",{original:i});const n=s.getRandomValues(new Uint8Array(16)),[o,a,c]=await G(()=>$e(t,n));if(!o)throw new Ie("Key derivation failed",{original:a,passphrase:t,salt:n});const u=s.getRandomValues(new Uint8Array(12)),l=(new TextEncoder).encode(e),[h,f,d]=await G(()=>s.subtle.encrypt({name:"AES-GCM",iv:u},c,l));if(!h)throw new Ie("Encryption failed",{original:f,content:e});const p=new Uint8Array(n.length+u.length+d.byteLength);return p.set(n),p.set(u,n.length),p.set(new Uint8Array(d),n.length+u.length),function(e){if("undefined"!=typeof process)return Buffer.from(e).toString("base64");{const[t,r,i]=J(()=>String.fromCharCode.apply(null,new Uint8Array(e)));if(!t)throw new Ie("Failed to convert ArrayBuffer to base64 (browser)",{original:r});return window.btoa(i)}}(p)}async function Te(e,t){const[r,i,s]=await G(xe);if(!r)throw new Ie("Crypto API not available",{original:i});const n=function(e){if("undefined"!=typeof process)return new Uint8Array(Buffer.from(e,"base64"));{const[t,r,i]=J(()=>window.atob(e));if(!t)throw new Ie("Failed to decode base64 (browser)",{original:r});const s=i.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=i.charCodeAt(e);return n}}(e),o=n.slice(0,16),a=n.slice(16,28),c=n.slice(28),[u,l,h]=await G(()=>$e(t,o));if(!u)throw new Ie("Key derivation failed (decrypt)",{original:l,passphrase:t,salt:o});const[f,d,p]=await G(()=>s.subtle.decrypt({name:"AES-GCM",iv:a},h,c));if(!f)throw new Ie("Decryption failed",{original:d,encryptedBase64:e});return(new TextDecoder).decode(p)}async function Le(e){if("undefined"==typeof process)throw new Ie("MD5 hashing is only available in Node.js environment",{context:"md5"});const[t,r,i]=await G(async()=>{const{createHash:t}=await import("crypto");return t("md5").update(e).digest("base64")});if(!t)throw new Ie("MD5 hashing failed",{original:r,data:e});return i}async function $e(e,t){const[r,i,s]=await G(xe);if(!r)throw new Ie("Crypto API not available",{original:i});const n=(new TextEncoder).encode(e),[o,a,c]=await G(()=>s.subtle.importKey("raw",n,{name:"PBKDF2"},!1,["deriveKey"]));if(!o)throw new Ie("importKey failed",{original:a,passphrase:e});const[u,l,h]=await G(()=>s.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:1e5,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]));if(!u)throw new Ie("deriveKey failed",{original:l,passphrase:e,salt:t});return h}const Me=e(t,22),Ue=e("ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789",16);var qe;function Fe(){}function Be(){Be.init.call(this)}function ze(e){return void 0===e._maxListeners?Be.defaultMaxListeners:e._maxListeners}function Ve(e,t,r,i){var s,n,o,a;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((n=e._events)?(n.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),n=e._events),o=n[t]):(n=e._events=new Fe,e._eventsCount=0),o){if("function"==typeof o?o=n[t]=i?[r,o]:[o,r]:i?o.unshift(r):o.push(r),!o.warned&&(s=ze(e))&&s>0&&o.length>s){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=o.length,a=c,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=n[t]=r,++e._eventsCount;return e}function Ke(e,t,r){var i=!1;function s(){e.removeListener(t,s),i||(i=!0,r.apply(e,arguments))}return s.listener=r,s}function He(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function We(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Fe.prototype=Object.create(null),Be.EventEmitter=Be,Be.usingDomains=!1,Be.prototype.domain=void 0,Be.prototype._events=void 0,Be.prototype._maxListeners=void 0,Be.defaultMaxListeners=10,Be.init=function(){this.domain=null,Be.usingDomains&&(!qe.active||this instanceof qe.Domain||(this.domain=qe.active)),this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Fe,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Be.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Be.prototype.getMaxListeners=function(){return ze(this)},Be.prototype.emit=function(e){var t,r,i,s,n,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(r=o[e]))return!1;var l="function"==typeof r;switch(i=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var i=e.length,s=We(e,i),n=0;n<i;++n)s[n].call(r)}(r,l,this);break;case 2:!function(e,t,r,i){if(t)e.call(r,i);else for(var s=e.length,n=We(e,s),o=0;o<s;++o)n[o].call(r,i)}(r,l,this,arguments[1]);break;case 3:!function(e,t,r,i,s){if(t)e.call(r,i,s);else for(var n=e.length,o=We(e,n),a=0;a<n;++a)o[a].call(r,i,s)}(r,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,r,i,s,n){if(t)e.call(r,i,s,n);else for(var o=e.length,a=We(e,o),c=0;c<o;++c)a[c].call(r,i,s,n)}(r,l,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(e,t,r,i){if(t)e.apply(r,i);else for(var s=e.length,n=We(e,s),o=0;o<s;++o)n[o].apply(r,i)}(r,l,this,s)}return!0},Be.prototype.addListener=function(e,t){return Ve(this,e,t,!1)},Be.prototype.on=Be.prototype.addListener,Be.prototype.prependListener=function(e,t){return Ve(this,e,t,!0)},Be.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Ke(this,e,t)),this},Be.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Ke(this,e,t)),this},Be.prototype.removeListener=function(e,t){var r,i,s,n,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(r=i[e]))return this;if(r===t||r.listener&&r.listener===t)0===--this._eventsCount?this._events=new Fe:(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(s=-1,n=r.length;n-- >0;)if(r[n]===t||r[n].listener&&r[n].listener===t){o=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 Fe,this;delete i[e]}else!function(e,t){for(var r=t,i=r+1,s=e.length;i<s;r+=1,i+=1)e[r]=e[i];e.pop()}(r,s);i.removeListener&&this.emit("removeListener",e,o||t)}return this},Be.prototype.off=function(e,t){return this.removeListener(e,t)},Be.prototype.removeAllListeners=function(e){var t,r;if(!(r=this._events))return this;if(!r.removeListener)return 0===arguments.length?(this._events=new Fe,this._eventsCount=0):r[e]&&(0===--this._eventsCount?this._events=new Fe:delete r[e]),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 Fe,this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Be.prototype.listeners=function(e){var t,r=this._events;return r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):[]},Be.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):He.call(e,t)},Be.prototype.listenerCount=He,Be.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class Ge extends Be{constructor(e={}){super(),this.name=this.constructor.name,this.options=e,this.hooks=new Map}async setup(e){this.database=e,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(e,t,r){this.hooks.has(e)||this.hooks.set(e,new Map);const i=this.hooks.get(e);i.has(t)||i.set(t,[]),i.get(t).push(r)}removeHook(e,t,r){const i=this.hooks.get(e);if(i&&i.has(t)){const e=i.get(t),s=e.indexOf(r);s>-1&&e.splice(s,1)}}wrapResourceMethod(e,t,r){const i=e[t];if(e._pluginWrappers||(e._pluginWrappers=new Map),e._pluginWrappers.has(t)||e._pluginWrappers.set(t,[]),e._pluginWrappers.get(t).push(r),!e[`_wrapped_${t}`]){e[`_wrapped_${t}`]=i;const r=i&&i._isMockFunction;e[t]=async function(...r){let i=await e[`_wrapped_${t}`](...r);for(const s of e._pluginWrappers.get(t))i=await s.call(this,i,r,t);return i},r&&(Object.setPrototypeOf(e[t],Object.getPrototypeOf(i)),Object.assign(e[t],i))}}addMiddleware(e,t,r){if(e._pluginMiddlewares||(e._pluginMiddlewares={}),!e._pluginMiddlewares[t]){e._pluginMiddlewares[t]=[];const r=e[t].bind(e);e[t]=async function(...i){let s=-1;const n=async(...i)=>(s++,s<e._pluginMiddlewares[t].length?await e._pluginMiddlewares[t][s].call(this,n,...i):await r(...i));return await n(...i)}}e._pluginMiddlewares[t].push(r)}getPartitionValues(e,t){if(!t.config?.partitions)return{};const r={};for(const[i,s]of Object.entries(t.config.partitions))if(s.fields){r[i]={};for(const[n,o]of Object.entries(s.fields)){const s=this.getNestedFieldValue(e,n);null!=s&&(r[i][n]=t.applyPartitionRule(s,o))}}else r[i]={};return r}getNestedFieldValue(e,t){if(!t.includes("."))return e[t]??null;const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return null;i=i[e]}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 Je={setup(e){},start(){},stop(){}};class Ye extends Ge{constructor(e={}){super(e),this.auditResource=null,this.config={includeData:!1!==e.includeData,includePartitions:!1!==e.includePartitions,maxDataSize:e.maxDataSize||1e4,...e}}async onSetup(){const[e,t,r]=await G(()=>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=e?r:this.database.resources.audits||null,(e||this.auditResource)&&(this.installDatabaseProxy(),this.installEventListeners())}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._auditProxyInstalled)return;const e=this.installEventListenersForResource.bind(this);this.database._originalCreateResource=this.database.createResource,this.database.createResource=async function(...t){const r=await this._originalCreateResource(...t);return"audits"!==r.name&&e(r),r},this.database._auditProxyInstalled=!0}installEventListeners(){for(const e of Object.values(this.database.resources))"audits"!==e.name&&this.installEventListenersForResource(e)}installEventListenersForResource(e){e.on("insert",async t=>{const r=t.id||"auto-generated",i=this.config.includePartitions?this.getPartitionValues(t,e):null,s={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.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(t)),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(console.error)}),e.on("update",async t=>{const r=t.id;let i=t.$before;if(this.config.includeData&&!i){const[t,s,n]=await G(()=>e.get(r));t&&(i=n)}const s=this.config.includePartitions?this.getPartitionValues(t,e):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.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(t)),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(console.error)}),e.on("delete",async t=>{const r=t.id;let i=t;if(this.config.includeData&&!i){const[t,s,n]=await G(()=>e.get(r));t&&(i=n)}const s=i&&this.config.includePartitions?this.getPartitionValues(i,e):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.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(console.error)}),e.useMiddleware("deleteMany",async(t,r)=>{const i=t.args[0],s={};if(this.config.includeData)for(const t of i){const[r,i,n]=await G(()=>e.get(t));s[t]=r?n:null}const n=await r();if(n&&n.length>0&&this.config.includeData)for(const t of i){const r=s[t],i=r&&this.config.includePartitions?this.getPartitionValues(r,e):null,n={id:`audit-${Date.now()}-${Math.random().toString(36).substring(2,11)}`,resourceName:e.name,operation:"delete",recordId:t,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(console.error)}return n})}getPartitionValues(e,t){if(!e)return null;const r=t.config?.partitions||{},i={};for(const[t,s]of Object.entries(r))if(s.fields){const r={};for(const[t,i]of Object.entries(s.fields)){const i=this.getNestedFieldValue(e,t);null!=i&&(r[t]=i)}Object.keys(r).length>0&&(i[t]=r)}return i}getNestedFieldValue(e,t){if(!t.includes("."))return e[t];const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return;i=i[e]}return i}getPrimaryPartition(e){if(!e)return null;const t=Object.keys(e);return t.length>0?t[0]:null}async logAudit(e){e.id||(e.id=`audit-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);return await this.auditResource.insert(e)}truncateData(e){if(!e)return e;const t={};for(const[r,i]of Object.entries(e))r.startsWith("_")||"$overflow"===r||(t[r]=i);const r=JSON.stringify(t);if(r.length<=this.config.maxDataSize)return t;let i={...t},s=JSON.stringify(i).length;const n=JSON.stringify({_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}).length,o=this.config.maxDataSize-n;for(const[e,t]of Object.entries(i))if("string"==typeof t&&s>o){const r=s-o,n=Math.max(0,t.length-r-3);n<t.length&&(i[e]=t.substring(0,n)+"...",s=JSON.stringify(i).length)}return{...i,_truncated:!0,_originalSize:r.length,_truncatedAt:(new Date).toISOString()}}async getAuditLogs(e={}){if(!this.auditResource)return[];const[t,r,i]=await G(async()=>{const{resourceName:t,operation:r,recordId:i,userId:s,partition:n,startDate:o,endDate:a,limit:c=100,offset:u=0}=e;let l=(await this.auditResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&((!i||e.recordId===i)&&((!s||e.userId===s)&&((!n||e.partition===n)&&(!(o&&new Date(e.timestamp)<new Date(o))&&!(a&&new Date(e.timestamp)>new Date(a))))))));l.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp));return l.slice(u,u+c).map(e=>{const[t,,r]="string"==typeof e.oldData?J(()=>JSON.parse(e.oldData)):[!0,null,e.oldData],[i,,s]="string"==typeof e.newData?J(()=>JSON.parse(e.newData)):[!0,null,e.newData],[n,,o]=e.partitionValues&&"string"==typeof e.partitionValues?J(()=>JSON.parse(e.partitionValues)):[!0,null,e.partitionValues],[a,,c]=e.metadata&&"string"==typeof e.metadata?J(()=>JSON.parse(e.metadata)):[!0,null,e.metadata];return{...e,oldData:null===e.oldData||void 0===e.oldData||"null"===e.oldData?null:t?r:null,newData:null===e.newData||void 0===e.newData||"null"===e.newData?null:i?s:null,partitionValues:n?o:e.partitionValues,metadata:a?c:e.metadata}})});return t?i:[]}async getRecordHistory(e,t){return this.getAuditLogs({resourceName:e,recordId:t,limit:1e3})}async getPartitionHistory(e,t,r){return this.getAuditLogs({resourceName:e,partition:t,limit:1e3})}async getAuditStats(e={}){const{resourceName:t,startDate:r,endDate:i}=e,s=await this.getAuditLogs({resourceName:t,startDate:r,endDate:i,limit:1e4}),n={total:s.length,byOperation:{},byResource:{},byPartition:{},byUser:{},timeline:{}};for(const e of s)if(n.byOperation[e.operation]=(n.byOperation[e.operation]||0)+1,n.byResource[e.resourceName]=(n.byResource[e.resourceName]||0)+1,e.partition&&(n.byPartition[e.partition]=(n.byPartition[e.partition]||0)+1),n.byUser[e.userId]=(n.byUser[e.userId]||0)+1,e.timestamp){const t=e.timestamp.split("T")[0];n.timeline[t]=(n.timeline[t]||0)+1}return n}}function Qe(e,t){for(var r=0,i=e.length-1;i>=0;i--){var s=e[i];"."===s?e.splice(i,1):".."===s?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}var Xe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,Ze=function(e){return Xe.exec(e).slice(1)};function et(){for(var e="",t=!1,r=arguments.length-1;r>=-1&&!t;r--){var i=r>=0?arguments[r]:"/";if("string"!=typeof i)throw new TypeError("Arguments to path.resolve must be strings");i&&(e=i+"/"+e,t="/"===i.charAt(0))}return(t?"/":"")+(e=Qe(nt(e.split("/"),function(e){return!!e}),!t).join("/"))||"."}function tt(e){var t=rt(e),r="/"===ot(e,-1);return(e=Qe(nt(e.split("/"),function(e){return!!e}),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e}function rt(e){return"/"===e.charAt(0)}function it(){return tt(nt(Array.prototype.slice.call(arguments,0),function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))}var st={extname:function(e){return Ze(e)[3]},basename:function(e,t){var r=Ze(e)[2];return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r},dirname:function(e){var t=Ze(e),r=t[0],i=t[1];return r||i?(i&&(i=i.substr(0,i.length-1)),r+i):"."},sep:"/",delimiter:":",relative:function(e,t){function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var r=e.length-1;r>=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=et(e).substr(1),t=et(t).substr(1);for(var i=r(e.split("/")),s=r(t.split("/")),n=Math.min(i.length,s.length),o=n,a=0;a<n;a++)if(i[a]!==s[a]){o=a;break}var c=[];for(a=o;a<i.length;a++)c.push("..");return(c=c.concat(s.slice(o))).join("/")},join:it,isAbsolute:rt,normalize:tt,resolve:et};function nt(e,t){if(e.filter)return e.filter(t);for(var r=[],i=0;i<e.length;i++)t(e[i],i,e)&&r.push(e[i]);return r}var ot="b"==="ab".substr(-1)?function(e,t,r){return e.substr(t,r)}:function(e,t,r){return t<0&&(t=e.length+t),e.substr(t,r)};class at extends Be{constructor(e={}){super(),this.config=e}async _set(e,t){}async _get(e){}async _del(e){}async _clear(e){}validateKey(e){if(null==e||"string"!=typeof e||!e)throw new Error("Invalid key")}async set(e,t){return this.validateKey(e),await this._set(e,t),this.emit("set",t),t}async get(e){this.validateKey(e);const t=await this._get(e);return this.emit("get",t),t}async del(e){this.validateKey(e);const t=await this._del(e);return this.emit("delete",t),t}async delete(e){return this.del(e)}async clear(e){const t=await this._clear(e);return this.emit("clear",t),t}}var ct="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},ut=[],lt=[],ht="undefined"!=typeof Uint8Array?Uint8Array:Array,ft=!1;function dt(){ft=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0;t<64;++t)ut[t]=e[t],lt[e.charCodeAt(t)]=t;lt["-".charCodeAt(0)]=62,lt["_".charCodeAt(0)]=63}function pt(e){return ut[e>>18&63]+ut[e>>12&63]+ut[e>>6&63]+ut[63&e]}function gt(e,t,r){for(var i,s=[],n=t;n<r;n+=3)i=(e[n]<<16)+(e[n+1]<<8)+e[n+2],s.push(pt(i));return s.join("")}function mt(e){var t;ft||dt();for(var r=e.length,i=r%3,s="",n=[],o=16383,a=0,c=r-i;a<c;a+=o)n.push(gt(e,a,a+o>c?c:a+o));return 1===i?(t=e[r-1],s+=ut[t>>2],s+=ut[t<<4&63],s+="=="):2===i&&(t=(e[r-2]<<8)+e[r-1],s+=ut[t>>10],s+=ut[t>>4&63],s+=ut[t<<2&63],s+="="),n.push(s),n.join("")}function yt(e,t,r,i,s){var n,o,a=8*s-i-1,c=(1<<a)-1,u=c>>1,l=-7,h=r?s-1:0,f=r?-1:1,d=e[t+h];for(h+=f,n=d&(1<<-l)-1,d>>=-l,l+=a;l>0;n=256*n+e[t+h],h+=f,l-=8);for(o=n&(1<<-l)-1,n>>=-l,l+=i;l>0;o=256*o+e[t+h],h+=f,l-=8);if(0===n)n=1-u;else{if(n===c)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,i),n-=u}return(d?-1:1)*o*Math.pow(2,n-i)}function bt(e,t,r,i,s,n){var o,a,c,u=8*n-s-1,l=(1<<u)-1,h=l>>1,f=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,d=i?0:n-1,p=i?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=l):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+h>=1?f/c:f*Math.pow(2,1-h))*c>=2&&(o++,c/=2),o+h>=l?(a=0,o=l):o+h>=1?(a=(t*c-1)*Math.pow(2,s),o+=h):(a=t*Math.pow(2,h-1)*Math.pow(2,s),o=0));s>=8;e[r+d]=255&a,d+=p,a/=256,s-=8);for(o=o<<s|a,u+=s;u>0;e[r+d]=255&o,d+=p,o/=256,u-=8);e[r+d-p]|=128*g}var wt={}.toString,vt=Array.isArray||function(e){return"[object Array]"==wt.call(e)};function Ot(){return St.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function kt(e,t){if(Ot()<t)throw new RangeError("Invalid typed array length");return St.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=St.prototype:(null===e&&(e=new St(t)),e.length=t),e}function St(e,t,r){if(!(St.TYPED_ARRAY_SUPPORT||this instanceof St))return new St(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return jt(this,e)}return _t(this,e,t,r)}function _t(e,t,r,i){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,i){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(i||0))throw new RangeError("'length' is out of bounds");t=void 0===r&&void 0===i?new Uint8Array(t):void 0===i?new Uint8Array(t,r):new Uint8Array(t,r,i);St.TYPED_ARRAY_SUPPORT?(e=t).__proto__=St.prototype:e=Nt(e,t);return e}(e,t,r,i):"string"==typeof t?function(e,t,r){"string"==typeof r&&""!==r||(r="utf8");if(!St.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var i=0|At(t,r);e=kt(e,i);var s=e.write(t,r);s!==i&&(e=e.slice(0,s));return e}(e,t,r):function(e,t){if(Et(t)){var r=0|It(t.length);return 0===(e=kt(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(i=t.length)!=i?kt(e,0):Nt(e,t);if("Buffer"===t.type&&vt(t.data))return Nt(e,t.data)}var i;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function Rt(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function jt(e,t){if(Rt(t),e=kt(e,t<0?0:0|It(t)),!St.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function Nt(e,t){var r=t.length<0?0:0|It(t.length);e=kt(e,r);for(var i=0;i<r;i+=1)e[i]=255&t[i];return e}function It(e){if(e>=Ot())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Ot().toString(16)+" bytes");return 0|e}function Et(e){return!(null==e||!e._isBuffer)}function At(e,t){if(Et(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return ir(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return sr(e).length;default:if(i)return ir(e).length;t=(""+t).toLowerCase(),i=!0}}function Dt(e,t,r){var i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return Ht(this,t,r);case"utf8":case"utf-8":return Bt(this,t,r);case"ascii":return Vt(this,t,r);case"latin1":case"binary":return Kt(this,t,r);case"base64":return Ft(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Wt(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function xt(e,t,r){var i=e[t];e[t]=e[r],e[r]=i}function Pt(e,t,r,i,s){if(0===e.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:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(s)return-1;r=e.length-1}else if(r<0){if(!s)return-1;r=0}if("string"==typeof t&&(t=St.from(t,i)),Et(t))return 0===t.length?-1:Ct(e,t,r,i,s);if("number"==typeof t)return t&=255,St.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):Ct(e,[t],r,i,s);throw new TypeError("val must be string, number or Buffer")}function Ct(e,t,r,i,s){var n,o=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,r/=2}function u(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(s){var l=-1;for(n=r;n<a;n++)if(u(e,n)===u(t,-1===l?0:n-l)){if(-1===l&&(l=n),n-l+1===c)return l*o}else-1!==l&&(n-=n-l),l=-1}else for(r+c>a&&(r=a-c),n=r;n>=0;n--){for(var h=!0,f=0;f<c;f++)if(u(e,n+f)!==u(t,f)){h=!1;break}if(h)return n}return-1}function Tt(e,t,r,i){r=Number(r)||0;var s=e.length-r;i?(i=Number(i))>s&&(i=s):i=s;var n=t.length;if(n%2!=0)throw new TypeError("Invalid hex string");i>n/2&&(i=n/2);for(var o=0;o<i;++o){var a=parseInt(t.substr(2*o,2),16);if(isNaN(a))return o;e[r+o]=a}return o}function Lt(e,t,r,i){return nr(ir(t,e.length-r),e,r,i)}function $t(e,t,r,i){return nr(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function Mt(e,t,r,i){return $t(e,t,r,i)}function Ut(e,t,r,i){return nr(sr(t),e,r,i)}function qt(e,t,r,i){return nr(function(e,t){for(var r,i,s,n=[],o=0;o<e.length&&!((t-=2)<0);++o)i=(r=e.charCodeAt(o))>>8,s=r%256,n.push(s),n.push(i);return n}(t,e.length-r),e,r,i)}function Ft(e,t,r){return 0===t&&r===e.length?mt(e):mt(e.slice(t,r))}function Bt(e,t,r){r=Math.min(e.length,r);for(var i=[],s=t;s<r;){var n,o,a,c,u=e[s],l=null,h=u>239?4:u>223?3:u>191?2:1;if(s+h<=r)switch(h){case 1:u<128&&(l=u);break;case 2:128==(192&(n=e[s+1]))&&(c=(31&u)<<6|63&n)>127&&(l=c);break;case 3:n=e[s+1],o=e[s+2],128==(192&n)&&128==(192&o)&&(c=(15&u)<<12|(63&n)<<6|63&o)>2047&&(c<55296||c>57343)&&(l=c);break;case 4:n=e[s+1],o=e[s+2],a=e[s+3],128==(192&n)&&128==(192&o)&&128==(192&a)&&(c=(15&u)<<18|(63&n)<<12|(63&o)<<6|63&a)>65535&&c<1114112&&(l=c)}null===l?(l=65533,h=1):l>65535&&(l-=65536,i.push(l>>>10&1023|55296),l=56320|1023&l),i.push(l),s+=h}return function(e){var t=e.length;if(t<=zt)return String.fromCharCode.apply(String,e);var r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=zt));return r}(i)}St.TYPED_ARRAY_SUPPORT=void 0===ct.TYPED_ARRAY_SUPPORT||ct.TYPED_ARRAY_SUPPORT,Ot(),St.poolSize=8192,St._augment=function(e){return e.__proto__=St.prototype,e},St.from=function(e,t,r){return _t(null,e,t,r)},St.TYPED_ARRAY_SUPPORT&&(St.prototype.__proto__=Uint8Array.prototype,St.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&St[Symbol.species]),St.alloc=function(e,t,r){return function(e,t,r,i){return Rt(t),t<=0?kt(e,t):void 0!==r?"string"==typeof i?kt(e,t).fill(r,i):kt(e,t).fill(r):kt(e,t)}(null,e,t,r)},St.allocUnsafe=function(e){return jt(null,e)},St.allocUnsafeSlow=function(e){return jt(null,e)},St.isBuffer=function(e){return null!=e&&(!!e._isBuffer||or(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&or(e.slice(0,0))}(e))},St.compare=function(e,t){if(!Et(e)||!Et(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,i=t.length,s=0,n=Math.min(r,i);s<n;++s)if(e[s]!==t[s]){r=e[s],i=t[s];break}return r<i?-1:i<r?1:0},St.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},St.concat=function(e,t){if(!vt(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return St.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var i=St.allocUnsafe(t),s=0;for(r=0;r<e.length;++r){var n=e[r];if(!Et(n))throw new TypeError('"list" argument must be an Array of Buffers');n.copy(i,s),s+=n.length}return i},St.byteLength=At,St.prototype._isBuffer=!0,St.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)xt(this,t,t+1);return this},St.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)xt(this,t,t+3),xt(this,t+1,t+2);return this},St.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)xt(this,t,t+7),xt(this,t+1,t+6),xt(this,t+2,t+5),xt(this,t+3,t+4);return this},St.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?Bt(this,0,e):Dt.apply(this,arguments)},St.prototype.equals=function(e){if(!Et(e))throw new TypeError("Argument must be a Buffer");return this===e||0===St.compare(this,e)},St.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),"<Buffer "+e+">"},St.prototype.compare=function(e,t,r,i,s){if(!Et(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),t<0||r>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&t>=r)return 0;if(i>=s)return-1;if(t>=r)return 1;if(this===e)return 0;for(var n=(s>>>=0)-(i>>>=0),o=(r>>>=0)-(t>>>=0),a=Math.min(n,o),c=this.slice(i,s),u=e.slice(t,r),l=0;l<a;++l)if(c[l]!==u[l]){n=c[l],o=u[l];break}return n<o?-1:o<n?1:0},St.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},St.prototype.indexOf=function(e,t,r){return Pt(this,e,t,r,!0)},St.prototype.lastIndexOf=function(e,t,r){return Pt(this,e,t,r,!1)},St.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}var s=this.length-t;if((void 0===r||r>s)&&(r=s),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var n=!1;;)switch(i){case"hex":return Tt(this,e,t,r);case"utf8":case"utf-8":return Lt(this,e,t,r);case"ascii":return $t(this,e,t,r);case"latin1":case"binary":return Mt(this,e,t,r);case"base64":return Ut(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return qt(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},St.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var zt=4096;function Vt(e,t,r){var i="";r=Math.min(e.length,r);for(var s=t;s<r;++s)i+=String.fromCharCode(127&e[s]);return i}function Kt(e,t,r){var i="";r=Math.min(e.length,r);for(var s=t;s<r;++s)i+=String.fromCharCode(e[s]);return i}function Ht(e,t,r){var i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);for(var s="",n=t;n<r;++n)s+=rr(e[n]);return s}function Wt(e,t,r){for(var i=e.slice(t,r),s="",n=0;n<i.length;n+=2)s+=String.fromCharCode(i[n]+256*i[n+1]);return s}function Gt(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function Jt(e,t,r,i,s,n){if(!Et(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>s||t<n)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function Yt(e,t,r,i){t<0&&(t=65535+t+1);for(var s=0,n=Math.min(e.length-r,2);s<n;++s)e[r+s]=(t&255<<8*(i?s:1-s))>>>8*(i?s:1-s)}function Qt(e,t,r,i){t<0&&(t=4294967295+t+1);for(var s=0,n=Math.min(e.length-r,4);s<n;++s)e[r+s]=t>>>8*(i?s:3-s)&255}function Xt(e,t,r,i,s,n){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Zt(e,t,r,i,s){return s||Xt(e,0,r,4),bt(e,t,r,i,23,4),r+4}function er(e,t,r,i,s){return s||Xt(e,0,r,8),bt(e,t,r,i,52,8),r+8}St.prototype.slice=function(e,t){var r,i=this.length;if((e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t<e&&(t=e),St.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=St.prototype;else{var s=t-e;r=new St(s,void 0);for(var n=0;n<s;++n)r[n]=this[n+e]}return r},St.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||Gt(e,t,this.length);for(var i=this[e],s=1,n=0;++n<t&&(s*=256);)i+=this[e+n]*s;return i},St.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||Gt(e,t,this.length);for(var i=this[e+--t],s=1;t>0&&(s*=256);)i+=this[e+--t]*s;return i},St.prototype.readUInt8=function(e,t){return t||Gt(e,1,this.length),this[e]},St.prototype.readUInt16LE=function(e,t){return t||Gt(e,2,this.length),this[e]|this[e+1]<<8},St.prototype.readUInt16BE=function(e,t){return t||Gt(e,2,this.length),this[e]<<8|this[e+1]},St.prototype.readUInt32LE=function(e,t){return t||Gt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},St.prototype.readUInt32BE=function(e,t){return t||Gt(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},St.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Gt(e,t,this.length);for(var i=this[e],s=1,n=0;++n<t&&(s*=256);)i+=this[e+n]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*t)),i},St.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Gt(e,t,this.length);for(var i=t,s=1,n=this[e+--i];i>0&&(s*=256);)n+=this[e+--i]*s;return n>=(s*=128)&&(n-=Math.pow(2,8*t)),n},St.prototype.readInt8=function(e,t){return t||Gt(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},St.prototype.readInt16LE=function(e,t){t||Gt(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},St.prototype.readInt16BE=function(e,t){t||Gt(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},St.prototype.readInt32LE=function(e,t){return t||Gt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},St.prototype.readInt32BE=function(e,t){return t||Gt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},St.prototype.readFloatLE=function(e,t){return t||Gt(e,4,this.length),yt(this,e,!0,23,4)},St.prototype.readFloatBE=function(e,t){return t||Gt(e,4,this.length),yt(this,e,!1,23,4)},St.prototype.readDoubleLE=function(e,t){return t||Gt(e,8,this.length),yt(this,e,!0,52,8)},St.prototype.readDoubleBE=function(e,t){return t||Gt(e,8,this.length),yt(this,e,!1,52,8)},St.prototype.writeUIntLE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||Jt(this,e,t,r,Math.pow(2,8*r)-1,0);var s=1,n=0;for(this[t]=255&e;++n<r&&(s*=256);)this[t+n]=e/s&255;return t+r},St.prototype.writeUIntBE=function(e,t,r,i){(e=+e,t|=0,r|=0,i)||Jt(this,e,t,r,Math.pow(2,8*r)-1,0);var s=r-1,n=1;for(this[t+s]=255&e;--s>=0&&(n*=256);)this[t+s]=e/n&255;return t+r},St.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,1,255,0),St.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},St.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,2,65535,0),St.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Yt(this,e,t,!0),t+2},St.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,2,65535,0),St.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Yt(this,e,t,!1),t+2},St.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,4,4294967295,0),St.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Qt(this,e,t,!0),t+4},St.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,4,4294967295,0),St.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Qt(this,e,t,!1),t+4},St.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t|=0,!i){var s=Math.pow(2,8*r-1);Jt(this,e,t,r,s-1,-s)}var n=0,o=1,a=0;for(this[t]=255&e;++n<r&&(o*=256);)e<0&&0===a&&0!==this[t+n-1]&&(a=1),this[t+n]=(e/o|0)-a&255;return t+r},St.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t|=0,!i){var s=Math.pow(2,8*r-1);Jt(this,e,t,r,s-1,-s)}var n=r-1,o=1,a=0;for(this[t+n]=255&e;--n>=0&&(o*=256);)e<0&&0===a&&0!==this[t+n+1]&&(a=1),this[t+n]=(e/o|0)-a&255;return t+r},St.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,1,127,-128),St.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},St.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,2,32767,-32768),St.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):Yt(this,e,t,!0),t+2},St.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,2,32767,-32768),St.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):Yt(this,e,t,!1),t+2},St.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,4,2147483647,-2147483648),St.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Qt(this,e,t,!0),t+4},St.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Jt(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),St.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Qt(this,e,t,!1),t+4},St.prototype.writeFloatLE=function(e,t,r){return Zt(this,e,t,!0,r)},St.prototype.writeFloatBE=function(e,t,r){return Zt(this,e,t,!1,r)},St.prototype.writeDoubleLE=function(e,t,r){return er(this,e,t,!0,r)},St.prototype.writeDoubleBE=function(e,t,r){return er(this,e,t,!1,r)},St.prototype.copy=function(e,t,r,i){if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<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),e.length-t<i-r&&(i=e.length-t+r);var s,n=i-r;if(this===e&&r<t&&t<i)for(s=n-1;s>=0;--s)e[s+t]=this[s+r];else if(n<1e3||!St.TYPED_ARRAY_SUPPORT)for(s=0;s<n;++s)e[s+t]=this[s+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+n),t);return n},St.prototype.fill=function(e,t,r,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),1===e.length){var s=e.charCodeAt(0);s<256&&(e=s)}if(void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!St.isEncoding(i))throw new TypeError("Unknown encoding: "+i)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{var o=Et(e)?e:ir(new St(e,i).toString()),a=o.length;for(n=0;n<r-t;++n)this[n+t]=o[n%a]}return this};var tr=/[^+\/0-9A-Za-z-_]/g;function rr(e){return e<16?"0"+e.toString(16):e.toString(16)}function ir(e,t){var r;t=t||1/0;for(var i=e.length,s=null,n=[],o=0;o<i;++o){if((r=e.charCodeAt(o))>55295&&r<57344){if(!s){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(o+1===i){(t-=3)>-1&&n.push(239,191,189);continue}s=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),s=r;continue}r=65536+(s-55296<<10|r-56320)}else s&&(t-=3)>-1&&n.push(239,191,189);if(s=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=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((t-=4)<0)break;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function sr(e){return function(e){var t,r,i,s,n,o;ft||dt();var a=e.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");n="="===e[a-2]?2:"="===e[a-1]?1:0,o=new ht(3*a/4-n),i=n>0?a-4:a;var c=0;for(t=0,r=0;t<i;t+=4,r+=3)s=lt[e.charCodeAt(t)]<<18|lt[e.charCodeAt(t+1)]<<12|lt[e.charCodeAt(t+2)]<<6|lt[e.charCodeAt(t+3)],o[c++]=s>>16&255,o[c++]=s>>8&255,o[c++]=255&s;return 2===n?(s=lt[e.charCodeAt(t)]<<2|lt[e.charCodeAt(t+1)]>>4,o[c++]=255&s):1===n&&(s=lt[e.charCodeAt(t)]<<10|lt[e.charCodeAt(t+1)]<<4|lt[e.charCodeAt(t+2)]>>2,o[c++]=s>>8&255,o[c++]=255&s),o}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(tr,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function nr(e,t,r,i){for(var s=0;s<i&&!(s+r>=t.length||s>=e.length);++s)t[s+r]=e[s];return s}function or(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function ar(){throw new Error("setTimeout has not been defined")}function cr(){throw new Error("clearTimeout has not been defined")}var ur=ar,lr=cr;function hr(e){if(ur===setTimeout)return setTimeout(e,0);if((ur===ar||!ur)&&setTimeout)return ur=setTimeout,setTimeout(e,0);try{return ur(e,0)}catch(t){try{return ur.call(null,e,0)}catch(t){return ur.call(this,e,0)}}}"function"==typeof ct.setTimeout&&(ur=setTimeout),"function"==typeof ct.clearTimeout&&(lr=clearTimeout);var fr,dr=[],pr=!1,gr=-1;function mr(){pr&&fr&&(pr=!1,fr.length?dr=fr.concat(dr):gr=-1,dr.length&&yr())}function yr(){if(!pr){var e=hr(mr);pr=!0;for(var t=dr.length;t;){for(fr=dr,dr=[];++gr<t;)fr&&fr[gr].run();gr=-1,t=dr.length}fr=null,pr=!1,function(e){if(lr===clearTimeout)return clearTimeout(e);if((lr===cr||!lr)&&clearTimeout)return lr=clearTimeout,clearTimeout(e);try{return lr(e)}catch(t){try{return lr.call(null,e)}catch(t){return lr.call(this,e)}}}(e)}}function br(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];dr.push(new wr(e,t)),1!==dr.length||pr||hr(yr)}function wr(e,t){this.fun=e,this.array=t}wr.prototype.run=function(){this.fun.apply(null,this.array)};var vr=ct.performance||{};vr.now||vr.mozNow||vr.msNow||vr.oNow||vr.webkitNow;var Or,kr={env:{}};Or="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e};var Sr=/%[sdj%]/g;function _r(e){if(!Lr(e)){for(var t=[],r=0;r<arguments.length;r++)t.push(Ir(arguments[r]));return t.join(" ")}r=1;for(var i=arguments,s=i.length,n=String(e).replace(Sr,function(e){if("%%"===e)return"%";if(r>=s)return e;switch(e){case"%s":return String(i[r++]);case"%d":return Number(i[r++]);case"%j":try{return JSON.stringify(i[r++])}catch(e){return"[Circular]"}default:return e}}),o=i[r];r<s;o=i[++r])Tr(o)||!Ur(o)?n+=" "+o:n+=" "+Ir(o);return n}function Rr(e,t){if($r(ct.process))return function(){return Rr(e,t).apply(this,arguments)};if(!0===kr.noDeprecation)return e;var r=!1;return function(){if(!r){if(kr.throwDeprecation)throw new Error(t);kr.traceDeprecation?console.trace(t):console.error(t),r=!0}return e.apply(this,arguments)}}var jr,Nr={};function Ir(e,t){var r={seen:[],stylize:Ar};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),Cr(t)?r.showHidden=t:t&&function(e,t){if(!t||!Ur(t))return e;var r=Object.keys(t),i=r.length;for(;i--;)e[r[i]]=t[r[i]]}(r,t),$r(r.showHidden)&&(r.showHidden=!1),$r(r.depth)&&(r.depth=2),$r(r.colors)&&(r.colors=!1),$r(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=Er),Dr(r,e,r.depth)}function Er(e,t){var r=Ir.styles[t];return r?"["+Ir.colors[r][0]+"m"+e+"["+Ir.colors[r][1]+"m":e}function Ar(e,t){return e}function Dr(e,t,r){if(e.customInspect&&t&&Br(t.inspect)&&t.inspect!==Ir&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(r,e);return Lr(i)||(i=Dr(e,i,r)),i}var s=function(e,t){if($r(t))return e.stylize("undefined","undefined");if(Lr(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(i=t,"number"==typeof i)return e.stylize(""+t,"number");var i;if(Cr(t))return e.stylize(""+t,"boolean");if(Tr(t))return e.stylize("null","null")}(e,t);if(s)return s;var n=Object.keys(t),o=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(n);if(e.showHidden&&(n=Object.getOwnPropertyNames(t)),Fr(t)&&(n.indexOf("message")>=0||n.indexOf("description")>=0))return xr(t);if(0===n.length){if(Br(t)){var a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(Mr(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(qr(t))return e.stylize(Date.prototype.toString.call(t),"date");if(Fr(t))return xr(t)}var c,u,l="",h=!1,f=["{","}"];(c=t,Array.isArray(c)&&(h=!0,f=["[","]"]),Br(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return Mr(t)&&(l=" "+RegExp.prototype.toString.call(t)),qr(t)&&(l=" "+Date.prototype.toUTCString.call(t)),Fr(t)&&(l=" "+xr(t)),0!==n.length||h&&0!=t.length?r<0?Mr(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),u=h?function(e,t,r,i,s){for(var n=[],o=0,a=t.length;o<a;++o)Vr(t,String(o))?n.push(Pr(e,t,r,i,String(o),!0)):n.push("");return s.forEach(function(s){s.match(/^\d+$/)||n.push(Pr(e,t,r,i,s,!0))}),n}(e,t,r,o,n):n.map(function(i){return Pr(e,t,r,o,i,h)}),e.seen.pop(),function(e,t,r){var i=e.reduce(function(e,t){return t.indexOf("\n"),e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(i>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(u,l,f)):f[0]+l+f[1]}function xr(e){return"["+Error.prototype.toString.call(e)+"]"}function Pr(e,t,r,i,s,n){var o,a,c;if((c=Object.getOwnPropertyDescriptor(t,s)||{value:t[s]}).get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),Vr(i,s)||(o="["+s+"]"),a||(e.seen.indexOf(c.value)<0?(a=Tr(r)?Dr(e,c.value,null):Dr(e,c.value,r-1)).indexOf("\n")>-1&&(a=n?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n")):a=e.stylize("[Circular]","special")),$r(o)){if(n&&s.match(/^\d+$/))return a;(o=JSON.stringify(""+s)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+a}function Cr(e){return"boolean"==typeof e}function Tr(e){return null===e}function Lr(e){return"string"==typeof e}function $r(e){return void 0===e}function Mr(e){return Ur(e)&&"[object RegExp]"===zr(e)}function Ur(e){return"object"==typeof e&&null!==e}function qr(e){return Ur(e)&&"[object Date]"===zr(e)}function Fr(e){return Ur(e)&&("[object Error]"===zr(e)||e instanceof Error)}function Br(e){return"function"==typeof e}function zr(e){return Object.prototype.toString.call(e)}function Vr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Kr(){this.head=null,this.tail=null,this.length=0}Ir.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]},Ir.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},Kr.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},Kr.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},Kr.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},Kr.prototype.clear=function(){this.head=this.tail=null,this.length=0},Kr.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},Kr.prototype.concat=function(e){if(0===this.length)return St.alloc(0);if(1===this.length)return this.head.data;for(var t=St.allocUnsafe(e>>>0),r=this.head,i=0;r;)r.data.copy(t,i),i+=r.data.length,r=r.next;return t};var Hr=St.isEncoding||function(e){switch(e&&e.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 Wr(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!Hr(e))throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Jr;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Yr;break;default:return void(this.write=Gr)}this.charBuffer=new St(6),this.charReceived=0,this.charLength=0}function Gr(e){return e.toString(this.encoding)}function Jr(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Yr(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}Wr.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived<this.charLength)return"";if(e=e.slice(r,e.length),!((s=(t=this.charBuffer.slice(0,this.charLength).toString(this.encoding)).charCodeAt(t.length-1))>=55296&&s<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var i=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,i),i-=this.charReceived);var s;i=(t+=e.toString(this.encoding,0,i)).length-1;if((s=t.charCodeAt(i))>=55296&&s<=56319){var n=this.surrogateSize;return this.charLength+=n,this.charReceived+=n,this.charBuffer.copy(this.charBuffer,n,0,n),e.copy(this.charBuffer,0,0,n),t.substring(0,i)}return t},Wr.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},Wr.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,i=this.charBuffer,s=this.encoding;t+=i.slice(0,r).toString(s)}return t},Zr.ReadableState=Xr;var Qr=function(e){if($r(jr)&&(jr=kr.env.NODE_DEBUG||""),e=e.toUpperCase(),!Nr[e])if(new RegExp("\\b"+e+"\\b","i").test(jr)){Nr[e]=function(){var t=_r.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else Nr[e]=function(){};return Nr[e]}("stream");function Xr(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof Ni&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,i=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i,this.highWaterMark=~~this.highWaterMark,this.buffer=new Kr,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=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new Wr(e.encoding),this.encoding=e.encoding)}function Zr(e){if(!(this instanceof Zr))return new Zr(e);this._readableState=new Xr(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Be.call(this)}function ei(e,t,r,i,s){var n=function(e,t){var r=null;St.isBuffer(t)||"string"==typeof t||null==t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(t,r);if(n)e.emit("error",n);else if(null===r)t.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,ii(e)}(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!s){var o=new Error("stream.push() after EOF");e.emit("error",o)}else if(t.endEmitted&&s){var a=new Error("stream.unshift() after end event");e.emit("error",a)}else{var c;!t.decoder||s||i||(r=t.decoder.write(r),c=!t.objectMode&&0===r.length),s||(t.reading=!1),c||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,s?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&ii(e))),function(e,t){t.readingMore||(t.readingMore=!0,br(ni,e,t))}(e,t)}else s||(t.reading=!1);return function(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}(t)}Or(Zr,Be),Zr.prototype.push=function(e,t){var r=this._readableState;return r.objectMode||"string"!=typeof e||(t=t||r.defaultEncoding)!==r.encoding&&(e=St.from(e,t),t=""),ei(this,r,e,t,!1)},Zr.prototype.unshift=function(e){return ei(this,this._readableState,e,"",!0)},Zr.prototype.isPaused=function(){return!1===this._readableState.flowing},Zr.prototype.setEncoding=function(e){return this._readableState.decoder=new Wr(e),this._readableState.encoding=e,this};var ti=8388608;function ri(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=ti?e=ti:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function ii(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Qr("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?br(si,e):si(e))}function si(e){Qr("emit readable"),e.emit("readable"),ci(e)}function ni(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(Qr("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=!1}function oi(e){Qr("readable nexttick read 0"),e.read(0)}function ai(e,t){t.reading||(Qr("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),ci(e),t.flowing&&!t.reading&&e.read(0)}function ci(e){var t=e._readableState;for(Qr("flow",t.flowing);t.flowing&&null!==e.read(););}function ui(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var i;e<t.head.data.length?(i=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):i=e===t.head.data.length?t.shift():r?function(e,t){var r=t.head,i=1,s=r.data;e-=s.length;for(;r=r.next;){var n=r.data,o=e>n.length?n.length:e;if(o===n.length?s+=n:s+=n.slice(0,e),0===(e-=o)){o===n.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=n.slice(o));break}++i}return t.length-=i,s}(e,t):function(e,t){var r=St.allocUnsafe(e),i=t.head,s=1;i.data.copy(r),e-=i.data.length;for(;i=i.next;){var n=i.data,o=e>n.length?n.length:e;if(n.copy(r,r.length-e,0,o),0===(e-=o)){o===n.length?(++s,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=n.slice(o));break}++s}return t.length-=s,r}(e,t);return i}(e,t.buffer,t.decoder),r);var r}function li(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,br(hi,t,e))}function hi(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function fi(e,t){for(var r=0,i=e.length;r<i;r++)if(e[r]===t)return r;return-1}function di(){}function pi(e,t,r){this.chunk=e,this.encoding=t,this.callback=r,this.next=null}function gi(e,t){Object.defineProperty(this,"buffer",{get:Rr(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")}),e=e||{},this.objectMode=!!e.objectMode,t instanceof Ni&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var r=e.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===e.decodeStrings;this.decodeStrings=!s,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,i=r.sync,s=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,i,s){--t.pendingcb,r?br(s,i):s(i);e._writableState.errorEmitted=!0,e.emit("error",i)}(e,r,i,t,s);else{var n=vi(r);n||r.corked||r.bufferProcessing||!r.bufferedRequest||wi(e,r),i?br(bi,e,r,n,s):bi(e,r,n,s)}}(t,e)},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 Si(this)}function mi(e){if(!(this instanceof mi||this instanceof Ni))return new mi(e);this._writableState=new gi(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev)),Be.call(this)}function yi(e,t,r,i,s,n,o){t.writelen=i,t.writecb=o,t.writing=!0,t.sync=!0,r?e._writev(s,t.onwrite):e._write(s,n,t.onwrite),t.sync=!1}function bi(e,t,r,i){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,i(),ki(e,t)}function wi(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var i=t.bufferedRequestCount,s=new Array(i),n=t.corkedRequestsFree;n.entry=r;for(var o=0;r;)s[o]=r,r=r.next,o+=1;yi(e,t,!0,t.length,s,"",n.finish),t.pendingcb++,t.lastBufferedRequest=null,n.next?(t.corkedRequestsFree=n.next,n.next=null):t.corkedRequestsFree=new Si(t)}else{for(;r;){var a=r.chunk,c=r.encoding,u=r.callback;if(yi(e,t,!1,t.objectMode?1:a.length,a,c,u),r=r.next,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequestCount=0,t.bufferedRequest=r,t.bufferProcessing=!1}function vi(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function Oi(e,t){t.prefinished||(t.prefinished=!0,e.emit("prefinish"))}function ki(e,t){var r=vi(t);return r&&(0===t.pendingcb?(Oi(e,t),t.finished=!0,e.emit("finish")):Oi(e,t)),r}function Si(e){var t=this;this.next=null,this.entry=null,this.finish=function(r){var i=t.entry;for(t.entry=null;i;){var s=i.callback;e.pendingcb--,s(r),i=i.next}e.corkedRequestsFree?e.corkedRequestsFree.next=t:e.corkedRequestsFree=t}}Zr.prototype.read=function(e){Qr("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return Qr("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?li(this):ii(this),null;if(0===(e=ri(e,t))&&t.ended)return 0===t.length&&li(this),null;var i,s=t.needReadable;return Qr("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&Qr("length less than watermark",s=!0),t.ended||t.reading?Qr("reading or ended",s=!1):s&&(Qr("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=ri(r,t))),null===(i=e>0?ui(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&li(this)),null!==i&&this.emit("data",i),i},Zr.prototype._read=function(e){this.emit("error",new Error("not implemented"))},Zr.prototype.pipe=function(e,t){var r=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,Qr("pipe count=%d opts=%j",i.pipesCount,t);var s=!t||!1!==t.end?o:u;function n(e){Qr("onunpipe"),e===r&&u()}function o(){Qr("onend"),e.end()}i.endEmitted?br(s):r.once("end",s),e.on("unpipe",n);var a=function(e){return function(){var t=e._readableState;Qr("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,ci(e))}}(r);e.on("drain",a);var c=!1;function u(){Qr("cleanup"),e.removeListener("close",d),e.removeListener("finish",p),e.removeListener("drain",a),e.removeListener("error",f),e.removeListener("unpipe",n),r.removeListener("end",o),r.removeListener("end",u),r.removeListener("data",h),c=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||a()}var l=!1;function h(t){Qr("ondata"),l=!1,!1!==e.write(t)||l||((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==fi(i.pipes,e))&&!c&&(Qr("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function f(t){var r;Qr("onerror",t),g(),e.removeListener("error",f),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function d(){e.removeListener("finish",p),g()}function p(){Qr("onfinish"),e.removeListener("close",d),g()}function g(){Qr("unpipe"),r.unpipe(e)}return r.on("data",h),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",f),e.once("close",d),e.once("finish",p),e.emit("pipe",r),i.flowing||(Qr("pipe resume"),r.resume()),e},Zr.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this);return this}var n=fi(t.pipes,e);return-1===n||(t.pipes.splice(n,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this)),this},Zr.prototype.on=function(e,t){var r=Be.prototype.on.call(this,e,t);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&ii(this):br(oi,this))}return r},Zr.prototype.addListener=Zr.prototype.on,Zr.prototype.resume=function(){var e=this._readableState;return e.flowing||(Qr("resume"),e.flowing=!0,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,br(ai,e,t))}(this,e)),this},Zr.prototype.pause=function(){return Qr("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(Qr("pause"),this._readableState.flowing=!1,this.emit("pause")),this},Zr.prototype.wrap=function(e){var t=this._readableState,r=!1,i=this;for(var s in e.on("end",function(){if(Qr("wrapped end"),t.decoder&&!t.ended){var e=t.decoder.end();e&&e.length&&i.push(e)}i.push(null)}),e.on("data",function(s){(Qr("wrapped data"),t.decoder&&(s=t.decoder.write(s)),t.objectMode&&null==s)||(t.objectMode||s&&s.length)&&(i.push(s)||(r=!0,e.pause()))}),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));return function(e,t){for(var r=0,i=e.length;r<i;r++)t(e[r],r)}(["error","close","destroy","pause","resume"],function(t){e.on(t,i.emit.bind(i,t))}),i._read=function(t){Qr("wrapped _read",t),r&&(r=!1,e.resume())},i},Zr._fromList=ui,mi.WritableState=gi,Or(mi,Be),gi.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},mi.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},mi.prototype.write=function(e,t,r){var i=this._writableState,s=!1;return"function"==typeof t&&(r=t,t=null),St.isBuffer(e)?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=di),i.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),br(t,r)}(this,r):function(e,t,r,i){var s=!0,n=!1;return null===r?n=new TypeError("May not write null values to stream"):St.isBuffer(r)||"string"==typeof r||void 0===r||t.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n&&(e.emit("error",n),br(i,n),s=!1),s}(this,i,e,r)&&(i.pendingcb++,s=function(e,t,r,i,s){r=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=St.from(t,r));return t}(t,r,i),St.isBuffer(r)&&(i="buffer");var n=t.objectMode?1:r.length;t.length+=n;var o=t.length<t.highWaterMark;o||(t.needDrain=!0);if(t.writing||t.corked){var a=t.lastBufferedRequest;t.lastBufferedRequest=new pi(r,i,s),a?a.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else yi(e,t,!1,n,r,i,s);return o}(this,i,e,t,r)),s},mi.prototype.cork=function(){this._writableState.corked++},mi.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||wi(this,e))},mi.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},mi.prototype._write=function(e,t,r){r(new Error("not implemented"))},mi.prototype._writev=null,mi.prototype.end=function(e,t,r){var i=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||i.finished||function(e,t,r){t.ending=!0,ki(e,t),r&&(t.finished?br(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,i,r)},Or(Ni,Zr);for(var _i=Object.keys(mi.prototype),Ri=0;Ri<_i.length;Ri++){var ji=_i[Ri];Ni.prototype[ji]||(Ni.prototype[ji]=mi.prototype[ji])}function Ni(e){if(!(this instanceof Ni))return new Ni(e);Zr.call(this,e),mi.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",Ii)}function Ii(){this.allowHalfOpen||this._writableState.ended||br(Ei,this)}function Ei(e){e.end()}function Ai(e){this.afterTransform=function(t,r){return function(e,t,r){var i=e._transformState;i.transforming=!1;var s=i.writecb;if(!s)return e.emit("error",new Error("no writecb in Transform class"));i.writechunk=null,i.writecb=null,null!=r&&e.push(r);s(t);var n=e._readableState;n.reading=!1,(n.needReadable||n.length<n.highWaterMark)&&e._read(n.highWaterMark)}(e,t,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function Di(e){if(!(this instanceof Di))return new Di(e);Ni.call(this,e),this._transformState=new Ai(this);var t=this;this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.once("prefinish",function(){"function"==typeof this._flush?this._flush(function(e){xi(t,e)}):xi(t)})}function xi(e,t){if(t)return e.emit("error",t);var r=e._writableState,i=e._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 e.push(null)}function Pi(e){if(!(this instanceof Pi))return new Pi(e);Di.call(this,e)}function Ci(){Be.call(this)}Or(Di,Ni),Di.prototype.push=function(e,t){return this._transformState.needTransform=!1,Ni.prototype.push.call(this,e,t)},Di.prototype._transform=function(e,t,r){throw new Error("Not implemented")},Di.prototype._write=function(e,t,r){var i=this._transformState;if(i.writecb=r,i.writechunk=e,i.writeencoding=t,!i.transforming){var s=this._readableState;(i.needTransform||s.needReadable||s.length<s.highWaterMark)&&this._read(s.highWaterMark)}},Di.prototype._read=function(e){var t=this._transformState;null!==t.writechunk&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0},Or(Pi,Di),Pi.prototype._transform=function(e,t,r){r(null,e)},Or(Ci,Be),Ci.Readable=Zr,Ci.Writable=mi,Ci.Duplex=Ni,Ci.Transform=Di,Ci.PassThrough=Pi,Ci.Stream=Ci,Ci.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function s(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",s),e._isStdio||t&&!1===t.end||(r.on("end",o),r.on("close",a));var n=!1;function o(){n||(n=!0,e.end())}function a(){n||(n=!0,"function"==typeof e.destroy&&e.destroy())}function c(e){if(u(),0===Be.listenerCount(this,"error"))throw e}function u(){r.removeListener("data",i),e.removeListener("drain",s),r.removeListener("end",o),r.removeListener("close",a),r.removeListener("error",c),e.removeListener("error",c),r.removeListener("end",u),r.removeListener("close",u),e.removeListener("close",u)}return r.on("error",c),e.on("error",c),r.on("end",u),r.on("close",u),e.on("close",u),e.emit("pipe",r),e};class Ti extends Be{constructor({resource:e}){super(),this.resource=e,this.client=e.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(e){this.controller=e,this.continuationToken=null,this.closeNextIteration=!1}async _pull(e){if(this.closeNextIteration)return void e.close();const t=await this.client.listObjects({prefix:`resource=${this.resource.name}`,continuationToken:this.continuationToken}),r=t?.Contents.map(e=>e.Key).map(e=>e.replace(this.client.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e).map(e=>e.replace(`resource=${this.resource.name}/id=`,""));this.continuationToken=t.NextContinuationToken,this.enqueue(r),t.IsTruncated||(this.closeNextIteration=!0)}enqueue(e){e.forEach(e=>{this.controller.enqueue(e),this.emit("id",e)})}_cancel(e){}}class Li extends Ti{enqueue(e){this.controller.enqueue(e),this.emit("page",e)}}class $i extends Be{constructor({resource:e,batchSize:t=10,concurrency:r=5}){if(super(),!e)throw new Error("Resource is required for ResourceReader");this.resource=e,this.client=e.client,this.batchSize=t,this.concurrency=r,this.input=new Li({resource:this.resource}),this.transform=new Di({objectMode:!0,transform:this._transform.bind(this)}),this.input.on("data",e=>{this.transform.write(e)}),this.input.on("end",()=>{this.transform.end()}),this.input.on("error",e=>{this.emit("error",e)}),this.transform.on("data",e=>{this.emit("data",e)}),this.transform.on("end",()=>{this.emit("end")}),this.transform.on("error",e=>{this.emit("error",e)})}build(){return this}async _transform(e,t,r){const[s,n]=await G(async()=>{await i.for(e).withConcurrency(this.concurrency).handleError(async(e,t)=>{this.emit("error",e,t)}).process(async e=>{const t=await this.resource.get(e);return this.push(t),t})});r(n)}resume(){this.input.resume()}}class Mi extends Be{constructor({resource:e,batchSize:t=10,concurrency:r=5}){super(),this.resource=e,this.client=e.client,this.batchSize=t,this.concurrency=r,this.buffer=[],this.writing=!1,this.writable=new mi({objectMode:!0,write:this._write.bind(this)}),this.writable.on("finish",()=>{this.emit("finish")}),this.writable.on("error",e=>{this.emit("error",e)})}build(){return this}write(e){return this.buffer.push(e),this._maybeWrite().catch(e=>{this.emit("error",e)}),!0}end(){this.ended=!0,this._maybeWrite().catch(e=>{this.emit("error",e)})}async _maybeWrite(){if(!this.writing&&(0!==this.buffer.length||this.ended)){for(this.writing=!0;this.buffer.length>0;){const e=this.buffer.splice(0,this.batchSize),[t,r]=await G(async()=>{await i.for(e).withConcurrency(this.concurrency).handleError(async(e,t)=>{this.emit("error",e,t)}).process(async e=>{const[t,r,i]=await G(async()=>await this.resource.insert(e));return t?i:(this.emit("error",r,e),null)})});t||this.emit("error",r)}this.writing=!1,this.ended&&this.writable.emit("finish")}}async _write(e,t,r){r()}}function Ui(e){return new Promise((t,r)=>{if(!e)return r(new Error("streamToString: stream is undefined"));const i=[];e.on("data",e=>i.push(e)),e.on("error",r),e.on("end",()=>t(Buffer.concat(i).toString("utf-8")))})}class qi extends at{constructor({client:e,keyPrefix:t="cache",ttl:r=0,prefix:i}){super({client:e,keyPrefix:t,ttl:r,prefix:i}),this.client=e,this.keyPrefix=t,this.config.ttl=r,this.config.client=e,this.config.prefix=void 0!==i?i:t+(t.endsWith("/")?"":"/")}async _set(e,t){let i=JSON.stringify(t);const s=i.length;return i=r.gzipSync(i).toString("base64"),this.client.putObject({key:it(this.keyPrefix,e),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(e){const[t,i,s]=await G(async()=>{const{Body:t}=await this.client.getObject(it(this.keyPrefix,e));let i=await Ui(t);return i=Buffer.from(i,"base64"),i=r.unzipSync(i).toString(),JSON.parse(i)});if(t)return s;if("NoSuchKey"===i.name||"NotFound"===i.name)return null;throw i}async _del(e){return await this.client.deleteObject(it(this.keyPrefix,e)),!0}async _clear(){const e=await this.client.getAllKeys({prefix:this.keyPrefix});await this.client.deleteObjects(e)}async size(){return(await this.keys()).length}async keys(){const e=await this.client.getAllKeys({prefix:this.keyPrefix}),t=this.keyPrefix.endsWith("/")?this.keyPrefix:this.keyPrefix+"/";return e.map(e=>e.startsWith(t)?e.slice(t.length):e)}}class Fi extends at{constructor(e={}){super(e),this.cache={},this.meta={},this.maxSize=e.maxSize||0,this.ttl=e.ttl||0}async _set(e,t){if(this.maxSize>0&&Object.keys(this.cache).length>=this.maxSize){const e=Object.entries(this.meta).sort((e,t)=>e[1].ts-t[1].ts)[0]?.[0];e&&(delete this.cache[e],delete this.meta[e])}return this.cache[e]=t,this.meta[e]={ts:Date.now()},t}async _get(e){if(!Object.prototype.hasOwnProperty.call(this.cache,e))return null;if(this.ttl>0){const t=Date.now(),r=this.meta[e];if(r&&t-r.ts>1e3*this.ttl)return delete this.cache[e],delete this.meta[e],null}return this.cache[e]}async _del(e){return delete this.cache[e],delete this.meta[e],!0}async _clear(e){if(!e)return this.cache={},this.meta={},!0;for(const t of Object.keys(this.cache))t.startsWith(e)&&(delete this.cache[t],delete this.meta[t]);return!0}async size(){return Object.keys(this.cache).length}async keys(){return Object.keys(this.cache)}}class Bi extends Ge{constructor(e={}){super(e),this.driver=e.driver,this.config={includePartitions:!1!==e.includePartitions,...e}}async setup(e){await super.setup(e)}async onSetup(){this.config.driver?this.driver=this.config.driver:"memory"===this.config.driverType?this.driver=new Fi(this.config.memoryOptions||{}):this.driver=new qi({client:this.database.client,...this.config.s3Options||{}}),this.installDatabaseProxy(),this.installResourceHooks()}async onStart(){}async onStop(){}installDatabaseProxy(){if(this.database._cacheProxyInstalled)return;const e=this.installResourceHooks.bind(this);this.database._originalCreateResourceForCache=this.database.createResource,this.database.createResource=async function(...t){const r=await this._originalCreateResourceForCache(...t);return e(r),r},this.database._cacheProxyInstalled=!0}installResourceHooks(){for(const e of Object.values(this.database.resources))this.installResourceHooksForResource(e)}installResourceHooksForResource(e){if(!this.driver)return;Object.defineProperty(e,"cache",{value:this.driver,writable:!0,configurable:!0,enumerable:!1}),e.cacheKeyFor=async(t={})=>{const{action:r,params:i={},partition:s,partitionValues:n}=t;return this.generateCacheKey(e,r,i,s,n)};const t=["count","listIds","getMany","getAll","page","list","get"];for(const r of t)e.useMiddleware(r,async(t,i)=>{let s;if("getMany"===r)s=await e.cacheKeyFor({action:r,params:{ids:t.args[0]}});else if("page"===r){const{offset:i,size:n,partition:o,partitionValues:a}=t.args[0]||{};s=await e.cacheKeyFor({action:r,params:{offset:i,size:n},partition:o,partitionValues:a})}else if("list"===r||"listIds"===r||"count"===r){const{partition:i,partitionValues:n}=t.args[0]||{};s=await e.cacheKeyFor({action:r,partition:i,partitionValues:n})}else"getAll"===r?s=await e.cacheKeyFor({action:r}):"get"===r&&(s=await e.cacheKeyFor({action:r,params:{id:t.args[0]}}));const[n,o,a]=await G(()=>e.cache.get(s));if(n&&null!=a)return a;if(!n&&"NoSuchKey"!==o.name)throw o;const c=await i();return await e.cache.set(s,c),c});const r=["insert","update","delete","deleteMany"];for(const t of r)e.useMiddleware(t,async(r,i)=>{const s=await i();if("insert"===t)await this.clearCacheForResource(e,r.args[0]);else if("update"===t)await this.clearCacheForResource(e,{id:r.args[0],...r.args[1]});else if("delete"===t){let t={id:r.args[0]};if("function"==typeof e.get){const[i,s,n]=await G(()=>e.get(r.args[0]));i&&n&&(t=n)}await this.clearCacheForResource(e,t)}else"deleteMany"===t&&await this.clearCacheForResource(e);return s})}async clearCacheForResource(e,t){if(!e.cache)return;const r=`resource=${e.name}`;if(await e.cache.clear(r),!0===this.config.includePartitions&&e.config?.partitions&&Object.keys(e.config.partitions).length>0)if(t){const i=this.getPartitionValues(t,e);for(const[t,s]of Object.entries(i))if(s&&Object.keys(s).length>0&&Object.values(s).some(e=>null!=e)){const i=it(r,`partition=${t}`);await e.cache.clear(i)}}else for(const t of Object.keys(e.config.partitions)){const i=it(r,`partition=${t}`);await e.cache.clear(i)}}async generateCacheKey(e,t,r={},i=null,s=null){const n=[`resource=${e.name}`,`action=${t}`];if(i&&s&&Object.keys(s).length>0){n.push(`partition:${i}`);for(const[e,t]of Object.entries(s))null!=t&&n.push(`${e}:${t}`)}if(Object.keys(r).length>0){const e=await this.hashParams(r);n.push(e)}return it(...n)+".json.gz"}async hashParams(e){const t=Object.keys(e).sort().map(t=>`${t}:${e[t]}`).join("|")||"empty";return await Pe(t)}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 e of Object.values(this.database.resources))if(e.cache){const t=`resource=${e.name}`;await e.cache.clear(t)}}async warmCache(e,t={}){const r=this.database.resources[e];if(!r)throw new Error(`Resource '${e}' not found`);const{includePartitions:i=!0}=t;if(await r.getAll(),i&&r.config.partitions)for(const[e,t]of Object.entries(r.config.partitions))if(t.fields){const t=await r.getAll(),i=Array.isArray(t)?t:[],s=new Set;for(const t of i.slice(0,10)){const i=this.getPartitionValues(t,r);i[e]&&s.add(JSON.stringify(i[e]))}for(const t of s){const i=JSON.parse(t);await r.list({partition:e,partitionValues:i})}}}}const zi={async setup(e){e&&e.client&&(this.client=e.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",e=>this.addRequest(e,this.map[e])),this.client.on("command.error",e=>this.addRequest(e,this.map[e])))},addRequest(e,t){t&&(this.costs.events[e]++,this.costs.events.total++,this.costs.requests.total++,this.costs.requests[t]++,this.costs.total+=this.costs.prices[t],this.client&&this.client.costs&&(this.client.costs.events[e]++,this.client.costs.events.total++,this.client.costs.requests.total++,this.client.costs.requests[t]++,this.client.costs.total+=this.client.costs.prices[t]))}};class Vi extends Ge{constructor(e={}){super(),this.indexResource=null,this.config={minWordLength:e.minWordLength||3,maxResults:e.maxResults||100,...e},this.indexes=new Map}async setup(e){this.database=e;const[t,r,i]=await G(()=>e.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=t?i:e.resources.fulltext_indexes,await this.loadIndexes(),this.installIndexingHooks()}async start(){}async stop(){await this.saveIndexes()}async loadIndexes(){if(!this.indexResource)return;const[e,t,r]=await G(()=>this.indexResource.getAll());if(e)for(const e of r){const t=`${e.resourceName}:${e.fieldName}:${e.word}`;this.indexes.set(t,{recordIds:e.recordIds||[],count:e.count||0})}}async saveIndexes(){if(!this.indexResource)return;const[e,t]=await G(async()=>{const e=await this.indexResource.getAll();for(const t of e)await this.indexResource.delete(t.id);for(const[e,t]of this.indexes.entries()){const[r,i,s]=e.split(":");await this.indexResource.insert({id:`index-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:r,fieldName:i,word:s,recordIds:t.recordIds,count:t.count,lastUpdated:(new Date).toISOString()})}})}installIndexingHooks(){this.database.plugins||(this.database.plugins={}),this.database.plugins.fulltext=this;for(const e of Object.values(this.database.resources))"fulltext_indexes"!==e.name&&this.installResourceHooks(e);this.database._fulltextProxyInstalled||(this.database._previousCreateResourceForFullText=this.database.createResource,this.database.createResource=async function(...e){const t=await this._previousCreateResourceForFullText(...e);return this.plugins?.fulltext&&"fulltext_indexes"!==t.name&&this.plugins.fulltext.installResourceHooks(t),t},this.database._fulltextProxyInstalled=!0);for(const e of Object.values(this.database.resources))"fulltext_indexes"!==e.name&&this.installResourceHooks(e)}installResourceHooks(e){e._insert=e.insert,e._update=e.update,e._delete=e.delete,e._deleteMany=e.deleteMany,this.wrapResourceMethod(e,"insert",async(t,r,i)=>{const[s]=r;return this.indexRecord(e.name,t.id,s).catch(console.error),t}),this.wrapResourceMethod(e,"update",async(t,r,i)=>{const[s,n]=r;return this.removeRecordFromIndex(e.name,s).catch(console.error),this.indexRecord(e.name,s,t).catch(console.error),t}),this.wrapResourceMethod(e,"delete",async(t,r,i)=>{const[s]=r;return this.removeRecordFromIndex(e.name,s).catch(console.error),t}),this.wrapResourceMethod(e,"deleteMany",async(t,r,i)=>{const[s]=r;for(const t of s)this.removeRecordFromIndex(e.name,t).catch(console.error);return t})}async indexRecord(e,t,r){const i=this.getIndexedFields(e);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=`${e}:${s}:${r.toLowerCase()}`,n=this.indexes.get(i)||{recordIds:[],count:0};n.recordIds.includes(t)||(n.recordIds.push(t),n.count=n.recordIds.length),this.indexes.set(i,n)}}}async removeRecordFromIndex(e,t){for(const[r,i]of this.indexes.entries())if(r.startsWith(`${e}:`)){const e=i.recordIds.indexOf(t);e>-1&&(i.recordIds.splice(e,1),i.count=i.recordIds.length,0===i.recordIds.length?this.indexes.delete(r):this.indexes.set(r,i))}}getFieldValue(e,t){if(!t.includes("."))return e&&void 0!==e[t]?e[t]:null;const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return null;i=i[e]}return i}tokenize(e){if(!e)return[];return String(e).toLowerCase().replace(/[^\w\s\u00C0-\u017F]/g," ").split(/\s+/).filter(e=>e.length>0)}getIndexedFields(e){if(this.config.fields)return this.config.fields;return{users:["name","email"],products:["name","description"],articles:["title","content"]}[e]||[]}async search(e,t,r={}){const{fields:i=null,limit:s=this.config.maxResults,offset:n=0,exactMatch:o=!1}=r;if(!t||0===t.trim().length)return[];const a=this.tokenize(t),c=new Map,u=i||this.getIndexedFields(e);if(0===u.length)return[];for(const t of a)if(!(t.length<this.config.minWordLength))for(const r of u)if(o){const i=`${e}:${r}:${t.toLowerCase()}`,s=this.indexes.get(i);if(s)for(const e of s.recordIds){const t=c.get(e)||0;c.set(e,t+1)}}else for(const[i,s]of this.indexes.entries())if(i.startsWith(`${e}:${r}:${t.toLowerCase()}`))for(const e of s.recordIds){const t=c.get(e)||0;c.set(e,t+1)}return Array.from(c.entries()).map(([e,t])=>({recordId:e,score:t})).sort((e,t)=>t.score-e.score).slice(n,n+s)}async searchRecords(e,t,r={}){const i=await this.search(e,t,r);if(0===i.length)return[];const s=this.database.resources[e];if(!s)throw new Error(`Resource '${e}' not found`);const n=i.map(e=>e.recordId);return(await s.getMany(n)).filter(e=>e&&"object"==typeof e).map(e=>{const t=i.find(t=>t.recordId===e.id);return{...e,_searchScore:t?t.score:0}}).sort((e,t)=>t._searchScore-e._searchScore)}async rebuildIndex(e){const t=this.database.resources[e];if(!t)throw new Error(`Resource '${e}' not found`);for(const[t]of this.indexes.entries())t.startsWith(`${e}:`)&&this.indexes.delete(t);const r=await t.getAll();for(let t=0;t<r.length;t+=100){const i=r.slice(t,t+100);for(const t of i){const[r,i]=await G(()=>this.indexRecord(e,t.id,t))}}await this.saveIndexes()}async getIndexStats(){const e={totalIndexes:this.indexes.size,resources:{},totalWords:0};for(const[t,r]of this.indexes.entries()){const[i,s]=t.split(":");e.resources[i]||(e.resources[i]={fields:{},totalRecords:new Set,totalWords:0}),e.resources[i].fields[s]||(e.resources[i].fields[s]={words:0,totalOccurrences:0}),e.resources[i].fields[s].words++,e.resources[i].fields[s].totalOccurrences+=r.count,e.resources[i].totalWords++;for(const t of r.recordIds)e.resources[i].totalRecords.add(t);e.totalWords++}for(const t in e.resources)e.resources[t].totalRecords=e.resources[t].totalRecords.size;return e}async rebuildAllIndexes({timeout:e}={}){return e?Promise.race([this._rebuildAllIndexesInternal(),new Promise((t,r)=>setTimeout(()=>r(new Error("Timeout")),e))]):this._rebuildAllIndexesInternal()}async _rebuildAllIndexesInternal(){const e=Object.keys(this.database.resources).filter(e=>"fulltext_indexes"!==e);for(const t of e){const[e,r]=await G(()=>this.rebuildIndex(t))}}async clearIndex(e){for(const[t]of this.indexes.entries())t.startsWith(`${e}:`)&&this.indexes.delete(t);await this.saveIndexes()}async clearAllIndexes(){this.indexes.clear(),await this.saveIndexes()}}class Ki extends Ge{constructor(e={}){super(),this.config={collectPerformance:!1!==e.collectPerformance,collectErrors:!1!==e.collectErrors,collectUsage:!1!==e.collectUsage,retentionDays:e.retentionDays||30,flushInterval:e.flushInterval||6e4,...e},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(e){if(this.database=e,"test"===process.env.NODE_ENV)return;const[t,r]=await G(async()=>{const[t,r,i]=await G(()=>e.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=t?i:e.resources.metrics;const[s,n,o]=await G(()=>e.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?o:e.resources.error_logs;const[a,c,u]=await G(()=>e.createResource({name:"performance_logs",attributes:{id:"string|required",resourceName:"string|required",operation:"string|required",duration:"number|required",timestamp:"string|required",metadata:"json"}}));this.performanceResource=a?u:e.resources.performance_logs});t||(this.metricsResource=e.resources.metrics,this.errorsResource=e.resources.error_logs,this.performanceResource=e.resources.performance_logs),this.installMetricsHooks(),"test"!==process.env.NODE_ENV&&this.startFlushTimer()}async start(){}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),"test"!==process.env.NODE_ENV&&await this.flushMetrics()}installMetricsHooks(){for(const e of Object.values(this.database.resources))["metrics","error_logs","performance_logs"].includes(e.name)||this.installResourceHooks(e);this.database._createResource=this.database.createResource,this.database.createResource=async function(...e){const t=await this._createResource(...e);return this.plugins?.metrics&&!["metrics","error_logs","performance_logs"].includes(t.name)&&this.plugins.metrics.installResourceHooks(t),t}}installResourceHooks(e){e._insert=e.insert,e._update=e.update,e._delete=e.delete,e._deleteMany=e.deleteMany,e._get=e.get,e._getMany=e.getMany,e._getAll=e.getAll,e._list=e.list,e._listIds=e.listIds,e._count=e.count,e._page=e.page,e.insert=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._insert(...t));if(this.recordOperation(e.name,"insert",Date.now()-r,!i),i||this.recordError(e.name,"insert",s),!i)throw s;return n}.bind(this),e.update=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._update(...t));if(this.recordOperation(e.name,"update",Date.now()-r,!i),i||this.recordError(e.name,"update",s),!i)throw s;return n}.bind(this),e.delete=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._delete(...t));if(this.recordOperation(e.name,"delete",Date.now()-r,!i),i||this.recordError(e.name,"delete",s),!i)throw s;return n}.bind(this),e.deleteMany=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._deleteMany(...t));if(this.recordOperation(e.name,"delete",Date.now()-r,!i),i||this.recordError(e.name,"delete",s),!i)throw s;return n}.bind(this),e.get=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._get(...t));if(this.recordOperation(e.name,"get",Date.now()-r,!i),i||this.recordError(e.name,"get",s),!i)throw s;return n}.bind(this),e.getMany=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._getMany(...t));if(this.recordOperation(e.name,"get",Date.now()-r,!i),i||this.recordError(e.name,"get",s),!i)throw s;return n}.bind(this),e.getAll=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._getAll(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this),e.list=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._list(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this),e.listIds=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._listIds(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this),e.count=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._count(...t));if(this.recordOperation(e.name,"count",Date.now()-r,!i),i||this.recordError(e.name,"count",s),!i)throw s;return n}.bind(this),e.page=async function(...t){const r=Date.now(),[i,s,n]=await G(()=>e._page(...t));if(this.recordOperation(e.name,"list",Date.now()-r,!i),i||this.recordError(e.name,"list",s),!i)throw s;return n}.bind(this)}recordOperation(e,t,r,i){this.metrics.operations[t]&&(this.metrics.operations[t].count++,this.metrics.operations[t].totalTime+=r,i&&this.metrics.operations[t].errors++),this.metrics.resources[e]||(this.metrics.resources[e]={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[e][t]&&(this.metrics.resources[e][t].count++,this.metrics.resources[e][t].totalTime+=r,i&&this.metrics.resources[e][t].errors++),this.config.collectPerformance&&this.metrics.performance.push({resourceName:e,operation:t,duration:r,timestamp:(new Date).toISOString()})}recordError(e,t,r){this.config.collectErrors&&this.metrics.errors.push({resourceName:e,operation:t,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(console.error)},this.config.flushInterval))}async flushMetrics(){if(!this.metricsResource)return;const[e,t]=await G(async()=>{const e="test"===process.env.NODE_ENV?{}:{global:"true"},t="test"===process.env.NODE_ENV?{}:{perf:"true"},r="test"===process.env.NODE_ENV?{}:{error:"true"},i="test"===process.env.NODE_ENV?{}:{resource:"true"};for(const[t,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:t,count:r.count,totalTime:r.totalTime,errors:r.errors,avgTime:r.count>0?r.totalTime/r.count:0,timestamp:(new Date).toISOString(),metadata:e});for(const[e,t]of Object.entries(this.metrics.resources))for(const[r,s]of Object.entries(t))s.count>0&&await this.metricsResource.insert({id:`metrics-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,type:"operation",resourceName:e,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 e of this.metrics.performance)await this.performanceResource.insert({id:`perf-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e.resourceName,operation:e.operation,duration:e.duration,timestamp:e.timestamp,metadata:t});if(this.config.collectErrors&&this.metrics.errors.length>0)for(const e of this.metrics.errors)await this.errorsResource.insert({id:`error-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e.resourceName,operation:e.operation,error:e.error,stack:e.stack,timestamp:e.timestamp,metadata:r});this.resetMetrics()});e||console.error("Failed to flush metrics:",t)}resetMetrics(){for(const e of Object.keys(this.metrics.operations))this.metrics.operations[e]={count:0,totalTime:0,errors:0};for(const e of Object.keys(this.metrics.resources))for(const t of Object.keys(this.metrics.resources[e]))this.metrics.resources[e][t]={count:0,totalTime:0,errors:0};this.metrics.performance=[],this.metrics.errors=[]}async getMetrics(e={}){const{type:t="operation",resourceName:r,operation:i,startDate:s,endDate:n,limit:o=100,offset:a=0}=e;if(!this.metricsResource)return[];let c=(await this.metricsResource.getAll()).filter(e=>(!t||e.type===t)&&((!r||e.resourceName===r)&&((!i||e.operation===i)&&(!(s&&new Date(e.timestamp)<new Date(s))&&!(n&&new Date(e.timestamp)>new Date(n))))));return c.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),c.slice(a,a+o)}async getErrorLogs(e={}){if(!this.errorsResource)return[];const{resourceName:t,operation:r,startDate:i,endDate:s,limit:n=100,offset:o=0}=e;let a=(await this.errorsResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&(!(i&&new Date(e.timestamp)<new Date(i))&&!(s&&new Date(e.timestamp)>new Date(s)))));return a.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),a.slice(o,o+n)}async getPerformanceLogs(e={}){if(!this.performanceResource)return[];const{resourceName:t,operation:r,startDate:i,endDate:s,limit:n=100,offset:o=0}=e;let a=(await this.performanceResource.getAll()).filter(e=>(!t||e.resourceName===t)&&((!r||e.operation===r)&&(!(i&&new Date(e.timestamp)<new Date(i))&&!(s&&new Date(e.timestamp)>new Date(s)))));return a.sort((e,t)=>new Date(t.timestamp)-new Date(e.timestamp)),a.slice(o,o+n)}async getStats(){const e=new Date,t=new Date(e.getTime()-864e5),[r,i,s]=await Promise.all([this.getMetrics({startDate:t.toISOString()}),this.getErrorLogs({startDate:t.toISOString()}),this.getPerformanceLogs({startDate:t.toISOString()})]),n={period:"24h",totalOperations:0,totalErrors:i.length,avgResponseTime:0,operationsByType:{},resources:{},uptime:{startTime:this.metrics.startTime,duration:e.getTime()-new Date(this.metrics.startTime).getTime()}};for(const e of r)if("operation"===e.type){n.totalOperations+=e.count,n.operationsByType[e.operation]||(n.operationsByType[e.operation]={count:0,errors:0,avgTime:0}),n.operationsByType[e.operation].count+=e.count,n.operationsByType[e.operation].errors+=e.errors;const t=n.operationsByType[e.operation],r=t.count,i=(t.avgTime*(r-e.count)+e.totalTime)/r;t.avgTime=i}const o=r.reduce((e,t)=>e+t.totalTime,0),a=r.reduce((e,t)=>e+t.count,0);return n.avgResponseTime=a>0?o/a:0,n}async cleanupOldData(){const e=new Date;if(e.setDate(e.getDate()-this.config.retentionDays),this.metricsResource){const t=await this.getMetrics({endDate:e.toISOString()});for(const e of t)await this.metricsResource.delete(e.id)}if(this.errorsResource){const t=await this.getErrorLogs({endDate:e.toISOString()});for(const e of t)await this.errorsResource.delete(e.id)}if(this.performanceResource){const t=await this.getPerformanceLogs({endDate:e.toISOString()});for(const e of t)await this.performanceResource.delete(e.id)}}}class Hi extends Be{constructor(e={}){super(),this.config=e,this.name=this.constructor.name,this.enabled=!1!==e.enabled}async initialize(e){this.database=e,this.emit("initialized",{replicator:this.name})}async replicate(e,t,r,i){throw new Error(`replicate() method must be implemented by ${this.name}`)}async replicateBatch(e,t){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:[]}}}const Wi="us-east-1",Gi="https://s3.us-east-1.amazonaws.com";class Ji{constructor(e){let t;const[r,i,s]=G(()=>new URL(e));if(!r)throw new Ne("Invalid connection string: "+e,{original:i,input:e});t=s,this.region=Wi,"s3:"===t.protocol?this.defineFromS3(t):this.defineFromCustomUri(t);for(const[e,r]of t.searchParams.entries())this[e]=r}defineFromS3(e){const[t,r,i]=J(()=>decodeURIComponent(e.hostname));if(!t)throw new Ne("Invalid bucket in connection string",{original:r,input:e.hostname});this.bucket=i||"s3db";const[s,n,o]=J(()=>decodeURIComponent(e.username));if(!s)throw new Ne("Invalid accessKeyId in connection string",{original:n,input:e.username});this.accessKeyId=o;const[a,c,u]=J(()=>decodeURIComponent(e.password));if(!a)throw new Ne("Invalid secretAccessKey in connection string",{original:c,input:e.password});if(this.secretAccessKey=u,this.endpoint=Gi,["/","",null].includes(e.pathname))this.keyPrefix="";else{let[,...t]=e.pathname.split("/");this.keyPrefix=[...t||[]].join("/")}}defineFromCustomUri(e){this.forcePathStyle=!0,this.endpoint=e.origin;const[t,r,i]=J(()=>decodeURIComponent(e.username));if(!t)throw new Ne("Invalid accessKeyId in connection string",{original:r,input:e.username});this.accessKeyId=i;const[s,n,o]=J(()=>decodeURIComponent(e.password));if(!s)throw new Ne("Invalid secretAccessKey in connection string",{original:n,input:e.password});if(this.secretAccessKey=o,["/","",null].includes(e.pathname))this.bucket="s3db",this.keyPrefix="";else{let[,t,...r]=e.pathname.split("/");if(t){const[e,r,i]=J(()=>decodeURIComponent(t));if(!e)throw new Ne("Invalid bucket in connection string",{original:r,input:t});this.bucket=i}else this.bucket="s3db";this.keyPrefix=[...r||[]].join("/")}}}class Yi extends Be{constructor({verbose:e=!1,id:t=null,AwsS3Client:r,connectionString:i,parallelism:s=10}){super(),this.verbose=e,this.id=t??Me(),this.parallelism=s,this.config=new Ji(i),this.client=r||this.createClient()}createClient(){let e={region:this.config.region,endpoint:this.config.endpoint};this.config.forcePathStyle&&(e.forcePathStyle=!0),this.config.accessKeyId&&(e.credentials={accessKeyId:this.config.accessKeyId,secretAccessKey:this.config.secretAccessKey});const t=new w(e);return t.middlewareStack.add((e,t)=>async r=>{if("DeleteObjectsCommand"===t.commandName){const e=r.request.body;if(e&&"string"==typeof e){const t=await Le(e);r.request.headers["Content-MD5"]=t}}return e(r)},{step:"build",name:"addContentMd5ForDeleteObjects",priority:"high"}),t}async sendCommand(e){this.emit("command.request",e.constructor.name,e.input);const[t,r,i]=await G(()=>this.client.send(e));if(!t){throw je(r,{bucket:this.config.bucket,key:e.input&&e.input.Key,commandName:e.constructor.name,commandInput:e.input})}return this.emit("command.response",e.constructor.name,i,e.input),i}async putObject({key:e,metadata:t,contentType:r,body:i,contentEncoding:s,contentLength:n}){const o="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";o&&st.join(o,e);const a={};if(t)for(const[e,r]of Object.entries(t)){a[String(e).replace(/[^a-zA-Z0-9\-_]/g,"_")]=String(r)}const c={Bucket:this.config.bucket,Key:o?st.join(o,e):e,Metadata:a,Body:i||Buffer.alloc(0)};let u,l;void 0!==r&&(c.ContentType=r),void 0!==s&&(c.ContentEncoding=s),void 0!==n&&(c.ContentLength=n);try{return u=await this.sendCommand(new v(c)),u}catch(t){throw l=t,je(t,{bucket:this.config.bucket,key:e,commandName:"PutObjectCommand",commandInput:c})}finally{this.emit("putObject",l||u,{key:e,metadata:t,contentType:r,body:i,contentEncoding:s,contentLength:n})}}async getObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:t?st.join(t,e):e};let i,s;try{return i=await this.sendCommand(new O(r)),i}catch(t){throw s=t,je(t,{bucket:this.config.bucket,key:e,commandName:"GetObjectCommand",commandInput:r})}finally{this.emit("getObject",s||i,{key:e})}}async headObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r={Bucket:this.config.bucket,Key:t?st.join(t,e):e};let i,s;try{return i=await this.sendCommand(new k(r)),i}catch(t){throw s=t,je(t,{bucket:this.config.bucket,key:e,commandName:"HeadObjectCommand",commandInput:r})}finally{this.emit("headObject",s||i,{key:e})}}async copyObject({from:e,to:t}){const r={Bucket:this.config.bucket,Key:this.config.keyPrefix?st.join(this.config.keyPrefix,t):t,CopySource:st.join(this.config.bucket,this.config.keyPrefix?st.join(this.config.keyPrefix,e):e)};let i,s;try{return i=await this.sendCommand(new S(r)),i}catch(e){throw s=e,je(e,{bucket:this.config.bucket,key:t,commandName:"CopyObjectCommand",commandInput:r})}finally{this.emit("copyObject",s||i,{from:e,to:t})}}async exists(e){const[t,r]=await G(()=>this.headObject(e));if(t)return!0;if("NoSuchKey"===r.name||"NotFound"===r.name)return!1;throw r}async deleteObject(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";t&&st.join(t,e);const r={Bucket:this.config.bucket,Key:t?st.join(t,e):e};let i,s;try{return i=await this.sendCommand(new _(r)),i}catch(t){throw s=t,je(t,{bucket:this.config.bucket,key:e,commandName:"DeleteObjectCommand",commandInput:r})}finally{this.emit("deleteObject",s||i,{key:e})}}async deleteObjects(e){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"",r=n(e,1e3),{results:s,errors:o}=await i.for(r).withConcurrency(this.parallelism).process(async e=>{for(const r of e)t&&st.join(t,r),this.config.bucket,await this.exists(r);const r={Bucket:this.config.bucket,Delete:{Objects:e.map(e=>({Key:t?st.join(t,e):e}))}};let i;const[s,n,o]=await G(()=>this.sendCommand(new R(r)));if(!s)throw n;return i=o,i&&i.Errors&&i.Errors.length,i&&i.Deleted&&(i.Deleted.length,e.length),i}),a={deleted:s,notFound:o};return this.emit("deleteObjects",a,e),a}async deleteAll({prefix:e}={}){const t="string"==typeof this.config.keyPrefix?this.config.keyPrefix:"";let r,i=0;do{const s=new j({Bucket:this.config.bucket,Prefix:t?st.join(t,e||""):e||"",ContinuationToken:r}),n=await this.client.send(s);if(n.Contents&&n.Contents.length>0){const t=new R({Bucket:this.config.bucket,Delete:{Objects:n.Contents.map(e=>({Key:e.Key}))}}),r=await this.client.send(t),s=r.Deleted?r.Deleted.length:0;i+=s,this.emit("deleteAll",{prefix:e,batch:s,total:i})}r=n.IsTruncated?n.NextContinuationToken:void 0}while(r);return this.emit("deleteAllComplete",{prefix:e,totalDeleted:i}),i}async moveObject({from:e,to:t}){const[r,i]=await G(async()=>{await this.copyObject({from:e,to:t}),await this.deleteObject(e)});if(!r)throw new _e("Unknown error in moveObject",{bucket:this.config.bucket,from:e,to:t,original:i});return!0}async listObjects({prefix:e,maxKeys:t=1e3,continuationToken:r}={}){const i={Bucket:this.config.bucket,MaxKeys:t,ContinuationToken:r,Prefix:this.config.keyPrefix?st.join(this.config.keyPrefix,e||""):e||""},[s,n,o]=await G(()=>this.sendCommand(new j(i)));if(!s)throw new _e("Unknown error in listObjects",{prefix:e,bucket:this.config.bucket,original:n});return this.emit("listObjects",o,i),o}async count({prefix:e}={}){let t,r=0,i=!0;for(;i;){const s={prefix:e,continuationToken:t},n=await this.listObjects(s);r+=n.KeyCount||0,i=n.IsTruncated||!1,t=n.NextContinuationToken}return this.emit("count",r,{prefix:e}),r}async getAllKeys({prefix:e}={}){let t,r=[],i=!0;for(;i;){const s={prefix:e,continuationToken:t},n=await this.listObjects(s);n.Contents&&(r=r.concat(n.Contents.map(e=>e.Key))),i=n.IsTruncated||!1,t=n.NextContinuationToken}return this.config.keyPrefix&&(r=r.map(e=>e.replace(this.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e)),this.emit("getAllKeys",r,{prefix:e}),r}async getContinuationTokenAfterOffset(e={}){const{prefix:t,offset:r=1e3}=e;if(0===r)return null;let i,s=!0,n=0;for(;s;){const e={prefix:t,maxKeys:r<1e3?r:r-n>1e3?1e3:r-n,continuationToken:i},o=await this.listObjects(e);if(o.Contents&&(n+=o.Contents.length),s=o.IsTruncated||!1,i=o.NextContinuationToken,n>=r)break}return this.emit("getContinuationTokenAfterOffset",i||null,e),i||null}async getKeysPage(e={}){const{prefix:t,offset:r=0,amount:i=100}=e;let s,n=[],o=!0;if(r>0&&(s=await this.getContinuationTokenAfterOffset({prefix:t,offset:r}),!s))return this.emit("getKeysPage",[],e),[];for(;o;){const e={prefix:t,continuationToken:s},r=await this.listObjects(e);if(r.Contents&&(n=n.concat(r.Contents.map(e=>e.Key))),o=r.IsTruncated||!1,s=r.NextContinuationToken,n.length>=i){n=n.slice(0,i);break}}return this.config.keyPrefix&&(n=n.map(e=>e.replace(this.config.keyPrefix,"")).map(e=>e.startsWith("/")?e.replace("/",""):e)),this.emit("getKeysPage",n,e),n}async moveAllObjects({prefixFrom:e,prefixTo:t}){const r=await this.getAllKeys({prefix:e}),{results:s,errors:n}=await i.for(r).withConcurrency(this.parallelism).process(async r=>{const i=r.replace(e,t),[s,n]=await G(async()=>{await this.moveObject({from:r,to:i})});if(!s)throw new _e("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:e,prefixTo:t}),n.length>0)throw new Error("Some objects could not be moved");return s}}async function Qi(e,t,r){if(!this.passphrase)return t.push(new pe("Missing configuration for secrets encryption.",{actual:e,type:"encryptionKeyMissing",suggestion:"Provide a passphrase for secret encryption."})),e;const[i,s,n]=await G(()=>Ce(String(e),this.passphrase));return i?n:(t.push(new pe("Problem encrypting secret.",{actual:e,type:"encryptionProblem",error:s,suggestion:"Check the passphrase and input value."})),e)}async function Xi(e,t,r){if(a(e))return e;const[i,s,n]=J(()=>JSON.stringify(e));if(!i)throw new pe("Failed to stringify JSON",{original:s,input:e});return n}class Zi extends E{constructor({options:e,passphrase:t,autoEncrypt:r=!0}={}){super(o({},{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}}},e)),this.passphrase=t,this.autoEncrypt=r,this.alias("secret",{type:"string",custom:this.autoEncrypt?Qi: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?Qi:void 0}),this.alias("secretNumber",{type:"number",custom:this.autoEncrypt?Qi:void 0}),this.alias("json",{type:"any",custom:this.autoEncrypt?Xi:void 0})}}const es=new Proxy(Zi,{instance:null,construct(e,t){return this.instance||(this.instance=new e(...t)),this.instance}});const ts={trim:e=>null==e?e:e.trim(),encrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,i,s]=await G(()=>Ce(e,t));return r?s:e},decrypt:async(e,{passphrase:t})=>{if(null==e)return e;const[r,i,s]=await G(()=>Te(e,t));return r?"null"===s?null:"undefined"!==s?s:void 0:e},toString:e=>null==e?e:String(e),fromArray:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>"string"==typeof e?e.replace(/\\/g,"\\\\").replace(new RegExp(`\\${t}`,"g"),`\\${t}`):String(e)).join(t)},toArray:(e,{separator:t})=>{if(Array.isArray(e))return e;if(null==e)return e;if(""===e)return[];const r=[];let i="",s=0;const n=String(e);for(;s<n.length;)"\\"===n[s]&&s+1<n.length?(i+=n[s+1],s+=2):n[s]===t?(r.push(i),i="",s++):(i+=n[s],s++);return r.push(i),r},toJSON:e=>{if(null===e)return null;if(void 0===e)return;if("string"==typeof e){const[t,r,i]=J(()=>JSON.parse(e));return e}const[t,r,i]=J(()=>JSON.stringify(e));return t?i:e},fromJSON:e=>{if(null===e)return null;if(void 0===e)return;if("string"!=typeof e)return e;if(""===e)return"";const[t,r,i]=J(()=>JSON.parse(e));return t?i:e},toNumber:e=>a(e)?e.includes(".")?parseFloat(e):parseInt(e):e,toBool:e=>[!0,1,"true","1","yes","y"].includes(e),fromBool:e=>[!0,1,"true","1","yes","y"].includes(e)?"1":"0",fromBase62:e=>{if(null==e||""===e)return e;if("number"==typeof e)return e;if("string"==typeof e){const t=ce(e);return isNaN(t)?void 0:t}},toBase62:e=>{if(null==e||""===e)return e;if("number"==typeof e)return ae(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:ae(t)}return e},fromBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return e;if("string"==typeof e){const t=le(e);return isNaN(t)?void 0:t}},toBase62Decimal:e=>{if(null==e||""===e)return e;if("number"==typeof e)return ue(e);if("string"==typeof e){const t=Number(e);return isNaN(t)?e:ue(t)}return e},fromArrayOfNumbers:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>{if("number"==typeof e&&!isNaN(e))return ae(e);const t=Number(e);return isNaN(t)?"":ae(t)}).join(t)},toArrayOfNumbers:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:ce(e));if(null==e)return e;if(""===e)return[];const r=String(e),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===t?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e){const t=ce(e);return isNaN(t)?NaN:t}return NaN})},fromArrayOfDecimals:(e,{separator:t})=>{if(null==e||!Array.isArray(e))return e;if(0===e.length)return"";return e.map(e=>{if("number"==typeof e&&!isNaN(e))return ue(e);const t=Number(e);return isNaN(t)?"":ue(t)}).join(t)},toArrayOfDecimals:(e,{separator:t})=>{if(Array.isArray(e))return e.map(e=>"number"==typeof e?e:le(e));if(null==e)return e;if(""===e)return[];const r=String(e),i=[];let s="",n=0;for(;n<r.length;)"\\"===r[n]&&n+1<r.length?(s+=r[n+1],n+=2):r[n]===t?(i.push(s),s="",n++):(s+=r[n],n++);return i.push(s),i.map(e=>{if("number"==typeof e)return e;if("string"==typeof e&&""!==e){const t=le(e);return isNaN(t)?NaN:t}return NaN})}};class rs{constructor(e){const{map:t,name:r,attributes:i,passphrase:s,version:n=1,options:a={}}=e;this.name=r,this.version=n,this.attributes=i||{},this.passphrase=s??"secret",this.options=o({},this.defaultOptions(),a),this.allNestedObjectsOptional=this.options.allNestedObjectsOptional??!1;const l=this.preprocessAttributesForValidation(this.attributes);if(this.validator=new es({autoEncrypt:!1}).compile(o({$$async:!0},l)),this.options.generateAutoHooks&&this.generateAutoHooks(),c(t)){const e=N(this.attributes,{safe:!0}),t=Object.keys(e).filter(e=>!e.includes("$$")),r=this.extractObjectKeys(this.attributes),i=[...new Set([...t,...r])],{mapping:s,reversedMapping:n}=function(e){const t={},r={};return e.forEach((e,i)=>{const s=ae(i);t[e]=s,r[s]=e}),{mapping:t,reversedMapping:r}}(i);this.map=s,this.reversedMap=n}else this.map=t,this.reversedMap=u(t)}defaultOptions(){return{autoEncrypt:!0,autoDecrypt:!0,arraySeparator:"|",generateAutoHooks:!0,hooks:{beforeMap:{},afterMap:{},beforeUnmap:{},afterUnmap:{}}}}addHook(e,t,r){this.options.hooks[e][t]||(this.options.hooks[e][t]=[]),this.options.hooks[e][t]=l([...this.options.hooks[e][t],r])}extractObjectKeys(e,t=""){const r=[];for(const[i,s]of Object.entries(e)){if(i.startsWith("$$"))continue;const e=t?`${t}.${i}`:i;"object"!=typeof s||null===s||Array.isArray(s)||(r.push(e),"object"===s.$$type&&r.push(...this.extractObjectKeys(s,e)))}return r}generateAutoHooks(){const e=N(h(this.attributes),{safe:!0});for(const[t,r]of Object.entries(e))if(r.includes("array")){if(r.includes("items:string"))this.addHook("beforeMap",t,"fromArray"),this.addHook("afterUnmap",t,"toArray");else if(r.includes("items:number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",t,"fromArrayOfNumbers"),this.addHook("afterUnmap",t,"toArrayOfNumbers")):(this.addHook("beforeMap",t,"fromArrayOfDecimals"),this.addHook("afterUnmap",t,"toArrayOfDecimals"))}}else if(r.includes("secret"))this.options.autoEncrypt&&this.addHook("beforeMap",t,"encrypt"),this.options.autoDecrypt&&this.addHook("afterUnmap",t,"decrypt");else{if(r.includes("number")){r.includes("integer:true")||r.includes("|integer:")||r.includes("|integer")?(this.addHook("beforeMap",t,"toBase62"),this.addHook("afterUnmap",t,"fromBase62")):(this.addHook("beforeMap",t,"toBase62Decimal"),this.addHook("afterUnmap",t,"fromBase62Decimal"));continue}r.includes("boolean")?(this.addHook("beforeMap",t,"fromBool"),this.addHook("afterUnmap",t,"toBool")):(r.includes("json")||"object"===r||r.includes("object"))&&(this.addHook("beforeMap",t,"toJSON"),this.addHook("afterUnmap",t,"fromJSON"))}}static import(e){let{map:t,name:r,options:i,version:s,attributes:n}=a(e)?JSON.parse(e):e;const[o,c,u]=J(()=>rs._importAttributes(n));if(!o)throw new Ee("Failed to import schema attributes",{original:c,input:n});n=u;return new rs({map:t,name:r,options:i,version:s,attributes:n})}static _importAttributes(e){if("string"==typeof e){const[t,r,i]=J(()=>JSON.parse(e));if(t&&"object"==typeof i&&null!==i){const[t,r,s]=J(()=>rs._importAttributes(i));if(!t)throw new Ee("Failed to parse nested schema attribute",{original:r,input:e});return s}return e}if(Array.isArray(e)){const[t,r,i]=J(()=>e.map(e=>rs._importAttributes(e)));if(!t)throw new Ee("Failed to import array schema attributes",{original:r,input:e});return i}if("object"==typeof e&&null!==e){const t={};for(const[r,i]of Object.entries(e)){const[e,s,n]=J(()=>rs._importAttributes(i));if(!e)throw new Ee("Failed to import object schema attribute",{original:s,key:r,input:i});t[r]=n}return t}return e}export(){return{version:this.version,name:this.name,options:this.options,attributes:this._exportAttributes(this.attributes),map:this.map}}_exportAttributes(e){if("string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>this._exportAttributes(e));if("object"==typeof e&&null!==e){const t={};for(const[r,i]of Object.entries(e))t[r]=this._exportAttributes(i);return t}return e}async applyHooksActions(e,t){const r=h(e);for(const[e,i]of Object.entries(this.options.hooks[t]))for(const t of i){const i=f(r,e);void 0!==i&&"function"==typeof ts[t]&&d(r,e,await ts[t](i,{passphrase:this.passphrase,separator:this.options.arraySeparator}))}return r}async validate(e,{mutateOriginal:t=!1}={}){let r=t?e:h(e);return await this.validator(r)}async mapper(e){let t=h(e);t=await this.applyHooksActions(t,"beforeMap");const r=N(t,{safe:!0}),i={_v:this.version+""};for(const[e,t]of Object.entries(r)){const r=this.map[e]||e,s=this.getAttributeDefinition(e);"number"==typeof t&&"string"==typeof s&&s.includes("number")?i[r]=ae(t):"string"==typeof t?"[object Object]"===t?i[r]="{}":(t.startsWith("{")||t.startsWith("["),i[r]=t):Array.isArray(t)||"object"==typeof t&&null!==t?i[r]=JSON.stringify(t):i[r]=t}return await this.applyHooksActions(i,"afterMap"),i}async unmapper(e,t){let r=h(e);delete r._v,r=await this.applyHooksActions(r,"beforeUnmap");const i=t?u(t):this.reversedMap,s={};for(const[e,t]of Object.entries(r)){const r=i&&i[e]?i[e]:e;let n=t;const o=this.getAttributeDefinition(r);if("string"!=typeof o||!o.includes("number")||o.includes("array")||o.includes("decimal")){if("string"==typeof t)if("[object Object]"===t)n={};else if(t.startsWith("{")||t.startsWith("[")){const[e,r,i]=J(()=>JSON.parse(t));e&&(n=i)}}else"string"==typeof n&&""!==n?n=ce(n):"number"==typeof n||(n=void 0);if(this.attributes&&"string"==typeof o&&o.includes("array"))if(Array.isArray(n));else if("string"==typeof n&&n.trim().startsWith("[")){const[e,t,r]=J(()=>JSON.parse(n));e&&Array.isArray(r)&&(n=r)}else n=ts.toArray(n,{separator:this.options.arraySeparator});if(this.options.hooks&&this.options.hooks.afterUnmap&&this.options.hooks.afterUnmap[r])for(const e of this.options.hooks.afterUnmap[r])"function"==typeof ts[e]&&(n=await ts[e](n,{passphrase:this.passphrase,separator:this.options.arraySeparator}));s[r]=n}await this.applyHooksActions(s,"afterUnmap");const n=I(s);for(const[t,r]of Object.entries(e))t.startsWith("$")&&(n[t]=r);return n}getAttributeDefinition(e){const t=e.split(".");let r=this.attributes;for(const e of t){if(!r)return;r=r[e]}return r}preprocessAttributesForValidation(e){const t={};for(const[r,i]of Object.entries(e))if("object"!=typeof i||null===i||Array.isArray(i))t[r]=i;else{const e=i.$$type&&i.$$type.includes("required"),s=i.$$type&&i.$$type.includes("optional"),n={type:"object",properties:this.preprocessAttributesForValidation(i),strict:!1};e||(s||this.allNestedObjectsOptional)&&(n.optional=!0),t[r]=n}return t}}class is extends Be{constructor(e={}){super(),this._instanceId=Math.random().toString(36).slice(2,8);const t=function(e){const t=[];e.name?"string"!=typeof e.name?t.push("Resource 'name' must be a string"):""===e.name.trim()&&t.push("Resource 'name' cannot be empty"):t.push("Resource 'name' is required");e.client||t.push("S3 'client' is required");e.attributes?"object"!=typeof e.attributes||Array.isArray(e.attributes)?t.push("Resource 'attributes' must be an object"):0===Object.keys(e.attributes).length&&t.push("Resource 'attributes' cannot be empty"):t.push("Resource 'attributes' are required");void 0!==e.version&&"string"!=typeof e.version&&t.push("Resource 'version' must be a string");void 0!==e.behavior&&"string"!=typeof e.behavior&&t.push("Resource 'behavior' must be a string");void 0!==e.passphrase&&"string"!=typeof e.passphrase&&t.push("Resource 'passphrase' must be a string");void 0!==e.parallelism&&("number"==typeof e.parallelism&&Number.isInteger(e.parallelism)?e.parallelism<1&&t.push("Resource 'parallelism' must be greater than 0"):t.push("Resource 'parallelism' must be an integer"));void 0===e.observers||Array.isArray(e.observers)||t.push("Resource 'observers' must be an array");const r=["cache","autoDecrypt","timestamps","paranoid","allNestedObjectsOptional"];for(const i of r)void 0!==e[i]&&"boolean"!=typeof e[i]&&t.push(`Resource '${i}' must be a boolean`);void 0!==e.idGenerator&&("function"!=typeof e.idGenerator&&"number"!=typeof e.idGenerator?t.push("Resource 'idGenerator' must be a function or a number (size)"):"number"==typeof e.idGenerator&&e.idGenerator<=0&&t.push("Resource 'idGenerator' size must be greater than 0"));void 0!==e.idSize&&("number"==typeof e.idSize&&Number.isInteger(e.idSize)?e.idSize<=0&&t.push("Resource 'idSize' must be greater than 0"):t.push("Resource 'idSize' must be an integer"));if(void 0!==e.partitions)if("object"!=typeof e.partitions||Array.isArray(e.partitions))t.push("Resource 'partitions' must be an object");else for(const[r,i]of Object.entries(e.partitions))if("object"!=typeof i||Array.isArray(i))t.push(`Partition '${r}' must be an object`);else if(i.fields)if("object"!=typeof i.fields||Array.isArray(i.fields))t.push(`Partition '${r}.fields' must be an object`);else for(const[e,s]of Object.entries(i.fields))"string"!=typeof s&&t.push(`Partition '${r}.fields.${e}' must be a string`);else t.push(`Partition '${r}' must have a 'fields' property`);if(void 0!==e.hooks)if("object"!=typeof e.hooks||Array.isArray(e.hooks))t.push("Resource 'hooks' must be an object");else{const r=["beforeInsert","afterInsert","beforeUpdate","afterUpdate","beforeDelete","afterDelete"];for(const[i,s]of Object.entries(e.hooks))if(r.includes(i))if(Array.isArray(s))for(let e=0;e<s.length;e++){const t=s[e];if("function"==typeof t);else if("string"==typeof t)continue}else t.push(`Resource 'hooks.${i}' must be an array`);else t.push(`Invalid hook event '${i}'. Valid events: ${r.join(", ")}`)}return{isValid:0===t.length,errors:t}}(e);if(!t.isValid)throw new Ae(`Invalid Resource ${e.name} configuration`,{resourceName:e.name,validation:t.errors,operation:"constructor",suggestion:"Check resource config and attributes."});const{name:r,client:i,version:s="1",attributes:n={},behavior:o=se,passphrase:a="secret",parallelism:c=10,observers:u=[],cache:l=!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}=e;if(this.name=r,this.client=i,this.version=s,this.behavior=o,this.observers=u,this.parallelism=c,this.passphrase=a??"secret",this.versioningEnabled=w,this.idGenerator=this.configureIdGenerator(y,b),this.config={cache:l,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=e.map,this.applyConfiguration({map:this.map}),m)for(const[e,t]of Object.entries(m))if(Array.isArray(t)&&this.hooks[e])for(const r of t)"function"==typeof r&&this.hooks[e].push(r.bind(this));this._initMiddleware()}configureIdGenerator(r,i){return"function"==typeof r?r:"number"==typeof r&&r>0?e(t,r):"number"==typeof i&&i>0&&22!==i?e(t,i):Me}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 e=this.schema.export();return e.behavior=this.behavior,e.timestamps=this.config.timestamps,e.partitions=this.config.partitions||{},e.paranoid=this.config.paranoid,e.allNestedObjectsOptional=this.config.allNestedObjectsOptional,e.autoDecrypt=this.config.autoDecrypt,e.cache=this.config.cache,e.hooks=this.hooks,e.map=this.map,e}applyConfiguration({map:e}={}){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 rs({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:this.version,options:{autoDecrypt:this.config.autoDecrypt,allNestedObjectsOptional:this.config.allNestedObjectsOptional},map:e||this.map}),this.validatePartitions()}updateAttributes(e){const t=this.attributes;return this.attributes=e,this.applyConfiguration({map:this.schema?.map}),{oldAttributes:t,newAttributes:e}}addHook(e,t){this.hooks[e]&&this.hooks[e].push(t.bind(this))}async executeHooks(e,t){if(!this.hooks[e])return t;let r=t;for(const t of this.hooks[e])r=await t(r);return r}setupPartitionHooks(){if(!this.config.partitions)return;const e=this.config.partitions;0!==Object.keys(e).length&&(this.hooks.afterInsert||(this.hooks.afterInsert=[]),this.hooks.afterInsert.push(async e=>(await this.createPartitionReferences(e),e)),this.hooks.afterDelete||(this.hooks.afterDelete=[]),this.hooks.afterDelete.push(async e=>(await this.deletePartitionReferences(e),e)))}async validate(e){const t={original:h(e),isValid:!1,errors:[]},r=await this.schema.validate(e,{mutateOriginal:!1});return!0===r?t.isValid=!0:t.errors=r,t.data=e,t}validatePartitions(){if(!this.config.partitions)return;const e=this.config.partitions;if(0===Object.keys(e).length)return;const t=Object.keys(this.attributes||{});for(const[r,i]of Object.entries(e))if(i.fields)for(const e of Object.keys(i.fields))if(!this.fieldExistsInAttributes(e))throw new De(`Partition '${r}' uses field '${e}' which does not exist in resource attributes. Available fields: ${t.join(", ")}.`,{resourceName:this.name,partitionName:r,fieldName:e,availableFields:t,operation:"validatePartitions"})}fieldExistsInAttributes(e){if(e.startsWith("_"))return!0;if(!e.includes("."))return Object.keys(this.attributes||{}).includes(e);const t=e.split(".");let r=this.attributes||{};for(const e of t){if(!r||"object"!=typeof r||!(e in r))return!1;r=r[e]}return!0}applyPartitionRule(e,t){if(null==e)return e;let r=e;if("string"==typeof t&&t.includes("maxlength:")){const e=t.match(/maxlength:(\d+)/);if(e){const t=parseInt(e[1]);"string"==typeof r&&r.length>t&&(r=r.substring(0,t))}}if(t.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 e=new Date(r);isNaN(e.getTime())||(r=e.toISOString().split("T")[0])}return r}getResourceKey(e){return it("resource="+this.name,"data",`id=${e}`)}getPartitionKey({partitionName:e,id:t,data:r}){if(!this.config.partitions||!this.config.partitions[e])throw new De(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"getPartitionKey"});const i=this.config.partitions[e],s=[],n=Object.entries(i.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of n){const i=this.getNestedFieldValue(r,e),n=this.applyPartitionRule(i,t);if(null==n)return null;s.push(`${e}=${n}`)}if(0===s.length)return null;const o=t||r?.id;return o?it(`resource=${this.name}`,`partition=${e}`,...s,`id=${o}`):null}getNestedFieldValue(e,t){if(!t.includes("."))return e[t];const r=t.split(".");let i=e;for(const e of r){if(!i||"object"!=typeof i||!(e in i))return;i=i[e]}return i}calculateContentLength(e){return e?Buffer.isBuffer(e)?e.length:"string"==typeof e?Buffer.byteLength(e,"utf8"):"object"==typeof e?Buffer.byteLength(JSON.stringify(e),"utf8"):Buffer.byteLength(String(e),"utf8"):0}async insert({id:e,...t}){if(await this.exists(e))throw new Error(`Resource with id '${e}' already exists`);this.getResourceKey(e||"(auto)"),this.options.timestamps&&(t.createdAt=(new Date).toISOString(),t.updatedAt=(new Date).toISOString());const r={id:e,...this.applyDefaults(t)},i=await this.executeHooks("beforeInsert",r),s=Object.keys(i).filter(e=>!(e in r)||i[e]!==r[e]),n={};for(const e of s)n[e]=i[e];const{errors:o,isValid:a,data:c}=await this.validate(i);if(!a){const e=o&&o.length&&o[0].message?o[0].message:"Insert failed";throw new Se({bucket:this.client.config.bucket,resourceName:this.name,attributes:i,validation:o,message:e})}const{id:u,...l}=c;Object.assign(l,n);const h=u||e||this.idGenerator(),f=await this.schema.mapper(l);f._v=String(this.version);const d=re(this.behavior),{mappedData:p,body:g}=await d.handleInsert({resource:this,data:l,mappedData:f,originalData:r}),m=p,y=this.getResourceKey(h);let b;if(g&&""!==g){const[e,t]=await G(()=>Promise.resolve(JSON.parse(g)));e&&(b="application/json")}if("body-only"===this.behavior&&(!g||""===g))throw new Error(`[Resource.insert] Tentativa de gravar objeto sem body! Dados: id=${h}, resource=${this.name}`);const[w,v,O]=await G(()=>this.client.putObject({key:y,body:g,contentType:b,metadata:m}));if(!w){const e=v&&v.message?v.message:"";if(e.includes("metadata headers exceed")||e.includes("Insert failed")){const e=C(m),t=$({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:h}}),r=e-t;throw v.totalSize=e,v.limit=2047,v.effectiveLimit=t,v.excess=r,new Ae("metadata headers exceed",{resourceName:this.name,operation:"insert",id:h,totalSize:e,effectiveLimit:t,excess:r,suggestion:"Reduce metadata size or number of fields."})}throw je(v,{bucket:this.client.config.bucket,key:y,resourceName:this.name,operation:"insert",id:h})}let k=await this.composeFullObjectFromWrite({id:h,metadata:m,body:g,behavior:this.behavior});const S=await this.executeHooks("afterInsert",k);return this.emit("insert",{...k,$before:{...r},$after:{...S}}),S}async get(e){if(p(e))throw new Error("id cannot be an object");if(c(e))throw new Error("id cannot be empty");const t=this.getResourceKey(e),[r,i,s]=await G(()=>this.client.getObject(t));if(!r)throw je(i,{bucket:this.client.config.bucket,key:t,resourceName:this.name,operation:"get",id:e});if(0===s.ContentLength){const r=new Error(`No such key: ${t} [bucket:${this.client.config.bucket}]`);throw r.name="NoSuchKey",je(r,{bucket:this.client.config.bucket,key:t,resourceName:this.name,operation:"get",id:e})}const n=s.Metadata?._v||this.version,o="string"==typeof n&&n.startsWith("v")?n.slice(1):n,a=await this.getSchemaForVersion(o);let u=await a.unmapper(s.Metadata);const l=re(this.behavior);let h="";if(s.ContentLength>0){const[e,r,i]=await G(()=>this.client.getObject(t));h=e?await Ui(i.Body):""}const{metadata:f}=await l.handleGet({resource:this,metadata:u,body:h});let d=await this.composeFullObjectFromWrite({id:e,metadata:f,body:h,behavior:this.behavior});d._contentLength=s.ContentLength,d._lastModified=s.LastModified,d._hasContent=s.ContentLength>0,d._mimeType=s.ContentType||null,d._v=o,s.VersionId&&(d._versionId=s.VersionId),s.Expiration&&(d._expiresAt=s.Expiration),d._definitionHash=this.getDefinitionHash(),o!==this.version&&(d=await this.applyVersionMapping(d,o,this.version)),this.emit("get",d);return d}async exists(e){const t=this.getResourceKey(e),[r,i]=await G(()=>this.client.headObject(t));return r}async update(e,t){if(c(e))throw new Error("id cannot be empty");if(!await this.exists(e))throw new Error(`Resource with id '${e}' does not exist`);const r=await this.get(e),i=h(t);let s=h(r);for(const[e,t]of Object.entries(i))if(e.includes(".")){let r=s;const i=e.split(".");for(let e=0;e<i.length-1;e++)"object"==typeof r[i[e]]&&null!==r[i[e]]||(r[i[e]]={}),r=r[i[e]];r[i[i.length-1]]=h(t)}else"object"!=typeof t||null===t||Array.isArray(t)?s[e]=h(t):s[e]=o({},s[e],t);if(this.config.timestamps){const e=(new Date).toISOString();s.updatedAt=e,s.metadata||(s.metadata={}),s.metadata.updatedAt=e}const n=await this.executeHooks("beforeUpdate",h(s)),a={...r,...n,id:e},{isValid:u,errors:l,data:f}=await this.validate(h(a));if(!u)throw new Se({bucket:this.client.config.bucket,resourceName:this.name,attributes:n,validation:l,message:"validation: "+(l&&l.length?JSON.stringify(l):"unknown")});await this.schema.mapper(f);const d=re(this.behavior),p=await this.schema.mapper({...r,...n});p._v=String(this.version),await d.handleUpdate({resource:this,id:e,data:{...r,...n},mappedData:p,originalData:{...i,id:e}});const{id:g,...m}=f,y={...r,id:e},b={...m,id:e};await this.handlePartitionReferenceUpdates(y,b);const w=await this.schema.mapper(m);w._v=String(this.version);const v=re(this.behavior),{mappedData:O,body:k}=await v.handleUpdate({resource:this,id:e,data:m,mappedData:w,originalData:{...i,id:e}}),S=O,_=this.getResourceKey(e);let R,j=k;if(""===k&&"body-overflow"!==this.behavior){const[e,t,r]=await G(()=>this.client.getObject(_));if(e&&r.ContentLength>0){const e=Buffer.from(await r.Body.transformToByteArray()),t=e.toString(),[i,s]=await G(()=>Promise.resolve(JSON.parse(t)));i||(j=e,R=r.ContentType)}}let N=R;if(j&&""!==j&&!N){const[e,t]=await G(()=>Promise.resolve(JSON.parse(j)));e&&(N="application/json")}this.versioningEnabled&&r._v!==this.version&&await this.createHistoricalVersion(e,r);const[I,E]=await G(()=>this.client.putObject({key:_,body:j,contentType:N,metadata:S}));if(!I&&E&&E.message&&E.message.includes("metadata headers exceed")){const t=C(S),r=$({s3Limit:2047,systemConfig:{version:this.version,timestamps:this.config.timestamps,id:e}}),i=t-r;throw E.totalSize=t,E.limit=2047,E.effectiveLimit=r,E.excess=i,this.emit("exceedsLimit",{operation:"update",totalSize:t,limit:2047,effectiveLimit:r,excess:i,data:m}),new Ae("metadata headers exceed",{resourceName:this.name,operation:"update",id:e,totalSize:t,effectiveLimit:r,excess:i,suggestion:"Reduce metadata size or number of fields."})}if(!I)throw je(E,{bucket:this.client.config.bucket,key:_,resourceName:this.name,operation:"update",id:e});const A=await this.composeFullObjectFromWrite({id:e,metadata:S,body:j,behavior:this.behavior}),D=await this.executeHooks("afterUpdate",A);return this.emit("update",{...A,$before:{...r},$after:{...D}}),D}async delete(e){if(c(e))throw new Error("id cannot be empty");let t,r=null;const[i,s,n]=await G(()=>this.get(e));i?t=n:(t={id:e},r=s),await this.executeHooks("beforeDelete",t);const o=this.getResourceKey(e),[a,u,l]=await G(()=>this.client.deleteObject(o));if(this.emit("delete",{...t,$before:{...t},$after:null}),r)throw je(r,{bucket:this.client.config.bucket,key:o,resourceName:this.name,operation:"delete",id:e});if(!a)throw je(u,{key:o,resourceName:this.name,operation:"delete",id:e});return await this.executeHooks("afterDelete",t),l}async upsert({id:e,...t}){return await this.exists(e)?this.update(e,t):this.insert({id:e,...t})}async count({partition:e=null,partitionValues:t={}}={}){let r;if(e&&Object.keys(t).length>0){const i=this.config.partitions[e];if(!i)throw new De(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"count"});const s=[],n=Object.entries(i.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,r]of n){const i=t[e];if(null!=i){const t=this.applyPartitionRule(i,r);s.push(`${e}=${t}`)}}r=s.length>0?`resource=${this.name}/partition=${e}/${s.join("/")}`:`resource=${this.name}/partition=${e}`}else r=`resource=${this.name}/data`;const i=await this.client.count({prefix:r});return this.emit("count",i),i}async insertMany(e){const{results:t}=await i.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,t),this.observers.map(r=>r.emit("error",this.name,e,t))}).process(async e=>await this.insert(e));return this.emit("insertMany",e.length),t}async deleteMany(e){const t=n(e.map(e=>this.getResourceKey(e)),1e3);e.map(e=>this.getResourceKey(e));const{results:r}=await i.for(t).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,t),this.observers.map(r=>r.emit("error",this.name,e,t))}).process(async e=>{const t=await this.client.deleteObjects(e);return e.forEach(e=>{const t=e.split("/").find(e=>e.startsWith("id=")),r=t?t.replace("id=",""):null;r&&(this.emit("deleted",r),this.observers.map(e=>e.emit("deleted",this.name,r)))}),t});return this.emit("deleteMany",e.length),r}async deleteAll(){if(!1!==this.config.paranoid)throw new Ae("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 e=`resource=${this.name}/data`,t=await this.client.deleteAll({prefix:e});return this.emit("deleteAll",{version:this.version,prefix:e,deletedCount:t}),{deletedCount:t,version:this.version}}async deleteAllData(){if(!1!==this.config.paranoid)throw new Ae("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 e=`resource=${this.name}`,t=await this.client.deleteAll({prefix:e});return this.emit("deleteAllData",{resource:this.name,prefix:e,deletedCount:t}),{deletedCount:t,resource:this.name}}async listIds({partition:e=null,partitionValues:t={},limit:r,offset:i=0}={}){let s;if(e&&Object.keys(t).length>0){if(!this.config.partitions||!this.config.partitions[e])throw new De(`Partition '${e}' not found`,{resourceName:this.name,partitionName:e,operation:"listIds"});const r=this.config.partitions[e],i=[],n=Object.entries(r.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,r]of n){const s=t[e];if(null!=s){const t=this.applyPartitionRule(s,r);i.push(`${e}=${t}`)}}s=i.length>0?`resource=${this.name}/partition=${e}/${i.join("/")}`:`resource=${this.name}/partition=${e}`}else s=`resource=${this.name}/data`;const n=(await this.client.getKeysPage({prefix:s,offset:i,amount:r||1e3})).map(e=>{const t=e.split("/").find(e=>e.startsWith("id="));return t?t.replace("id=",""):null}).filter(Boolean);return this.emit("listIds",n.length),n}async list({partition:e=null,partitionValues:t={},limit:r,offset:i=0}={}){const[s,n,o]=await G(async()=>e?await this.listPartition({partition:e,partitionValues:t,limit:r,offset:i}):await this.listMain({limit:r,offset:i}));return s?o:this.handleListError(n,{partition:e,partitionValues:t})}async listMain({limit:e,offset:t=0}){const[r,i,s]=await G(()=>this.listIds({limit:e,offset:t}));if(!r)throw i;const n=await this.processListResults(s,"main");return this.emit("list",{count:n.length,errors:0}),n}async listPartition({partition:e,partitionValues:t,limit:r,offset:i=0}){if(!this.config.partitions?.[e])return this.emit("list",{partition:e,partitionValues:t,count:0,errors:0}),[];const s=this.config.partitions[e],n=this.buildPartitionPrefix(e,s,t),[o,a,c]=await G(()=>this.client.getAllKeys({prefix:n}));if(!o)throw a;const u=this.extractIdsFromKeys(c).slice(i),l=r?u.slice(0,r):u,h=await this.processPartitionResults(l,e,s,c);return this.emit("list",{partition:e,partitionValues:t,count:h.length,errors:0}),h}buildPartitionPrefix(e,t,r){const i=[],s=Object.entries(t.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of s){const s=r[e];if(null!=s){const r=this.applyPartitionRule(s,t);i.push(`${e}=${r}`)}}return i.length>0?`resource=${this.name}/partition=${e}/${i.join("/")}`:`resource=${this.name}/partition=${e}`}extractIdsFromKeys(e){return e.map(e=>{const t=e.split("/").find(e=>e.startsWith("id="));return t?t.replace("id=",""):null}).filter(Boolean)}async processListResults(e,t="main"){const{results:r,errors:s}=await i.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content))}).process(async e=>{const[r,i,s]=await G(()=>this.get(e));return r?s:this.handleResourceError(i,e,t)});return this.emit("list",{count:r.length,errors:0}),r}async processPartitionResults(e,t,r,s){const n=Object.entries(r.fields).sort(([e],[t])=>e.localeCompare(t)),{results:o,errors:a}=await i.for(e).withConcurrency(this.parallelism).handleError(async(e,t)=>{this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content))}).process(async e=>{const[r,i,o]=await G(async()=>{const r=this.extractPartitionValuesFromKey(e,s,n);return await this.getFromPartition({id:e,partitionName:t,partitionValues:r})});return r?o:this.handleResourceError(i,e,"partition")});return o.filter(e=>null!==e)}extractPartitionValuesFromKey(e,t,r){const i=t.find(t=>t.includes(`id=${e}`));if(!i)throw new De(`Partition key not found for ID ${e}`,{resourceName:this.name,id:e,operation:"extractPartitionValuesFromKey"});const s=i.split("/"),n={};for(const[e]of r){const t=s.find(t=>t.startsWith(`${e}=`));if(t){const r=t.replace(`${e}=`,"");n[e]=r}}return n}handleResourceError(e,t,r){if(e.message.includes("Cipher job failed")||e.message.includes("OperationError"))return{id:t,_decryptionFailed:!0,_error:e.message,..."partition"===r&&{_partition:r}};throw e}handleListError(e,{partition:t,partitionValues:r}){return e.message.includes("Partition '")&&e.message.includes("' not found"),this.emit("list",{partition:t,partitionValues:r,count:0,errors:1}),[]}async getMany(e){const{results:t,errors:r}=await i.for(e).withConcurrency(this.client.parallelism).handleError(async(e,t)=>(this.emit("error",e,content),this.observers.map(t=>t.emit("error",this.name,e,content)),{id:t,_error:e.message,_decryptionFailed:e.message.includes("Cipher job failed")||e.message.includes("OperationError")})).process(async e=>{const[t,r,i]=await G(()=>this.get(e));if(t)return i;if(r.message.includes("Cipher job failed")||r.message.includes("OperationError"))return{id:e,_decryptionFailed:!0,_error:r.message};throw r});return this.emit("getMany",e.length),t}async getAll(){const[e,t,r]=await G(()=>this.listIds());if(!e)throw t;const i=[];for(const e of r){const[t,r,s]=await G(()=>this.get(e));t&&i.push(s)}return i}async page({offset:e=0,size:t=100,partition:r=null,partitionValues:i={},skipCount:s=!1}={}){const[n,o,a]=await G(async()=>{let n=null,o=null;if(!s){const[e,s,a]=await G(()=>this.count({partition:r,partitionValues:i}));e?(n=a,o=Math.ceil(n/t)):(n=null,o=null)}const a=Math.floor(e/t);let c=[];if(t<=0)c=[];else{const[s,n,o]=await G(()=>this.list({partition:r,partitionValues:i,limit:t,offset:e}));c=s?o:[]}const u={items:c,totalItems:n,page:a,pageSize:t,totalPages:o,hasMore:c.length===t&&e+t<(n||1/0),_debug:{requestedSize:t,requestedOffset:e,actualItemsReturned:c.length,skipCount:s,hasTotalItems:null!==n}};return this.emit("page",u),u});return n?a:{items:[],totalItems:null,page:Math.floor(e/t),pageSize:t,totalPages:null,_debug:{requestedSize:t,requestedOffset:e,actualItemsReturned:0,skipCount:s,hasTotalItems:!1,error:o.message}}}readable(){return new $i({resource:this}).build()}writable(){return new Mi({resource:this}).build()}async setContent({id:e,buffer:t,contentType:r="application/octet-stream"}){const[i,s,n]=await G(()=>this.get(e));if(!i||!n)throw new Ae(`Resource with id '${e}' not found`,{resourceName:this.name,id:e,operation:"setContent"});const o={...n,_hasContent:!0,_contentLength:t.length,_mimeType:r},a=await this.schema.mapper(o),[c,u]=await G(()=>this.client.putObject({key:this.getResourceKey(e),metadata:a,body:t,contentType:r}));if(!c)throw u;return this.emit("setContent",{id:e,contentType:r,contentLength:t.length}),o}async content(e){const t=this.getResourceKey(e),[r,i,s]=await G(()=>this.client.getObject(t));if(!r){if("NoSuchKey"===i.name)return{buffer:null,contentType:null};throw i}const n=Buffer.from(await s.Body.transformToByteArray()),o=s.ContentType||null;return this.emit("content",e,n.length,o),{buffer:n,contentType:o}}async hasContent(e){const t=this.getResourceKey(e),[r,i,s]=await G(()=>this.client.headObject(t));return!!r&&s.ContentLength>0}async deleteContent(e){const t=this.getResourceKey(e),[r,i,s]=await G(()=>this.client.headObject(t));if(!r)throw i;const n=s.Metadata||{},[o,a,c]=await G(()=>this.client.putObject({key:t,body:"",metadata:n}));if(!o)throw a;return this.emit("deleteContent",e),c}getDefinitionHash(){const e={attributes:this.attributes,behavior:this.behavior},t=b(e);return`sha256:${y("sha256").update(t).digest("hex")}`}extractVersionFromKey(e){const t=e.split("/").find(e=>e.startsWith("v="));return t?t.replace("v=",""):null}async getSchemaForVersion(e){if(e===this.version)return this.schema;const[t,r,i]=await G(()=>Promise.resolve(new rs({name:this.name,attributes:this.attributes,passphrase:this.passphrase,version:e,options:{...this.config,autoDecrypt:!0,autoEncrypt:!0}})));return t?i:this.schema}async createPartitionReferences(e){const t=this.config.partitions;if(t&&0!==Object.keys(t).length)for(const[r,i]of Object.entries(t)){const t=this.getPartitionKey({partitionName:r,id:e.id,data:e});if(t){const e={_v:String(this.version)};await this.client.putObject({key:t,metadata:e,body:"",contentType:void 0})}}}async deletePartitionReferences(e){const t=this.config.partitions;if(!t||0===Object.keys(t).length)return;const r=[];for(const[i,s]of Object.entries(t)){const t=this.getPartitionKey({partitionName:i,id:e.id,data:e});t&&r.push(t)}if(r.length>0){const[e,t]=await G(()=>this.client.deleteObjects(r))}}async query(e={},{limit:t=100,offset:r=0,partition:i=null,partitionValues:s={}}={}){if(0===Object.keys(e).length)return await this.list({partition:i,partitionValues:s,limit:t,offset:r});const n=[];let o=r;const a=Math.min(t,50);for(;n.length<t;){const t=await this.list({partition:i,partitionValues:s,limit:a,offset:o});if(0===t.length)break;const r=t.filter(t=>Object.entries(e).every(([e,r])=>t[e]===r));if(n.push(...r),o+=a,t.length<a)break}return n.slice(0,t)}async handlePartitionReferenceUpdates(e,t){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 G(()=>this.handlePartitionReferenceUpdate(i,s,e,t))}const i=t.id||e.id;for(const[e,s]of Object.entries(r)){const r=`resource=${this.name}/partition=${e}`;let s=[];const[n,o,a]=await G(()=>this.client.getAllKeys({prefix:r}));if(!n)continue;s=a;const c=this.getPartitionKey({partitionName:e,id:i,data:t});for(const e of s)if(e.endsWith(`/id=${i}`)&&e!==c){const[t,r]=await G(()=>this.client.deleteObject(e))}}}async handlePartitionReferenceUpdate(e,t,r,i){const s=i.id||r.id,n=this.getPartitionKey({partitionName:e,id:s,data:r}),o=this.getPartitionKey({partitionName:e,id:s,data:i});if(n!==o){if(n){const[e,t]=await G(async()=>{await this.client.deleteObject(n)})}if(o){const[e,t]=await G(async()=>{const e={_v:String(this.version)};await this.client.putObject({key:o,metadata:e,body:"",contentType:void 0})})}}else if(o){const[e,t]=await G(async()=>{const e={_v:String(this.version)};await this.client.putObject({key:o,metadata:e,body:"",contentType:void 0})})}}async updatePartitionReferences(e){const t=this.config.partitions;if(t&&0!==Object.keys(t).length)for(const[r,i]of Object.entries(t)){if(!i||!i.fields||"object"!=typeof i.fields)continue;const t=this.getPartitionKey({partitionName:r,id:e.id,data:e});if(t){const e={_v:String(this.version)},[r,i]=await G(async()=>{await this.client.putObject({key:t,metadata:e,body:"",contentType:void 0})})}}}async getFromPartition({id:e,partitionName:t,partitionValues:r={}}){if(!this.config.partitions||!this.config.partitions[t])throw new De(`Partition '${t}' not found`,{resourceName:this.name,partitionName:t,operation:"getFromPartition"});const i=this.config.partitions[t],s=[],n=Object.entries(i.fields).sort(([e],[t])=>e.localeCompare(t));for(const[e,t]of n){const i=r[e];if(null!=i){const r=this.applyPartitionRule(i,t);s.push(`${e}=${r}`)}}if(0===s.length)throw new De(`No partition values provided for partition '${t}'`,{resourceName:this.name,partitionName:t,operation:"getFromPartition"});const o=it(`resource=${this.name}`,`partition=${t}`,...s,`id=${e}`),[a,c]=await G(async()=>{await this.client.headObject(o)});if(!a)throw new Ae(`Resource with id '${e}' not found in partition '${t}'`,{resourceName:this.name,id:e,partitionName:t,operation:"getFromPartition"});const u=await this.get(e);return u._partition=t,u._partitionValues=r,this.emit("getFromPartition",u),u}async createHistoricalVersion(e,t){const r=it(`resource=${this.name}`,"historical",`id=${e}`),i={...t,_v:t._v||this.version,_historicalTimestamp:(new Date).toISOString()},s=await this.schema.mapper(i),n=re(this.behavior),{mappedData:o,body:a}=await n.handleInsert({resource:this,data:i,mappedData:s}),c={...o,_v:t._v||this.version,_historicalTimestamp:i._historicalTimestamp};let u;if(a&&""!==a){const[e,t]=await G(()=>Promise.resolve(JSON.parse(a)));e&&(u="application/json")}await this.client.putObject({key:r,metadata:c,body:a,contentType:u})}async applyVersionMapping(e,t,r){if(t===r)return e;return{...e,_v:r,_originalVersion:t,_versionMapped:!0}}async composeFullObjectFromWrite({id:e,metadata:t,body:r,behavior:i}){const s={};t&&"true"===t.$truncated&&(s.$truncated="true"),t&&"true"===t.$overflow&&(s.$overflow="true");let n={};const[o,a,c]=await G(()=>this.schema.unmapper(t));n=o?c:t;const u=e=>{if(!e||"object"!=typeof e)return e;const t={};for(const[r,i]of Object.entries(e))r.startsWith("_")||(t[r]=i);return t},l=e=>{if("object"==typeof e&&null!==e)return e;if("string"==typeof e){if("[object Object]"===e)return{};if(e.startsWith("{")||e.startsWith("[")){const[t,r,i]=J(()=>JSON.parse(e));return t?i:e}return e}return e};if("body-overflow"===i){const i=t&&"true"===t.$overflow;let s={};if(i&&r){const[e,t,i]=await G(()=>Promise.resolve(JSON.parse(r)));if(e){const[e,t,r]=await G(()=>this.schema.unmapper(i));s=e?r:{}}}const o={...n,...s,id:e};Object.keys(o).forEach(e=>{o[e]=l(o[e])});const a=u(o);return i&&(a.$overflow="true"),a}if("body-only"===i){const[i,s,n]=await G(()=>Promise.resolve(r?JSON.parse(r):{}));let o=this.schema.map;if(t&&t._map){const[e,r,i]=await G(()=>Promise.resolve("string"==typeof t._map?JSON.parse(t._map):t._map));o=e?i:this.schema.map}const[a,c,u]=await G(()=>this.schema.unmapper(n,o)),h=a?{...u,id:e}:{id:e};return Object.keys(h).forEach(e=>{h[e]=l(h[e])}),h}const h={...n,id:e};Object.keys(h).forEach(e=>{h[e]=l(h[e])});const f=u(h);return s.$truncated&&(f.$truncated=s.$truncated),s.$overflow&&(f.$overflow=s.$overflow),f}emit(e,...t){return super.emit(e,...t)}async replace(e,t){await this.delete(e),await new Promise(e=>setTimeout(e,100));const r=Date.now();for(;Date.now()-r<5e3;){if(!await this.exists(e))break;await new Promise(e=>setTimeout(e,50))}try{return await this.insert({...t,id:e})}catch(r){if(r&&r.message&&r.message.includes("already exists")){return await this.update(e,t)}throw r}}_initMiddleware(){this._middlewares=new Map,this._middlewareMethods=["get","list","listIds","getAll","count","page","insert","update","delete","deleteMany","exists","getMany"];for(const e of this._middlewareMethods)this._middlewares.set(e,[]),this[`_original_${e}`]||(this[`_original_${e}`]=this[e].bind(this),this[e]=async(...t)=>{const r={resource:this,args:t,method:e};let i=-1;const s=this._middlewares.get(e),n=async t=>{if(t<=i)throw new Error("next() called multiple times");return i=t,t<s.length?await s[t](r,()=>n(t+1)):await this[`_original_${e}`](...r.args)};return await n(0)})}useMiddleware(e,t){if(this._middlewares||this._initMiddleware(),!this._middlewares.has(e))throw new Ae(`No such method for middleware: ${e}`,{operation:"useMiddleware",method:e});this._middlewares.get(e).push(t)}applyDefaults(e){const t={...e};for(const[e,r]of Object.entries(this.attributes))if(void 0===t[e]&&"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)),t[e]=s}}return t}}class ss extends Be{constructor(e){super(),this.version="1",this.s3dbVersion=(()=>{const[e,t,r]=G(()=>"7.0.2");return e?r:"latest"})(),this.resources={},this.savedMetadata=null,this.options=e,this.verbose=e.verbose||!1,this.parallelism=parseInt(e.parallelism+"")||10,this.plugins=e.plugins||[],this.pluginList=e.plugins||[],this.cache=e.cache,this.passphrase=e.passphrase||"secret",this.versioningEnabled=e.versioningEnabled||!1;let t=e.connectionString;if(!t&&(e.bucket||e.accessKeyId||e.secretAccessKey)){const{bucket:r,region:i,accessKeyId:s,secretAccessKey:n,endpoint:o,forcePathStyle:a}=e;if(o){const e=new URL(o);s&&(e.username=encodeURIComponent(s)),n&&(e.password=encodeURIComponent(n)),e.pathname=`/${r||"s3db"}`,a&&e.searchParams.set("forcePathStyle","true"),t=e.toString()}else if(s&&n){const e=new URLSearchParams;e.set("region",i||"us-east-1"),a&&e.set("forcePathStyle","true"),t=`s3://${encodeURIComponent(s)}:${encodeURIComponent(n)}@${r||"s3db"}?${e.toString()}`}}this.client=e.client||new Yi({verbose:this.verbose,parallelism:this.parallelism,connectionString:t}),this.bucket=this.client.bucket,this.keyPrefix=this.client.keyPrefix,this._exitListenerRegistered||(this._exitListenerRegistered=!0,process.on("exit",async()=>{if(this.isConnected())try{await this.disconnect()}catch(e){}}))}async connect(){await this.startPlugins();let e=null;if(await this.client.exists("s3db.json")){const t=await this.client.getObject("s3db.json");e=JSON.parse(await Ui(t?.Body))}else e=this.blankMetadataStructure(),await this.uploadMetadataFile();this.savedMetadata=e;const t=this.detectDefinitionChanges(e);for(const[t,r]of Object.entries(e.resources||{})){const e=r.currentVersion||"v0",i=r.versions?.[e];i&&(this.resources[t]=new is({name:t,client:this.client,database:this,version:e,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}))}t.length>0&&this.emit("resourceDefinitionsChanged",{changes:t,metadata:this.savedMetadata}),this.emit("connected",new Date)}detectDefinitionChanges(e){const t=[];for(const[r,i]of Object.entries(this.resources)){const s=this.generateDefinitionHash(i.export()),n=e.resources?.[r];if(n){const e=n.currentVersion||"v0",i=n.versions?.[e],o=i?.hash;o!==s&&t.push({type:"changed",resourceName:r,currentHash:s,savedHash:o,fromVersion:e,toVersion:this.getNextVersion(n.versions)})}else t.push({type:"new",resourceName:r,currentHash:s,savedHash:null})}for(const[r,i]of Object.entries(e.resources||{}))if(!this.resources[r]){const e=i.currentVersion||"v0",s=i.versions?.[e];t.push({type:"deleted",resourceName:r,currentHash:null,savedHash:s?.hash,deletedVersion:e})}return t}generateDefinitionHash(e,t=void 0){const r={...e.attributes};e.timestamps&&(delete r.createdAt,delete r.updatedAt);const i={attributes:r,behavior:t||e.behavior||"user-managed",partitions:e.partitions||{}},s=b(i);return`sha256:${y("sha256").update(s).digest("hex")}`}getNextVersion(e={}){const t=Object.keys(e).filter(e=>e.startsWith("v")).map(e=>parseInt(e.substring(1))).filter(e=>!isNaN(e));return`v${(t.length>0?Math.max(...t):-1)+1}`}async startPlugins(){const e=this;if(!c(this.pluginList)){const t=this.pluginList.map(e=>g(e)?new e(this):e),r=t.map(async t=>{t.beforeSetup&&await t.beforeSetup(),await t.setup(e),t.afterSetup&&await t.afterSetup()});await Promise.all(r);const i=t.map(async e=>{e.beforeStart&&await e.beforeStart(),await e.start(),e.afterStart&&await e.afterStart()});await Promise.all(i)}}async usePlugin(e,t=null){const r=t||e.constructor.name.replace("Plugin","").toLowerCase();return this.plugins[r]=e,this.isConnected()&&(await e.setup(this),await e.start()),e}async uploadMetadataFile(){const e={version:this.version,s3dbVersion:this.s3dbVersion,lastUpdated:(new Date).toISOString(),resources:{}};Object.entries(this.resources).forEach(([t,r])=>{const i=r.export(),s=this.generateDefinitionHash(i),n=this.savedMetadata?.resources?.[t],o=n?.currentVersion||"v0",a=n?.versions?.[o];let c,u;a&&a.hash===s?(c=o,u=!1):(c=this.getNextVersion(n?.versions),u=!0),e.resources[t]={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:u?(new Date).toISOString():a?.createdAt}}},r.version!==c&&(r.version=c,r.emit("versionUpdated",{oldVersion:o,newVersion:c}))}),await this.client.putObject({key:"s3db.json",body:JSON.stringify(e,null,2),contentType:"application/json"}),this.savedMetadata=e,this.emit("metadataUploaded",e)}blankMetadataStructure(){return{version:"1",s3dbVersion:this.s3dbVersion,resources:{}}}resourceExists(e){return!!this.resources[e]}resourceExistsWithSameHash({name:e,attributes:t,behavior:r="user-managed",partitions:i={},options:s={}}){if(!this.resources[e])return{exists:!1,sameHash:!1,hash:null};const n=this.resources[e],o=this.generateDefinitionHash(n.export()),a=new is({name:e,attributes:t,behavior:r,partitions:i,client:this.client,version:n.version,passphrase:this.passphrase,versioningEnabled:this.versioningEnabled,...s}),c=this.generateDefinitionHash(a.export());return{exists:!0,sameHash:o===c,hash:c,existingHash:o}}async createResource({name:e,attributes:t,behavior:r="user-managed",hooks:i,...s}){if(this.resources[e]){const n=this.resources[e];if(Object.assign(n.config,{cache:this.cache,...s}),r&&(n.behavior=r),n.versioningEnabled=this.versioningEnabled,n.updateAttributes(t),i)for(const[e,t]of Object.entries(i))if(Array.isArray(t)&&n.hooks[e])for(const r of t)"function"==typeof r&&n.hooks[e].push(r.bind(n));const o=this.generateDefinitionHash(n.export(),n.behavior),a=this.savedMetadata?.resources?.[e],c=a?.currentVersion||"v0",u=a?.versions?.[c];return u&&u.hash===o||await this.uploadMetadataFile(),this.emit("s3db.resourceUpdated",e),n}const n=this.savedMetadata?.resources?.[e],o=n?.currentVersion||"v0",a=new is({name:e,client:this.client,version:void 0!==s.version?s.version:o,attributes:t,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 a.database=this,this.resources[e]=a,await this.uploadMetadataFile(),this.emit("s3db.resourceCreated",e),a}resource(e){return this.resources[e]?this.resources[e]:Promise.reject(`resource ${e} does not exist`)}async listResources(){return Object.keys(this.resources).map(e=>({name:e}))}async getResource(e){if(!this.resources[e])throw new be({bucket:this.client.config.bucket,resourceName:e,id:e});return this.resources[e]}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 e of this.pluginList)e&&"function"==typeof e.removeAllListeners&&e.removeAllListeners();const e=this.pluginList.map(async e=>{try{e&&"function"==typeof e.stop&&await e.stop()}catch(e){}});await Promise.all(e)}if(this.resources&&Object.keys(this.resources).length>0){for(const[e,t]of Object.entries(this.resources))try{t&&"function"==typeof t.removeAllListeners&&t.removeAllListeners(),t._pluginWrappers&&t._pluginWrappers.clear(),t._pluginMiddlewares&&(t._pluginMiddlewares={}),t.observers&&Array.isArray(t.observers)&&(t.observers=[])}catch(e){}Object.keys(this.resources).forEach(e=>delete this.resources[e])}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(e){}}}class ns extends ss{}function os(e){return"string"==typeof e?e.trim().toLowerCase():e}const as={s3db:class extends Hi{constructor(e={},t=[],r=null){super(e),this.instanceId=Math.random().toString(36).slice(2,10),this.client=r,this.connectionString=e.connectionString;let i=t;if(t)if(Array.isArray(t)){i={};for(const e of t)"string"==typeof e&&(i[os(e)]=e)}else"string"==typeof t&&(i[os(t)]=t);else i={};this.resourcesMap=this._normalizeResources(i)}_normalizeResources(e){if(!e)return{};if(Array.isArray(e)){const t={};for(const r of e)"string"==typeof r?t[os(r)]=r:Array.isArray(r)&&"string"==typeof r[0]?t[os(r[0])]=r:"object"==typeof r&&r.resource&&(t[os(r.resource)]={...r});return t}if("object"==typeof e){const t={};for(const[r,i]of Object.entries(e)){const e=os(r);"string"==typeof i?t[e]=i:Array.isArray(i)?t[e]=i.map(e=>"string"==typeof e||"function"==typeof e?e:"object"==typeof e&&e.resource?{...e}:e):"function"==typeof i?t[e]=i:"object"==typeof i&&i.resource&&(t[e]={...i})}return t}if("function"==typeof e)return e;if("string"==typeof e){return{[os(e)]:e}}return{}}validateConfig(){const e=[];return this.client||this.connectionString||e.push("You must provide a client or a connectionString"),(!this.resourcesMap||"object"==typeof this.resourcesMap&&0===Object.keys(this.resourcesMap).length)&&e.push("You must provide a resources map or array"),{isValid:0===e.length,errors:e}}async initialize(e){try{if(await super.initialize(e),this.client)this.targetDatabase=this.client;else{if(!this.connectionString)throw new Error("S3dbReplicator: No client or connectionString provided");{const e={connectionString:this.connectionString,region:this.region,keyPrefix:this.keyPrefix,verbose:this.config.verbose||!1};this.targetDatabase=new ns(e),await this.targetDatabase.connect()}}this.emit("connected",{replicator:this.name,target:this.connectionString||"client-provided"})}catch(e){throw e}}async replicate({resource:e,operation:t,data:r,id:i}){const s=os(e),n=this._resolveDestResource(s,r),o=this._getDestResourceObj(n),a=this._applyTransformer(s,r);let c;if("insert"===t)c=await o.insert(a);else if("update"===t)c=await o.update(i,a);else{if("delete"!==t)throw new Error(`Invalid operation: ${t}. Supported operations are: insert, update, delete`);c=await o.delete(i)}return c}_applyTransformer(e,t){const r=os(e),i=this.resourcesMap[r];let s;return i?(Array.isArray(i)&&"function"==typeof i[1]?s=i[1](t):"function"==typeof i?s=i(t):"object"==typeof i?"function"==typeof i.transform?s=i.transform(t):"function"==typeof i.transformer&&(s=i.transformer(t)):s=t,s&&t&&t.id&&!s.id&&(s.id=t.id),!s&&t&&(s=t),s):t}_resolveDestResource(e,t){const r=os(e),i=this.resourcesMap[r];if(!i)return e;if(Array.isArray(i)){if("string"==typeof i[0])return i[0];if("object"==typeof i[0]&&i[0].resource)return i[0].resource;if("function"==typeof i[0])return e}return"string"==typeof i?i:"function"==typeof i?e:"object"==typeof i&&i.resource?i.resource:e}_getDestResourceObj(e){if(!this.client||!this.client.resources)return null;const t=Object.keys(this.client.resources),r=os(e),i=t.find(e=>os(e)===r);if(!i)throw new Error(`[S3dbReplicator] Destination resource not found: ${e}. Available: ${t.join(", ")}`);return this.client.resources[i]}async replicateBatch(e,t){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const r=[],i=[];for(const s of t){const[t,n,o]=await G(()=>this.replicate({resource:e,operation:s.operation,id:s.id,data:s.data,beforeData:s.beforeData}));t?r.push(o):i.push({id:s.id,error:n.message})}return this.emit("batch_replicated",{replicator:this.name,resourceName:e,total:t.length,successful:r.length,errors:i.length}),{success:0===i.length,results:r,errors:i,total:t.length}}async testConnection(){const[e,t]=await G(async()=>(this.targetDatabase||await this.initialize(this.database),await this.targetDatabase.listResources(),!0));return!!e||(this.emit("connection_error",{replicator:this.name,error:t.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(e,t){const r=os(e),i=this.resourcesMap[r];if(!i)return!1;if(!t)return!0;if(Array.isArray(i)){for(const e of i)if("object"==typeof e&&e.resource){if(!e.actions||!Array.isArray(e.actions))return!0;if(e.actions.includes(t))return!0}else if("string"==typeof e||"function"==typeof e)return!0;return!1}return"object"==typeof i&&i.resource?!i.actions||!Array.isArray(i.actions)||i.actions.includes(t):"string"==typeof i||"function"==typeof i}},sqs:class extends Hi{constructor(e={},t=[],r=null){if(super(e),this.resources=t,this.client=r,this.queueUrl=e.queueUrl,this.queues=e.queues||{},this.defaultQueue=e.defaultQueue||e.defaultQueueUrl||e.queueUrlDefault,this.region=e.region||"us-east-1",this.sqsClient=r||null,this.messageGroupId=e.messageGroupId,this.deduplicationId=e.deduplicationId,t&&"object"==typeof t)for(const[e,r]of Object.entries(t))r.queueUrl&&(this.queues[e]=r.queueUrl)}validateConfig(){const e=[];return this.queueUrl||0!==Object.keys(this.queues).length||this.defaultQueue||this.resourceQueueMap||e.push("Either queueUrl, queues object, defaultQueue, or resourceQueueMap must be provided"),{isValid:0===e.length,errors:e}}getQueueUrlsForResource(e){if(this.resourceQueueMap&&this.resourceQueueMap[e])return this.resourceQueueMap[e];if(this.queues[e])return[this.queues[e]];if(this.queueUrl)return[this.queueUrl];if(this.defaultQueue)return[this.defaultQueue];throw new Error(`No queue URL found for resource '${e}'`)}_applyTransformer(e,t){const r=this.resources[e];let i=t;return r?("function"==typeof r.transform?i=r.transform(t):"function"==typeof r.transformer&&(i=r.transformer(t)),i||t):t}createMessage(e,t,r,i,s=null){const n={resource:e,action:t,timestamp:(new Date).toISOString(),source:"s3db-replicator"};switch(t){case"insert":case"delete":default:return{...n,data:r};case"update":return{...n,before:s,data:r}}}async initialize(e,t){if(await super.initialize(e),!this.sqsClient){const[e,r,i]=await G(()=>import("@aws-sdk/client-sqs"));if(!e)throw this.emit("initialization_error",{replicator:this.name,error:r.message}),r;const{SQSClient:s}=i;this.sqsClient=t||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(e,t,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const[n,o,a]=await G(async()=>{const{SendMessageCommand:n}=await import("@aws-sdk/client-sqs"),o=this.getQueueUrlsForResource(e),a=this._applyTransformer(e,r),c=this.createMessage(e,t,a,i,s),u=[];for(const r of o){const s=new n({QueueUrl:r,MessageBody:JSON.stringify(c),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${e}:${t}:${i}`:void 0}),o=await this.sqsClient.send(s);u.push({queueUrl:r,messageId:o.MessageId}),this.emit("replicated",{replicator:this.name,resource:e,operation:t,id:i,queueUrl:r,messageId:o.MessageId,success:!0})}return{success:!0,results:u}});return n?a:(this.emit("replicator_error",{replicator:this.name,resource:e,operation:t,id:i,error:o.message}),{success:!1,error:o.message})}async replicateBatch(e,t){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};const[r,i,s]=await G(async()=>{const{SendMessageBatchCommand:r}=await import("@aws-sdk/client-sqs"),i=this.getQueueUrlsForResource(e),s=[];for(let e=0;e<t.length;e+=10)s.push(t.slice(e,e+10));const n=[],o=[];for(const t of s){const[s,a]=await G(async()=>{const s=t.map((t,r)=>({Id:`${t.id}-${r}`,MessageBody:JSON.stringify(this.createMessage(e,t.operation,t.data,t.id,t.beforeData)),MessageGroupId:this.messageGroupId,MessageDeduplicationId:this.deduplicationId?`${e}:${t.operation}:${t.id}`:void 0})),o=new r({QueueUrl:i[0],Entries:s}),a=await this.sqsClient.send(o);n.push(a)});if(!s&&(o.push({batch:t.length,error:a.message}),a.message&&(a.message.includes("Batch error")||a.message.includes("Connection")||a.message.includes("Network"))))throw a}return this.emit("batch_replicated",{replicator:this.name,resource:e,queueUrl:i[0],total:t.length,successful:n.length,errors:o.length}),{success:0===o.length,results:n,errors:o,total:t.length,queueUrl:i[0]}});if(r)return s;const n=i?.message||i||"Unknown error";return this.emit("batch_replicator_error",{replicator:this.name,resource:e,error:n}),{success:!1,error:n}}async testConnection(){const[e,t]=await G(async()=>{this.sqsClient||await this.initialize(this.database);const{GetQueueAttributesCommand:e}=await import("@aws-sdk/client-sqs"),t=new e({QueueUrl:this.queueUrl,AttributeNames:["QueueArn"]});return await this.sqsClient.send(t),!0});return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async getStatus(){return{...await super.getStatus(),connected:!!this.sqsClient,queueUrl:this.queueUrl,region:this.region,resources:this.resources,totalreplicators:this.listenerCount("replicated"),totalErrors:this.listenerCount("replicator_error")}}async cleanup(){this.sqsClient&&this.sqsClient.destroy(),await super.cleanup()}shouldReplicateResource(e){return this.resourceQueueMap&&Object.keys(this.resourceQueueMap).includes(e)||this.queues&&Object.keys(this.queues).includes(e)||!(!this.defaultQueue&&!this.queueUrl)||this.resources&&Object.keys(this.resources).includes(e)||!1}},bigquery:class extends Hi{constructor(e={},t={}){super(e),this.projectId=e.projectId,this.datasetId=e.datasetId,this.bigqueryClient=null,this.credentials=e.credentials,this.location=e.location||"US",this.logTable=e.logTable,this.resources=this.parseResourcesConfig(t)}parseResourcesConfig(e){const t={};for(const[r,i]of Object.entries(e))"string"==typeof i?t[r]=[{table:i,actions:["insert"]}]:Array.isArray(i)?t[r]=i.map(e=>"string"==typeof e?{table:e,actions:["insert"]}:{table:e.table,actions:e.actions||["insert"]}):"object"==typeof i&&(t[r]=[{table:i.table,actions:i.actions||["insert"]}]);return t}validateConfig(){const e=[];this.projectId||e.push("projectId is required"),this.datasetId||e.push("datasetId is required"),0===Object.keys(this.resources).length&&e.push("At least one resource must be configured");for(const[t,r]of Object.entries(this.resources))for(const i of r){i.table||e.push(`Table name is required for resource '${t}'`),Array.isArray(i.actions)&&0!==i.actions.length||e.push(`Actions array is required for resource '${t}'`);const r=["insert","update","delete"],s=i.actions.filter(e=>!r.includes(e));s.length>0&&e.push(`Invalid actions for resource '${t}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}async initialize(e){await super.initialize(e);const[t,r,i]=await G(()=>import("@google-cloud/bigquery"));if(!t)throw 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(e){return this.resources.hasOwnProperty(e)}shouldReplicateAction(e,t){return!!this.resources[e]&&this.resources[e].some(e=>e.actions.includes(t))}getTablesForResource(e,t){return this.resources[e]?this.resources[e].filter(e=>e.actions.includes(t)).map(e=>e.table):[]}async replicate(e,t,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(e,t))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(e,t);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const o=[],a=[],[c,u,l]=await G(async()=>{const s=this.bigqueryClient.dataset(this.datasetId);for(const e of n){const[n,c]=await G(async()=>{const n=s.table(e);let a;if("insert"===t){const e={...r};a=await n.insert([e])}else if("update"===t){const t=Object.keys(r).filter(e=>"id"!==e),s=t.map(e=>`${e}=@${e}`).join(", "),n={id:i};t.forEach(e=>{n[e]=r[e]});const o=`UPDATE \`${this.projectId}.${this.datasetId}.${e}\` SET ${s} WHERE id=@id`,[c]=await this.bigqueryClient.createQueryJob({query:o,params:n});await c.getQueryResults(),a=[c]}else{if("delete"!==t)throw new Error(`Unsupported operation: ${t}`);{const t=`DELETE FROM \`${this.projectId}.${this.datasetId}.${e}\` WHERE id=@id`,[r]=await this.bigqueryClient.createQueryJob({query:t,params:{id:i}});await r.getQueryResults(),a=[r]}}o.push({table:e,success:!0,jobId:a[0]?.id})});n||a.push({table:e,error:c.message})}if(this.logTable){const[n,o]=await G(async()=>{const n=s.table(this.logTable);await n.insert([{resource_name:e,operation:t,record_id:i,data:JSON.stringify(r),timestamp:(new Date).toISOString(),source:"s3db-replicator"}])})}const c=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:e,operation:t,id:i,tables:n,results:o,errors:a,success:c}),{success:c,results:o,errors:a,tables:n}});return c?l:(this.emit("replicator_error",{replicator:this.name,resourceName:e,operation:t,id:i,error:u.message}),{success:!1,error:u.message})}async replicateBatch(e,t){const r=[],i=[];for(const s of t){const[t,n,o]=await G(()=>this.replicate(e,s.operation,s.data,s.id,s.beforeData));t?r.push(o):i.push({id:s.id,error:n.message})}return{success:0===i.length,results:r,errors:i}}async testConnection(){const[e,t]=await G(async()=>{this.bigqueryClient||await this.initialize();const e=this.bigqueryClient.dataset(this.datasetId);return await e.getMetadata(),!0});return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async cleanup(){}getStatus(){return{...super.getStatus(),projectId:this.projectId,datasetId:this.datasetId,resources:this.resources,logTable:this.logTable}}},postgres:class extends Hi{constructor(e={},t={}){super(e),this.connectionString=e.connectionString,this.host=e.host,this.port=e.port||5432,this.database=e.database,this.user=e.user,this.password=e.password,this.client=null,this.ssl=e.ssl,this.logTable=e.logTable,this.resources=this.parseResourcesConfig(t)}parseResourcesConfig(e){const t={};for(const[r,i]of Object.entries(e))"string"==typeof i?t[r]=[{table:i,actions:["insert"]}]:Array.isArray(i)?t[r]=i.map(e=>"string"==typeof e?{table:e,actions:["insert"]}:{table:e.table,actions:e.actions||["insert"]}):"object"==typeof i&&(t[r]=[{table:i.table,actions:i.actions||["insert"]}]);return t}validateConfig(){const e=[];this.connectionString||this.host&&this.database||e.push("Either connectionString or host+database must be provided"),0===Object.keys(this.resources).length&&e.push("At least one resource must be configured");for(const[t,r]of Object.entries(this.resources))for(const i of r){i.table||e.push(`Table name is required for resource '${t}'`),Array.isArray(i.actions)&&0!==i.actions.length||e.push(`Actions array is required for resource '${t}'`);const r=["insert","update","delete"],s=i.actions.filter(e=>!r.includes(e));s.length>0&&e.push(`Invalid actions for resource '${t}': ${s.join(", ")}. Valid actions: ${r.join(", ")}`)}return{isValid:0===e.length,errors:e}}async initialize(e){await super.initialize(e);const[t,r,i]=await G(()=>import("pg"));if(!t)throw 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 e=`\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(e)}shouldReplicateResource(e){return this.resources.hasOwnProperty(e)}shouldReplicateAction(e,t){return!!this.resources[e]&&this.resources[e].some(e=>e.actions.includes(t))}getTablesForResource(e,t){return this.resources[e]?this.resources[e].filter(e=>e.actions.includes(t)).map(e=>e.table):[]}async replicate(e,t,r,i,s=null){if(!this.enabled||!this.shouldReplicateResource(e))return{skipped:!0,reason:"resource_not_included"};if(!this.shouldReplicateAction(e,t))return{skipped:!0,reason:"action_not_included"};const n=this.getTablesForResource(e,t);if(0===n.length)return{skipped:!0,reason:"no_tables_for_action"};const o=[],a=[],[c,u,l]=await G(async()=>{for(const e of n){const[s,n]=await G(async()=>{let s;if("insert"===t){const t=Object.keys(r),i=t.map(e=>r[e]),n=t.map(e=>`"${e}"`).join(", "),o=t.map((e,t)=>`$${t+1}`).join(", "),a=`INSERT INTO ${e} (${n}) VALUES (${o}) ON CONFLICT (id) DO NOTHING RETURNING *`;s=await this.client.query(a,i)}else if("update"===t){const t=Object.keys(r).filter(e=>"id"!==e),n=t.map((e,t)=>`"${e}"=$${t+1}`).join(", "),o=t.map(e=>r[e]);o.push(i);const a=`UPDATE ${e} SET ${n} WHERE id=$${t.length+1} RETURNING *`;s=await this.client.query(a,o)}else{if("delete"!==t)throw new Error(`Unsupported operation: ${t}`);{const t=`DELETE FROM ${e} WHERE id=$1 RETURNING *`;s=await this.client.query(t,[i])}}o.push({table:e,success:!0,rows:s.rows,rowCount:s.rowCount})});s||a.push({table:e,error:n.message})}if(this.logTable){const[s,n]=await G(async()=>{await this.client.query(`INSERT INTO ${this.logTable} (resource_name, operation, record_id, data, timestamp, source) VALUES ($1, $2, $3, $4, $5, $6)`,[e,t,i,JSON.stringify(r),(new Date).toISOString(),"s3db-replicator"])})}const s=0===a.length;return this.emit("replicated",{replicator:this.name,resourceName:e,operation:t,id:i,tables:n,results:o,errors:a,success:s}),{success:s,results:o,errors:a,tables:n}});return c?l:(this.emit("replicator_error",{replicator:this.name,resourceName:e,operation:t,id:i,error:u.message}),{success:!1,error:u.message})}async replicateBatch(e,t){const r=[],i=[];for(const s of t){const[t,n,o]=await G(()=>this.replicate(e,s.operation,s.data,s.id,s.beforeData));t?r.push(o):i.push({id:s.id,error:n.message})}return{success:0===i.length,results:r,errors:i}}async testConnection(){const[e,t]=await G(async()=>(this.client||await this.initialize(),await this.client.query("SELECT 1"),!0));return!!e||(this.emit("connection_error",{replicator:this.name,error:t.message}),!1)}async cleanup(){this.client&&await this.client.end()}getStatus(){return{...super.getStatus(),database:this.database||"postgres",resources:this.resources,logTable:this.logTable}}}};function cs(e,t={},r=[],i=null){const s=as[e];if(!s)throw new Error(`Unknown replicator driver: ${e}. Available drivers: ${Object.keys(as).join(", ")}`);return new s(t,r,i)}function us(e){return"string"==typeof e?e.trim().toLowerCase():e}class ls extends Ge{constructor(e={}){if(super(),e.verbose&&console.log("[PLUGIN][CONSTRUCTOR] ReplicatorPlugin constructor called"),e.verbose&&console.log("[PLUGIN][constructor] New ReplicatorPlugin instance created with config:",e),!e.replicators||!Array.isArray(e.replicators))throw new Error("ReplicatorPlugin: replicators array is required");for(const t of e.replicators)if(!t.driver)throw new Error("ReplicatorPlugin: each replicator must have a driver");this.config={verbose:e.verbose??!1,persistReplicatorLog:e.persistReplicatorLog??!1,replicatorLogResource:e.replicatorLogResource??"replicator_logs",replicators:e.replicators||[]},this.replicators=[],this.queue=[],this.isProcessing=!1,this.stats={totalOperations:0,totalErrors:0,lastError:null},this._installedListeners=[]}async decompressData(e){return e}filterInternalFields(e){if(!e||"object"!=typeof e)return e;const t={};for(const[r,i]of Object.entries(e))r.startsWith("_")||"$overflow"===r||"$before"===r||"$after"===r||(t[r]=i);return t}installEventListeners(e){const t=this;t.config.verbose&&console.log("[PLUGIN] installEventListeners called for:",e&&e.name,{hasDatabase:!!e.database,sameDatabase:e.database===t.database,alreadyInstalled:e._replicatorListenersInstalled,resourceObj:e,resourceObjId:e&&e.id,resourceObjType:typeof e,resourceObjIs:e&&Object.is(e,t.database.resources&&t.database.resources[e.name]),resourceObjEq:e===(t.database.resources&&t.database.resources[e.name])}),e&&e.name!==t.config.replicatorLogResource&&e.database&&e.database===t.database&&(e._replicatorListenersInstalled||(e._replicatorListenersInstalled=!0,this._installedListeners.push(e),t.config.verbose&&console.log(`[PLUGIN] installEventListeners INSTALLED for resource: ${e&&e.name}`),e.on("insert",async r=>{t.config.verbose&&console.log("[PLUGIN] Listener INSERT on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})));try{const i=await t.getCompleteData(e,r);t.config.verbose&&console.log(`[PLUGIN] Listener INSERT completeData for ${e.name} id=${r&&r.id}:`,i),await t.processReplicatorEvent(e.name,"insert",r.id,i,null)}catch(i){t.config.verbose&&console.error(`[PLUGIN] Listener INSERT error on ${e.name} id=${r&&r.id}:`,i)}}),e.on("update",async r=>{console.log("[PLUGIN][Listener][UPDATE][START] triggered for resource:",e.name,"data:",r);const i=r&&r.$before;t.config.verbose&&console.log("[PLUGIN] Listener UPDATE on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})),"data:",r,"beforeData:",i);try{let s;const[n,o,a]=await G(()=>e.get(r.id));s=n&&a?a:r,await t.processReplicatorEvent(e.name,"update",r.id,s,i)}catch(i){t.config.verbose&&console.error(`[PLUGIN] Listener UPDATE erro em ${e.name} id=${r&&r.id}:`,i)}}),e.on("delete",async(r,i)=>{t.config.verbose&&console.log("[PLUGIN] Listener DELETE on",e.name,"plugin.replicators.length:",t.replicators.length,t.replicators.map(e=>({id:e.id,driver:e.driver})));try{await t.processReplicatorEvent(e.name,"delete",r.id,null,i)}catch(i){t.config.verbose&&console.error(`[PLUGIN] Listener DELETE erro em ${e.name} id=${r&&r.id}:`,i)}}),t.config.verbose&&console.log(`[PLUGIN] Listeners instalados para resource: ${e&&e.name} (insert: ${e.listenerCount("insert")}, update: ${e.listenerCount("update")}, delete: ${e.listenerCount("delete")})`)))}async getCompleteData(e,t){const[r,i,s]=await G(()=>e.get(t.id));return r?s:t}async setup(e){if(console.log("[PLUGIN][SETUP] setup called"),this.config.verbose&&console.log("[PLUGIN][setup] called with database:",e&&e.name),this.database=e,this.config.persistReplicatorLog){let t=e.resources[us(this.config.replicatorLogResource)];t||(t=await e.createResource({name:this.config.replicatorLogResource,behavior:"truncate-data",attributes:{id:"string|required",resource:"string|required",action:"string|required",data:"object",timestamp:"number|required",createdAt:"string|required"},partitions:{byDate:{fields:{createdAt:"string|maxlength:10"}}}}),this.config.verbose&&console.log("[PLUGIN] Log resource created:",this.config.replicatorLogResource,!!t)),e.resources[us(this.config.replicatorLogResource)]=t,this.replicatorLog=t,this.config.verbose&&console.log("[PLUGIN] Log resource created and registered:",this.config.replicatorLogResource,!!e.resources[us(this.config.replicatorLogResource)]),"function"==typeof e.uploadMetadataFile&&(await e.uploadMetadataFile(),this.config.verbose&&console.log("[PLUGIN] uploadMetadataFile called. database.resources keys:",Object.keys(e.resources)))}this.config.replicators&&this.config.replicators.length>0&&0===this.replicators.length&&(await this.initializeReplicators(),console.log("[PLUGIN][SETUP] after initializeReplicators, replicators.length:",this.replicators.length),this.config.verbose&&console.log("[PLUGIN][setup] After initializeReplicators, replicators.length:",this.replicators.length,this.replicators.map(e=>({id:e.id,driver:e.driver}))));for(const t in e.resources)us(t)!==us(this.config.replicatorLogResource)&&this.installEventListeners(e.resources[t]);e.on("connected",()=>{for(const t in e.resources)us(t)!==us(this.config.replicatorLogResource)&&this.installEventListeners(e.resources[t])});const t=e.createResource.bind(e);e.createResource=async e=>{this.config.verbose&&console.log("[PLUGIN] createResource proxy called for:",e&&e.name);const r=await t(e);return r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r),r},e.on("s3db.resourceCreated",t=>{const r=e.resources[t];r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r)}),e.on("s3db.resourceUpdated",t=>{const r=e.resources[t];r&&r.name!==this.config.replicatorLogResource&&this.installEventListeners(r)})}async initializeReplicators(){console.log("[PLUGIN][INIT] initializeReplicators called");for(const e of this.config.replicators)try{console.log("[PLUGIN][INIT] processing replicatorConfig:",e);const t=e.driver,r=e.resources,i=cs(t,e,r,e.client);i?(await i.initialize(this.database),this.replicators.push({id:Math.random().toString(36).slice(2),driver:t,config:e,resources:r,instance:i}),console.log("[PLUGIN][INIT] pushed replicator:",t,r)):console.log("[PLUGIN][INIT] createReplicator returned null/undefined for driver:",t)}catch(e){console.error("[PLUGIN][INIT] Error creating replicator:",e)}}async start(){}async stop(){}async processReplicatorEvent(e,t,r,i,s=null){if(this.config.verbose&&(console.log("[PLUGIN][processReplicatorEvent] replicators.length:",this.replicators.length,this.replicators.map(e=>({id:e.id,driver:e.driver}))),console.log(`[PLUGIN][processReplicatorEvent] operation: ${t}, resource: ${e}, recordId: ${r}, data:`,i,"beforeData:",s)),this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: resource=${e} op=${t} id=${r} data=`,i),this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: resource=${e} op=${t} replicators=${this.replicators.length}`),0===this.replicators.length)return void(this.config.verbose&&console.log("[PLUGIN] No replicators registered"));const n=this.replicators.filter(r=>{const i=r.instance.shouldReplicateResource(e,t);return this.config.verbose&&console.log(`[PLUGIN] Replicator ${r.driver} shouldReplicateResource(${e}, ${t}):`,i),i});if(this.config.verbose&&console.log(`[PLUGIN] processReplicatorEvent: applicableReplicators for resource=${e}:`,n.map(e=>e.driver)),0===n.length)return void(this.config.verbose&&console.log("[PLUGIN] No applicable replicators for resource",e));const o=this.filterInternalFields(m(i)?i:{raw:i}),a=s?this.filterInternalFields(m(s)?s:{raw:s}):null,c={id:`repl-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,resourceName:e,operation:t,recordId:r,data:o,beforeData:a,timestamp:(new Date).toISOString(),attempts:0},u=await this.logreplicator(c),[l,h,f]=await G(async()=>this.processreplicatorItem(c));l?(u&&await this.updatereplicatorLog(u,{status:f.success?"success":"failed",attempts:1,error:f.success?"":JSON.stringify(f.results)}),this.stats.totalOperations++,f.success?this.stats.successfulOperations++:this.stats.failedOperations++):(u&&await this.updatereplicatorLog(u,{status:"failed",attempts:1,error:h.message}),this.stats.failedOperations++)}async processreplicatorItem(e){this.config.verbose&&console.log("[PLUGIN][processreplicatorItem] called with item:",e);const t=this.replicators.filter(t=>{const r=t.instance.shouldReplicateResource(e.resourceName,e.operation);return this.config.verbose&&console.log(`[PLUGIN] processreplicatorItem: Replicator ${t.driver} shouldReplicateResource(${e.resourceName}, ${e.operation}):`,r),r});if(this.config.verbose&&console.log(`[PLUGIN] processreplicatorItem: applicableReplicators for resource=${e.resourceName}:`,t.map(e=>e.driver)),0===t.length)return this.config.verbose&&console.log("[PLUGIN] processreplicatorItem: No applicable replicators for resource",e.resourceName),{success:!0,skipped:!0,reason:"no_applicable_replicators"};const r=[];for(const i of t){let t,s,n;this.config.verbose&&console.log("[PLUGIN] processReplicatorItem",{resource:e.resourceName,operation:e.operation,data:e.data,beforeData:e.beforeData,replicator:i.instance?.constructor?.name}),i.instance&&i.instance.constructor&&"S3dbReplicator"===i.instance.constructor.name?[s,n,t]=await G(()=>i.instance.replicate({resource:e.resourceName,operation:e.operation,data:e.data,id:e.recordId,beforeData:e.beforeData})):[s,n,t]=await G(()=>i.instance.replicate(e.resourceName,e.operation,e.data,e.recordId,e.beforeData)),r.push({replicatorId:i.id,driver:i.driver,success:t&&t.success,error:t&&t.error,skipped:t&&t.skipped})}return{success:r.every(e=>e.success||e.skipped),results:r}}async logreplicator(e){const t=this.replicatorLog||this.database.resources[us(this.config.replicatorLogResource)];if(!t)return this.config.verbose&&console.error("[PLUGIN] replicator log resource not found!"),this.database&&(this.config.verbose&&console.warn("[PLUGIN] database.resources keys:",Object.keys(this.database.resources)),this.database.options&&this.database.options.connectionString&&this.config.verbose&&console.warn("[PLUGIN] database connectionString:",this.database.options.connectionString)),void this.emit("replicator.log.failed",{error:"replicator log resource not found",item:e});const r={id:e.id||`repl-${Date.now()}-${Math.random().toString(36).slice(2)}`,resource:e.resource||e.resourceName||"",action:e.operation||e.action||"",data:e.data||{},timestamp:"number"==typeof e.timestamp?e.timestamp:Date.now(),createdAt:e.createdAt||(new Date).toISOString().slice(0,10)};try{await t.insert(r)}catch(t){this.config.verbose&&console.error("[PLUGIN] Error writing to replicator log:",t),this.emit("replicator.log.failed",{error:t,item:e})}}async updatereplicatorLog(e,t){if(!this.replicatorLog)return;const[r,i]=await G(async()=>{await this.replicatorLog.update(e,{...t,lastAttempt:(new Date).toISOString()})});r||this.emit("replicator.updateLog.failed",{error:i.message,logId:e,updates:t})}async getreplicatorStats(){return{replicators:await Promise.all(this.replicators.map(async e=>{const t=await e.instance.getStatus();return{id:e.id,driver:e.driver,config:e.config,status:t}})),queue:{length:this.queue.length,isProcessing:this.isProcessing},stats:this.stats,lastSync:this.stats.lastSync}}async getreplicatorLogs(e={}){if(!this.replicatorLog)return[];const{resourceName:t,operation:r,status:i,limit:s=100,offset:n=0}=e;let o={};t&&(o.resourceName=t),r&&(o.operation=r),i&&(o.status=i);return(await this.replicatorLog.list(o)).slice(n,n+s)}async retryFailedreplicators(){if(!this.replicatorLog)return{retried:0};const e=await this.replicatorLog.list({status:"failed"});let t=0;for(const r of e){const[e,i]=await G(async()=>{await this.processReplicatorEvent(r.resourceName,r.operation,r.recordId,r.data)});e?t++:this.config.verbose&&console.error("Failed to retry replicator:",i)}return{retried:t}}async syncAllData(e){const t=this.replicators.find(t=>t.id===e);if(!t)throw new Error(`Replicator not found: ${e}`);this.stats.lastSync=(new Date).toISOString();for(const r in this.database.resources)if(us(r)!==us("replicator_logs")&&t.instance.shouldReplicateResource(r)){this.emit("replicator.sync.resource",{resourceName:r,replicatorId:e});const i=this.database.resources[r],s=await i.getAll();for(const e of s)await t.instance.replicate(r,"insert",e,e.id)}this.emit("replicator.sync.completed",{replicatorId:e,stats:this.stats})}async cleanup(){if(this.config.verbose&&console.log("[PLUGIN][CLEANUP] Cleaning up ReplicatorPlugin"),this._installedListeners&&Array.isArray(this._installedListeners)){for(const e of this._installedListeners)e&&"function"==typeof e.removeAllListeners&&(e.removeAllListeners("insert"),e.removeAllListeners("update"),e.removeAllListeners("delete")),e._replicatorListenersInstalled=!1;this._installedListeners=[]}if(this.database&&"function"==typeof this.database.removeAllListeners&&this.database.removeAllListeners(),this.replicators&&Array.isArray(this.replicators)){for(const e of this.replicators)e.instance&&"function"==typeof e.instance.cleanup&&await e.instance.cleanup();this.replicators=[]}this.queue=[],this.isProcessing=!1,this.stats={totalOperations:0,totalErrors:0,lastError:null},this.config.verbose&&console.log("[PLUGIN][CLEANUP] ReplicatorPlugin cleanup complete")}}export{ie as AVAILABLE_BEHAVIORS,Ye as AuditPlugin,ge as AuthenticationError,he as BaseError,Bi as CachePlugin,Yi as Client,Ji as ConnectionString,Ne as ConnectionStringError,zi as CostsPlugin,Ie as CryptoError,se as DEFAULT_BEHAVIOR,ss as Database,de as DatabaseError,ye as EncryptionError,Re as ErrorMap,Vi as FullTextPlugin,Se as InvalidResourceItem,Ki as MetricsPlugin,ke as MissingMetadata,we as NoSuchBucket,ve as NoSuchKey,Oe as NotFound,De as PartitionError,me as PermissionError,Ge as Plugin,Je as PluginObject,ls as ReplicatorPlugin,is as Resource,Ae as ResourceError,Li as ResourceIdsPageReader,Ti as ResourceIdsReader,be as ResourceNotFound,$i as ResourceReader,Mi as ResourceWriter,Gi as S3_DEFAULT_ENDPOINT,Wi as S3_DEFAULT_REGION,ns as S3db,fe as S3dbError,rs as Schema,ts as SchemaActions,Ee as SchemaError,_e as UnknownError,pe as ValidationError,Zi as Validator,es as ValidatorManager,te as behaviors,D as calculateAttributeNamesSize,P as calculateAttributeSizes,$ as calculateEffectiveLimit,L as calculateSystemOverhead,C as calculateTotalSize,A as calculateUTF8Bytes,ce as decode,le as decodeDecimal,Te as decrypt,ns as default,ae as encode,ue as encodeDecimal,Ce as encrypt,re as getBehavior,T as getSizeBreakdown,Me as idGenerator,je as mapAwsError,Le as md5,Ue as passwordGenerator,Pe as sha256,Ui as streamToString,x as transformValue,G as tryFn,J as tryFnSync};
|