@libp2p/mplex 9.0.11-fb8a6f188 → 9.0.12-0f5c305af

Sign up to get free protection for your applications and to get access to all the features.
package/dist/index.min.js CHANGED
@@ -1,5 +1,5 @@
1
1
  (function (root, factory) {(typeof module === 'object' && module.exports) ? module.exports = factory() : root.Libp2PMplex = factory()}(typeof self !== 'undefined' ? self : this, function () {
2
- "use strict";var Libp2PMplex=(()=>{var wi=Object.create;var be=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Ei=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,Si=Object.prototype.hasOwnProperty;var g=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),L=(i,e)=>{for(var t in e)be(i,t,{get:e[t],enumerable:!0})},kt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ei(e))!Si.call(i,s)&&s!==t&&be(i,s,{get:()=>e[s],enumerable:!(r=xi(e,s))||r.enumerable});return i};var Mt=(i,e,t)=>(t=i!=null?wi(_i(i)):{},kt(e||!i||!i.__esModule?be(t,"default",{value:i,enumerable:!0}):t,i)),Ci=i=>kt(be({},"__esModule",{value:!0}),i);var Dt=g((io,Pt)=>{var Y=1e3,Q=Y*60,X=Q*60,K=X*24,Ri=K*7,Ai=K*365.25;Pt.exports=function(i,e){e=e||{};var t=typeof i;if(t==="string"&&i.length>0)return Ii(i);if(t==="number"&&isFinite(i))return e.long?Ti(i):Li(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))};function Ii(i){if(i=String(i),!(i.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(i);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Ai;case"weeks":case"week":case"w":return t*Ri;case"days":case"day":case"d":return t*K;case"hours":case"hour":case"hrs":case"hr":case"h":return t*X;case"minutes":case"minute":case"mins":case"min":case"m":return t*Q;case"seconds":case"second":case"secs":case"sec":case"s":return t*Y;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Li(i){var e=Math.abs(i);return e>=K?Math.round(i/K)+"d":e>=X?Math.round(i/X)+"h":e>=Q?Math.round(i/Q)+"m":e>=Y?Math.round(i/Y)+"s":i+"ms"}function Ti(i){var e=Math.abs(i);return e>=K?ye(i,e,K,"day"):e>=X?ye(i,e,X,"hour"):e>=Q?ye(i,e,Q,"minute"):e>=Y?ye(i,e,Y,"second"):i+" ms"}function ye(i,e,t,r){var s=e>=t*1.5;return Math.round(i/t)+" "+r+(s?"s":"")}});var vt=g((so,Ot)=>{function Ni(i){t.debug=t,t.default=t,t.coerce=c,t.disable=n,t.enable=s,t.enabled=o,t.humanize=Dt(),t.destroy=h,Object.keys(i).forEach(u=>{t[u]=i[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let l=0;for(let d=0;d<u.length;d++)l=(l<<5)-l+u.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(u){let l,d=null,w,m;function p(...f){if(!p.enabled)return;let y=p,E=Number(new Date),_=E-(l||E);y.diff=_,y.prev=l,y.curr=E,l=E,f[0]=t.coerce(f[0]),typeof f[0]!="string"&&f.unshift("%O");let S=0;f[0]=f[0].replace(/%([a-zA-Z%])/g,(P,I)=>{if(P==="%%")return"%";S++;let D=t.formatters[I];if(typeof D=="function"){let H=f[S];P=D.call(y,H),f.splice(S,1),S--}return P}),t.formatArgs.call(y,f),(y.log||t.log).apply(y,f)}return p.namespace=u,p.useColors=t.useColors(),p.color=t.selectColor(u),p.extend=r,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(w!==t.namespaces&&(w=t.namespaces,m=t.enabled(u)),m),set:f=>{d=f}}),typeof t.init=="function"&&t.init(p),p}function r(u,l){let d=t(this.namespace+(typeof l>"u"?":":l)+u);return d.log=this.log,d}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let l,d=(typeof u=="string"?u:"").split(/[\s,]+/),w=d.length;for(l=0;l<w;l++)d[l]&&(u=d[l].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.slice(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function n(){let u=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),u}function o(u){if(u[u.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(u))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack||u.message:u}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Ot.exports=Ni});var Bt=g((T,ge)=>{T.formatArgs=Mi;T.save=Pi;T.load=Di;T.useColors=ki;T.storage=Oi();T.destroy=(()=>{let i=!1;return()=>{i||(i=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();T.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function ki(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Mi(i){if(i[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+i[0]+(this.useColors?"%c ":" ")+"+"+ge.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;i.splice(1,0,e,"color: inherit");let t=0,r=0;i[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),i.splice(r,0,e)}T.log=console.debug||console.log||(()=>{});function Pi(i){try{i?T.storage.setItem("debug",i):T.storage.removeItem("debug")}catch{}}function Di(){let i;try{i=T.storage.getItem("debug")}catch{}return!i&&typeof process<"u"&&"env"in process&&(i=process.env.DEBUG),i}function Oi(){try{return localStorage}catch{}}ge.exports=vt()(T);var{formatters:vi}=ge.exports;vi.j=function(i){try{return JSON.stringify(i)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ue=g((Bo,Xt)=>{Xt.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var Zt=g((Uo,Jt)=>{Jt.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let r=Date.now();return t>=r?t-r:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var tr=g((qo,er)=>{var ns=Zt();er.exports=ns});var k=g((zo,rr)=>{rr.exports=class{constructor(e,t,r,s){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof r>"u"?0:r,this.isFirstInDuration=typeof s>"u"?!1:s}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var te=g((Wo,sr)=>{var We=ue(),os=tr(),ir=k();sr.exports=class extends We{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new os}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,r,s,n,o={}){let a=this._getRateLimiterRes(r,s,n);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(r,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+s&&(a.msBeforeNext=this.msBlockDuration,c=this._block(r,a.consumedPoints,this.msBlockDuration,o)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(r,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(h=>{t(h)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c<this.execEvenlyMinDelayMs&&(c=a.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(e,c,a)}else e(a)}_handleError(e,t,r,s,n,o=!1,a={}){this.insuranceLimiter instanceof We?this.insuranceLimiter[t](n,o,a).then(c=>{r(c)}).catch(c=>{s(c)}):s(e)}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof We))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,r={}){let s=t*1e3;return this._block(this.getKey(e),this.points+1,s,r)}set(e,t,r,s={}){let n=(r>=0?r:this.duration)*1e3;return this._block(this.getKey(e),t,n,s)}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return n(new ir(0,a));this._upsert(o,t,this._getKeySecDuration(r)*1e3,!1,r).then(c=>{this._afterConsume(s,n,o,t,c)}).catch(c=>{this._handleError(c,"consume",s,n,e,t,r)})})}penalty(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,t,a))}).catch(a=>{this._handleError(a,"penalty",n,o,e,t,r)})})}reward(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,-t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,-t,a))}).catch(a=>{this._handleError(a,"reward",n,o,e,t,r)})})}get(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._get(r,t).then(o=>{s(o===null||typeof o>"u"?null:this._getRateLimiterRes(r,0,o))}).catch(o=>{this._handleError(o,"get",s,n,e,t)})})}delete(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._delete(r,t).then(o=>{this._inMemoryBlockedKeys.delete(r),s(o)}).catch(o=>{this._handleError(o,"delete",s,n,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,r){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,r,s={}){return new Promise((n,o)=>{this._upsert(e,t,r,!0,s).then(()=>{n(new ir(0,r>0?r:-1,t))}).catch(a=>{this._handleError(a,"block",n,o,this.parseKey(e),r/1e3,s)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,r,s=!1,n={}){throw new Error("You have to implement the method '_upsert'!")}}});var or=g((Ko,nr)=>{var as=te(),cs=k(),Ke="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",Ge=class extends as{constructor(e){super(e),this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,this.useRedisPackage=e.useRedisPackage,this.useRedis3AndLowerPackage=e.useRedis3AndLowerPackage,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:Ke})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,r){let[s,n]=r;Array.isArray(s)&&([,s]=s,[,n]=n);let o=new cs;return o.consumedPoints=parseInt(s),o.isFirstInDuration=o.consumedPoints===t,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=n,o}async _upsert(e,t,r,s=!1){if(!this._isRedisReady())throw new Error("Redis connection is not ready");let n=Math.floor(r/1e3),o=this.client.multi();return s?(n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.set(e,t,"EX",n):o.set(e,t,{EX:n}):o.set(e,t),!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.pttl(e).exec(!0):o.pTTL(e).exec(!0)):n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.rlflxIncr([e].concat([String(t),String(n)])):this.useRedis3AndLowerPackage?new Promise((a,c)=>{let h=function(u,l){return u?c(u):a(l)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,n,h):this.client.eval(Ke,1,e,t,n,h)}):this.client.eval(Ke,{keys:[e],arguments:[String(t),String(n)]}):!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.incrby(e,t).pttl(e).exec(!0):o.incrBy(e,t).pTTL(e).exec(!0)}async _get(e){if(!this._isRedisReady())throw new Error("Redis connection is not ready");return!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.multi().get(e).pttl(e).exec().then(t=>{let[[,r]]=t;return r===null?null:t}):this.client.multi().get(e).pTTL(e).exec(!0).then(t=>{let[r]=t;return r===null?null:t})}_delete(e){return this.client.del(e).then(t=>t>0)}};nr.exports=Ge});var ur=g((Go,cr)=>{var us=te(),ls=k();function ar(i){try{let e=i.client?i.client:i,{version:t}=e.topology.s.options.metadata.driver,r=t.split(".").map(s=>parseInt(s));return{major:r[0],feature:r[1],patch:r[2]}}catch{return{major:0,feature:0,patch:0}}}var je=class i extends us{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=ar(this.client)}):(this._initCollection(),this._driverVersion=ar(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?i.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,r){let s=new ls,n;return typeof r.value>"u"?n=r:n=r.value,s.isFirstInDuration=n.points===t,s.consumedPoints=n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire!==null?Math.max(new Date(n.expire).getTime()-Date.now(),0):-1,s}_upsert(e,t,r,s=!1,n={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=n.attrs||{},a,c;s?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:t,expire:r>0?new Date(Date.now()+r):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:r>0?new Date(Date.now()+r):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));let h={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?h.returnDocument="after":h.returnOriginal=!1,new Promise((u,l)=>{this._collection.findOneAndUpdate(a,c,h).then(d=>{u(d)}).catch(d=>{if(d&&d.code===11e3){let w=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),m={$set:Object.assign({key:e,points:t,expire:r>0?new Date(Date.now()+r):null},o)};this._collection.findOneAndUpdate(w,m,h).then(p=>{u(p)}).catch(p=>{p&&p.code===11e3?this._upsert(e,t,r,s).then(f=>u(f)).catch(f=>l(f)):l(p)})}else l(d)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},r);return this._collection.findOne(s)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e},r);return this._collection.deleteOne(s).then(n=>n.deletedCount>0)}};cr.exports=je});var hr=g((jo,lr)=>{var hs=te(),ds=k(),He=class extends hs{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(r=>{if(typeof t=="function")t(r);else throw r})}clearExpired(e){return new Promise(t=>{this._getConnection().then(r=>{r.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(r),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((r,s)=>{if(r)return t(r);e(s)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(r=>{r.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,s=>{if(s)return this._releaseConnection(r),t(s);r.query(this._getCreateTableStmt(),n=>{if(n)return this._releaseConnection(r),t(n);this._releaseConnection(r),e()})})}).catch(r=>{t(r)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,r){let s=new ds,[n]=r;return s.isFirstInDuration=t===n.points,s.consumedPoints=s.isFirstInDuration?t:n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire?Math.max(n.expire-Date.now(),0):-1,s}_upsertTransaction(e,t,r,s,n){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let h=Date.now(),u=s>0?h+s:null,l,d;n?(l=`INSERT INTO ??.?? VALUES (?, ?, ?)
2
+ "use strict";var Libp2PMplex=(()=>{var wi=Object.create;var be=Object.defineProperty;var xi=Object.getOwnPropertyDescriptor;var Ei=Object.getOwnPropertyNames;var _i=Object.getPrototypeOf,Si=Object.prototype.hasOwnProperty;var g=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),L=(i,e)=>{for(var t in e)be(i,t,{get:e[t],enumerable:!0})},kt=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ei(e))!Si.call(i,s)&&s!==t&&be(i,s,{get:()=>e[s],enumerable:!(r=xi(e,s))||r.enumerable});return i};var Mt=(i,e,t)=>(t=i!=null?wi(_i(i)):{},kt(e||!i||!i.__esModule?be(t,"default",{value:i,enumerable:!0}):t,i)),Ci=i=>kt(be({},"__esModule",{value:!0}),i);var Dt=g((io,Pt)=>{var Y=1e3,Q=Y*60,X=Q*60,K=X*24,Ri=K*7,Ai=K*365.25;Pt.exports=function(i,e){e=e||{};var t=typeof i;if(t==="string"&&i.length>0)return Ii(i);if(t==="number"&&isFinite(i))return e.long?Ti(i):Li(i);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(i))};function Ii(i){if(i=String(i),!(i.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(i);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Ai;case"weeks":case"week":case"w":return t*Ri;case"days":case"day":case"d":return t*K;case"hours":case"hour":case"hrs":case"hr":case"h":return t*X;case"minutes":case"minute":case"mins":case"min":case"m":return t*Q;case"seconds":case"second":case"secs":case"sec":case"s":return t*Y;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Li(i){var e=Math.abs(i);return e>=K?Math.round(i/K)+"d":e>=X?Math.round(i/X)+"h":e>=Q?Math.round(i/Q)+"m":e>=Y?Math.round(i/Y)+"s":i+"ms"}function Ti(i){var e=Math.abs(i);return e>=K?ye(i,e,K,"day"):e>=X?ye(i,e,X,"hour"):e>=Q?ye(i,e,Q,"minute"):e>=Y?ye(i,e,Y,"second"):i+" ms"}function ye(i,e,t,r){var s=e>=t*1.5;return Math.round(i/t)+" "+r+(s?"s":"")}});var vt=g((so,Ot)=>{function Ni(i){t.debug=t,t.default=t,t.coerce=c,t.disable=n,t.enable=s,t.enabled=o,t.humanize=Dt(),t.destroy=h,Object.keys(i).forEach(u=>{t[u]=i[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let l=0;for(let d=0;d<u.length;d++)l=(l<<5)-l+u.charCodeAt(d),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(u){let l,d=null,w,m;function p(...f){if(!p.enabled)return;let y=p,E=Number(new Date),_=E-(l||E);y.diff=_,y.prev=l,y.curr=E,l=E,f[0]=t.coerce(f[0]),typeof f[0]!="string"&&f.unshift("%O");let S=0;f[0]=f[0].replace(/%([a-zA-Z%])/g,(P,I)=>{if(P==="%%")return"%";S++;let D=t.formatters[I];if(typeof D=="function"){let H=f[S];P=D.call(y,H),f.splice(S,1),S--}return P}),t.formatArgs.call(y,f),(y.log||t.log).apply(y,f)}return p.namespace=u,p.useColors=t.useColors(),p.color=t.selectColor(u),p.extend=r,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(w!==t.namespaces&&(w=t.namespaces,m=t.enabled(u)),m),set:f=>{d=f}}),typeof t.init=="function"&&t.init(p),p}function r(u,l){let d=t(this.namespace+(typeof l>"u"?":":l)+u);return d.log=this.log,d}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let l,d=(typeof u=="string"?u:"").split(/[\s,]+/),w=d.length;for(l=0;l<w;l++)d[l]&&(u=d[l].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.slice(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function n(){let u=[...t.names.map(a),...t.skips.map(a).map(l=>"-"+l)].join(",");return t.enable(""),u}function o(u){if(u[u.length-1]==="*")return!0;let l,d;for(l=0,d=t.skips.length;l<d;l++)if(t.skips[l].test(u))return!1;for(l=0,d=t.names.length;l<d;l++)if(t.names[l].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack||u.message:u}function h(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}Ot.exports=Ni});var Bt=g((T,ge)=>{T.formatArgs=Mi;T.save=Pi;T.load=Di;T.useColors=ki;T.storage=Oi();T.destroy=(()=>{let i=!1;return()=>{i||(i=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();T.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function ki(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Mi(i){if(i[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+i[0]+(this.useColors?"%c ":" ")+"+"+ge.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;i.splice(1,0,e,"color: inherit");let t=0,r=0;i[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),i.splice(r,0,e)}T.log=console.debug||console.log||(()=>{});function Pi(i){try{i?T.storage.setItem("debug",i):T.storage.removeItem("debug")}catch{}}function Di(){let i;try{i=T.storage.getItem("debug")}catch{}return!i&&typeof process<"u"&&"env"in process&&(i=process.env.DEBUG),i}function Oi(){try{return localStorage}catch{}}ge.exports=vt()(T);var{formatters:vi}=ge.exports;vi.j=function(i){try{return JSON.stringify(i)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ue=g((Bo,Xt)=>{Xt.exports=class{constructor(e={}){this.points=e.points,this.duration=e.duration,this.blockDuration=e.blockDuration,this.execEvenly=e.execEvenly,this.execEvenlyMinDelayMs=e.execEvenlyMinDelayMs,this.keyPrefix=e.keyPrefix}get points(){return this._points}set points(e){this._points=e>=0?e:4}get duration(){return this._duration}set duration(e){this._duration=typeof e>"u"?1:e}get msDuration(){return this.duration*1e3}get blockDuration(){return this._blockDuration}set blockDuration(e){this._blockDuration=typeof e>"u"?0:e}get msBlockDuration(){return this.blockDuration*1e3}get execEvenly(){return this._execEvenly}set execEvenly(e){this._execEvenly=typeof e>"u"?!1:!!e}get execEvenlyMinDelayMs(){return this._execEvenlyMinDelayMs}set execEvenlyMinDelayMs(e){this._execEvenlyMinDelayMs=typeof e>"u"?Math.ceil(this.msDuration/this.points):e}get keyPrefix(){return this._keyPrefix}set keyPrefix(e){if(typeof e>"u"&&(e="rlflx"),typeof e!="string")throw new Error("keyPrefix must be string");this._keyPrefix=e}_getKeySecDuration(e={}){return e&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?`${this.keyPrefix}:${e}`:e}parseKey(e){return e.substring(this.keyPrefix.length)}consume(){throw new Error("You have to implement the method 'consume'!")}penalty(){throw new Error("You have to implement the method 'penalty'!")}reward(){throw new Error("You have to implement the method 'reward'!")}get(){throw new Error("You have to implement the method 'get'!")}set(){throw new Error("You have to implement the method 'set'!")}block(){throw new Error("You have to implement the method 'block'!")}delete(){throw new Error("You have to implement the method 'delete'!")}}});var Zt=g((Uo,Jt)=>{Jt.exports=class{constructor(){this._keys={},this._addedKeysAmount=0}collectExpired(){let e=Date.now();Object.keys(this._keys).forEach(t=>{this._keys[t]<=e&&delete this._keys[t]}),this._addedKeysAmount=Object.keys(this._keys).length}add(e,t){this.addMs(e,t*1e3)}addMs(e,t){this._keys[e]=Date.now()+t,this._addedKeysAmount++,this._addedKeysAmount>999&&this.collectExpired()}msBeforeExpire(e){let t=this._keys[e];if(t&&t>=Date.now()){this.collectExpired();let r=Date.now();return t>=r?t-r:0}return 0}delete(e){e?delete this._keys[e]:Object.keys(this._keys).forEach(t=>{delete this._keys[t]})}}});var tr=g((qo,er)=>{var ns=Zt();er.exports=ns});var k=g((zo,rr)=>{rr.exports=class{constructor(e,t,r,s){this.remainingPoints=typeof e>"u"?0:e,this.msBeforeNext=typeof t>"u"?0:t,this.consumedPoints=typeof r>"u"?0:r,this.isFirstInDuration=typeof s>"u"?!1:s}get msBeforeNext(){return this._msBeforeNext}set msBeforeNext(e){return this._msBeforeNext=e,this}get remainingPoints(){return this._remainingPoints}set remainingPoints(e){return this._remainingPoints=e,this}get consumedPoints(){return this._consumedPoints}set consumedPoints(e){return this._consumedPoints=e,this}get isFirstInDuration(){return this._isFirstInDuration}set isFirstInDuration(e){this._isFirstInDuration=!!e}_getDecoratedProperties(){return{remainingPoints:this.remainingPoints,msBeforeNext:this.msBeforeNext,consumedPoints:this.consumedPoints,isFirstInDuration:this.isFirstInDuration}}[Symbol.for("nodejs.util.inspect.custom")](){return this._getDecoratedProperties()}toString(){return JSON.stringify(this._getDecoratedProperties())}toJSON(){return this._getDecoratedProperties()}}});var te=g((Wo,sr)=>{var We=ue(),os=tr(),ir=k();sr.exports=class extends We{constructor(e={}){super(e),this.inMemoryBlockOnConsumed=e.inMemoryBlockOnConsumed,this.inMemoryBlockDuration=e.inMemoryBlockDuration,this.insuranceLimiter=e.insuranceLimiter,this._inMemoryBlockedKeys=new os}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("storeClient is not set");this._client=e}_afterConsume(e,t,r,s,n,o={}){let a=this._getRateLimiterRes(r,s,n);if(this.inMemoryBlockOnConsumed>0&&!(this.inMemoryBlockDuration>0)&&a.consumedPoints>=this.inMemoryBlockOnConsumed)return this._inMemoryBlockedKeys.addMs(r,a.msBeforeNext),a.consumedPoints>this.points?t(a):e(a);if(a.consumedPoints>this.points){let c=Promise.resolve();this.blockDuration>0&&a.consumedPoints<=this.points+s&&(a.msBeforeNext=this.msBlockDuration,c=this._block(r,a.consumedPoints,this.msBlockDuration,o)),this.inMemoryBlockOnConsumed>0&&a.consumedPoints>=this.inMemoryBlockOnConsumed&&(this._inMemoryBlockedKeys.add(r,this.inMemoryBlockDuration),a.msBeforeNext=this.msInMemoryBlockDuration),c.then(()=>{t(a)}).catch(h=>{t(h)})}else if(this.execEvenly&&a.msBeforeNext>0&&!a.isFirstInDuration){let c=Math.ceil(a.msBeforeNext/(a.remainingPoints+2));c<this.execEvenlyMinDelayMs&&(c=a.consumedPoints*this.execEvenlyMinDelayMs),setTimeout(e,c,a)}else e(a)}_handleError(e,t,r,s,n,o=!1,a={}){this.insuranceLimiter instanceof We?this.insuranceLimiter[t](n,o,a).then(c=>{r(c)}).catch(c=>{s(c)}):s(e)}getInMemoryBlockMsBeforeExpire(e){return this.inMemoryBlockOnConsumed>0?this._inMemoryBlockedKeys.msBeforeExpire(e):0}get inMemoryBlockOnConsumed(){return this._inMemoryBlockOnConsumed}set inMemoryBlockOnConsumed(e){if(this._inMemoryBlockOnConsumed=e?parseInt(e):0,this.inMemoryBlockOnConsumed>0&&this.points>this.inMemoryBlockOnConsumed)throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option')}get inMemoryBlockDuration(){return this._inMemoryBlockDuration}set inMemoryBlockDuration(e){if(this._inMemoryBlockDuration=e?parseInt(e):0,this.inMemoryBlockDuration>0&&this.inMemoryBlockOnConsumed===0)throw new Error("inMemoryBlockOnConsumed option must be set up")}get msInMemoryBlockDuration(){return this._inMemoryBlockDuration*1e3}get insuranceLimiter(){return this._insuranceLimiter}set insuranceLimiter(e){if(typeof e<"u"&&!(e instanceof We))throw new Error("insuranceLimiter must be instance of RateLimiterAbstract");this._insuranceLimiter=e,this._insuranceLimiter&&(this._insuranceLimiter.blockDuration=this.blockDuration,this._insuranceLimiter.execEvenly=this.execEvenly)}block(e,t,r={}){let s=t*1e3;return this._block(this.getKey(e),this.points+1,s,r)}set(e,t,r,s={}){let n=(r>=0?r:this.duration)*1e3;return this._block(this.getKey(e),t,n,s)}consume(e,t=1,r={}){return new Promise((s,n)=>{let o=this.getKey(e),a=this.getInMemoryBlockMsBeforeExpire(o);if(a>0)return n(new ir(0,a));this._upsert(o,t,this._getKeySecDuration(r)*1e3,!1,r).then(c=>{this._afterConsume(s,n,o,t,c)}).catch(c=>{this._handleError(c,"consume",s,n,e,t,r)})})}penalty(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,t,a))}).catch(a=>{this._handleError(a,"penalty",n,o,e,t,r)})})}reward(e,t=1,r={}){let s=this.getKey(e);return new Promise((n,o)=>{this._upsert(s,-t,this._getKeySecDuration(r)*1e3,!1,r).then(a=>{n(this._getRateLimiterRes(s,-t,a))}).catch(a=>{this._handleError(a,"reward",n,o,e,t,r)})})}get(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._get(r,t).then(o=>{s(o===null||typeof o>"u"?null:this._getRateLimiterRes(r,0,o))}).catch(o=>{this._handleError(o,"get",s,n,e,t)})})}delete(e,t={}){let r=this.getKey(e);return new Promise((s,n)=>{this._delete(r,t).then(o=>{this._inMemoryBlockedKeys.delete(r),s(o)}).catch(o=>{this._handleError(o,"delete",s,n,e,t)})})}deleteInMemoryBlockedAll(){this._inMemoryBlockedKeys.delete()}_getRateLimiterRes(e,t,r){throw new Error("You have to implement the method '_getRateLimiterRes'!")}_block(e,t,r,s={}){return new Promise((n,o)=>{this._upsert(e,t,r,!0,s).then(()=>{n(new ir(0,r>0?r:-1,t))}).catch(a=>{this._handleError(a,"block",n,o,this.parseKey(e),r/1e3,s)})})}_get(e,t={}){throw new Error("You have to implement the method '_get'!")}_delete(e,t={}){throw new Error("You have to implement the method '_delete'!")}_upsert(e,t,r,s=!1,n={}){throw new Error("You have to implement the method '_upsert'!")}}});var or=g((Ko,nr)=>{var as=te(),cs=k(),Ke="redis.call('set', KEYS[1], 0, 'EX', ARGV[2], 'NX') local consumed = redis.call('incrby', KEYS[1], ARGV[1]) local ttl = redis.call('pttl', KEYS[1]) if ttl == -1 then redis.call('expire', KEYS[1], ARGV[2]) ttl = 1000 * ARGV[2] end return {consumed, ttl} ",Ge=class extends as{constructor(e){super(e),this.client=e.storeClient,this._rejectIfRedisNotReady=!!e.rejectIfRedisNotReady,this.useRedisPackage=e.useRedisPackage||this.client.constructor.name==="Commander"||!1,this.useRedis3AndLowerPackage=e.useRedis3AndLowerPackage,typeof this.client.defineCommand=="function"&&this.client.defineCommand("rlflxIncr",{numberOfKeys:1,lua:Ke})}_isRedisReady(){return this._rejectIfRedisNotReady?!(this.client.status&&this.client.status!=="ready"||typeof this.client.isReady=="function"&&!this.client.isReady()):!0}_getRateLimiterRes(e,t,r){let[s,n]=r;Array.isArray(s)&&([,s]=s,[,n]=n);let o=new cs;return o.consumedPoints=parseInt(s),o.isFirstInDuration=o.consumedPoints===t,o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o.msBeforeNext=n,o}async _upsert(e,t,r,s=!1){if(!this._isRedisReady())throw new Error("Redis connection is not ready");let n=Math.floor(r/1e3),o=this.client.multi();return s?(n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.set(e,t,"EX",n):o.set(e,t,{EX:n}):o.set(e,t),!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.pttl(e).exec(!0):o.pTTL(e).exec(!0)):n>0?!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.rlflxIncr([e].concat([String(t),String(n)])):this.useRedis3AndLowerPackage?new Promise((a,c)=>{let h=function(u,l){return u?c(u):a(l)};typeof this.client.rlflxIncr=="function"?this.client.rlflxIncr(e,t,n,h):this.client.eval(Ke,1,e,t,n,h)}):this.client.eval(Ke,{keys:[e],arguments:[String(t),String(n)]}):!this.useRedisPackage&&!this.useRedis3AndLowerPackage?o.incrby(e,t).pttl(e).exec(!0):o.incrBy(e,t).pTTL(e).exec(!0)}async _get(e){if(!this._isRedisReady())throw new Error("Redis connection is not ready");return!this.useRedisPackage&&!this.useRedis3AndLowerPackage?this.client.multi().get(e).pttl(e).exec().then(t=>{let[[,r]]=t;return r===null?null:t}):this.client.multi().get(e).pTTL(e).exec(!0).then(t=>{let[r]=t;return r===null?null:t})}_delete(e){return this.client.del(e).then(t=>t>0)}};nr.exports=Ge});var ur=g((Go,cr)=>{var us=te(),ls=k();function ar(i){try{let e=i.client?i.client:i,{version:t}=e.topology.s.options.metadata.driver,r=t.split(".").map(s=>parseInt(s));return{major:r[0],feature:r[1],patch:r[2]}}catch{return{major:0,feature:0,patch:0}}}var je=class i extends us{constructor(e){super(e),this.dbName=e.dbName,this.tableName=e.tableName,this.indexKeyPrefix=e.indexKeyPrefix,e.mongo?this.client=e.mongo:this.client=e.storeClient,typeof this.client.then=="function"?this.client.then(t=>{this.client=t,this._initCollection(),this._driverVersion=ar(this.client)}):(this._initCollection(),this._driverVersion=ar(this.client))}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?i.getDbName():e}static getDbName(){return"node-rate-limiter-flexible"}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get client(){return this._client}set client(e){if(typeof e>"u")throw new Error("mongo is not set");this._client=e}get indexKeyPrefix(){return this._indexKeyPrefix}set indexKeyPrefix(e){this._indexKeyPrefix=e||{}}_initCollection(){let t=(typeof this.client.db=="function"?this.client.db(this.dbName):this.client).collection(this.tableName);t.createIndex({expire:-1},{expireAfterSeconds:0}),t.createIndex(Object.assign({},this.indexKeyPrefix,{key:1}),{unique:!0}),this._collection=t}_getRateLimiterRes(e,t,r){let s=new ls,n;return typeof r.value>"u"?n=r:n=r.value,s.isFirstInDuration=n.points===t,s.consumedPoints=n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire!==null?Math.max(new Date(n.expire).getTime()-Date.now(),0):-1,s}_upsert(e,t,r,s=!1,n={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let o=n.attrs||{},a,c;s?(a={key:e},a=Object.assign(a,o),c={$set:{key:e,points:t,expire:r>0?new Date(Date.now()+r):null}},c.$set=Object.assign(c.$set,o)):(a={$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}],key:e},a=Object.assign(a,o),c={$setOnInsert:{key:e,expire:r>0?new Date(Date.now()+r):null},$inc:{points:t}},c.$setOnInsert=Object.assign(c.$setOnInsert,o));let h={upsert:!0};return this._driverVersion.major>=4||this._driverVersion.major===3&&this._driverVersion.feature>=7||this._driverVersion.feature>=6&&this._driverVersion.patch>=7?h.returnDocument="after":h.returnOriginal=!1,new Promise((u,l)=>{this._collection.findOneAndUpdate(a,c,h).then(d=>{u(d)}).catch(d=>{if(d&&d.code===11e3){let w=Object.assign({$or:[{expire:{$lte:new Date}},{expire:{$eq:null}}],key:e},o),m={$set:Object.assign({key:e,points:t,expire:r>0?new Date(Date.now()+r):null},o)};this._collection.findOneAndUpdate(w,m,h).then(p=>{u(p)}).catch(p=>{p&&p.code===11e3?this._upsert(e,t,r,s).then(f=>u(f)).catch(f=>l(f)):l(p)})}else l(d)})})}_get(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e,$or:[{expire:{$gt:new Date}},{expire:{$eq:null}}]},r);return this._collection.findOne(s)}_delete(e,t={}){if(!this._collection)return Promise.reject(Error("Mongo connection is not established"));let r=t.attrs||{},s=Object.assign({key:e},r);return this._collection.deleteOne(s).then(n=>n.deletedCount>0)}};cr.exports=je});var hr=g((jo,lr)=>{var hs=te(),ds=k(),He=class extends hs{constructor(e,t=null){super(e),this.client=e.storeClient,this.clientType=e.storeType,this.dbName=e.dbName,this.tableName=e.tableName,this.clearExpiredByTimeout=e.clearExpiredByTimeout,this.tableCreated=e.tableCreated,this.tableCreated?(this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()):this._createDbAndTable().then(()=>{this.tableCreated=!0,this.clearExpiredByTimeout&&this._clearExpiredHourAgo(),typeof t=="function"&&t()}).catch(r=>{if(typeof t=="function")t(r);else throw r})}clearExpired(e){return new Promise(t=>{this._getConnection().then(r=>{r.query("DELETE FROM ??.?? WHERE expire < ?",[this.dbName,this.tableName,e],()=>{this._releaseConnection(r),t()})}).catch(()=>{t()})})}_clearExpiredHourAgo(){this._clearExpiredTimeoutId&&clearTimeout(this._clearExpiredTimeoutId),this._clearExpiredTimeoutId=setTimeout(()=>{this.clearExpired(Date.now()-36e5).then(()=>{this._clearExpiredHourAgo()})},3e5),this._clearExpiredTimeoutId.unref()}_getConnection(){switch(this.clientType){case"pool":return new Promise((e,t)=>{this.client.getConnection((r,s)=>{if(r)return t(r);e(s)})});case"sequelize":return this.client.connectionManager.getConnection();case"knex":return this.client.client.acquireConnection();default:return Promise.resolve(this.client)}}_releaseConnection(e){switch(this.clientType){case"pool":return e.release();case"sequelize":return this.client.connectionManager.releaseConnection(e);case"knex":return this.client.client.releaseConnection(e);default:return!0}}_createDbAndTable(){return new Promise((e,t)=>{this._getConnection().then(r=>{r.query(`CREATE DATABASE IF NOT EXISTS \`${this.dbName}\`;`,s=>{if(s)return this._releaseConnection(r),t(s);r.query(this._getCreateTableStmt(),n=>{if(n)return this._releaseConnection(r),t(n);this._releaseConnection(r),e()})})}).catch(r=>{t(r)})})}_getCreateTableStmt(){return`CREATE TABLE IF NOT EXISTS \`${this.dbName}\`.\`${this.tableName}\` (\`key\` VARCHAR(255) CHARACTER SET utf8 NOT NULL,\`points\` INT(9) NOT NULL default 0,\`expire\` BIGINT UNSIGNED,PRIMARY KEY (\`key\`)) ENGINE = INNODB;`}get clientType(){return this._clientType}set clientType(e){if(typeof e>"u")if(this.client.constructor.name==="Connection")e="connection";else if(this.client.constructor.name==="Pool")e="pool";else if(this.client.constructor.name==="Sequelize")e="sequelize";else throw new Error("storeType is not defined");this._clientType=e.toLowerCase()}get dbName(){return this._dbName}set dbName(e){this._dbName=typeof e>"u"?"rtlmtrflx":e}get tableName(){return this._tableName}set tableName(e){this._tableName=typeof e>"u"?this.keyPrefix:e}get tableCreated(){return this._tableCreated}set tableCreated(e){this._tableCreated=typeof e>"u"?!1:!!e}get clearExpiredByTimeout(){return this._clearExpiredByTimeout}set clearExpiredByTimeout(e){this._clearExpiredByTimeout=typeof e>"u"?!0:!!e}_getRateLimiterRes(e,t,r){let s=new ds,[n]=r;return s.isFirstInDuration=t===n.points,s.consumedPoints=s.isFirstInDuration?t:n.points,s.remainingPoints=Math.max(this.points-s.consumedPoints,0),s.msBeforeNext=n.expire?Math.max(n.expire-Date.now(),0):-1,s}_upsertTransaction(e,t,r,s,n){return new Promise((o,a)=>{e.query("BEGIN",c=>{if(c)return e.rollback(),a(c);let h=Date.now(),u=s>0?h+s:null,l,d;n?(l=`INSERT INTO ??.?? VALUES (?, ?, ?)
3
3
  ON DUPLICATE KEY UPDATE
4
4
  points = ?,
5
5
  expire = ?;`,d=[this.dbName,this.tableName,t,r,u,r,u]):(l=`INSERT INTO ??.?? VALUES (?, ?, ?)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libp2p/mplex",
3
- "version": "9.0.11-fb8a6f188",
3
+ "version": "9.0.12-0f5c305af",
4
4
  "description": "JavaScript implementation of https://github.com/libp2p/mplex",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "homepage": "https://github.com/libp2p/js-libp2p/tree/master/packages/stream-multiplexer-mplex#readme",
@@ -57,8 +57,8 @@
57
57
  "test:electron-main": "aegir test -t electron-main"
58
58
  },
59
59
  "dependencies": {
60
- "@libp2p/interface": "0.1.5-fb8a6f188",
61
- "@libp2p/logger": "3.0.5-fb8a6f188",
60
+ "@libp2p/interface": "0.1.6-0f5c305af",
61
+ "@libp2p/logger": "3.1.0-0f5c305af",
62
62
  "abortable-iterator": "^5.0.1",
63
63
  "benchmark": "^2.1.4",
64
64
  "it-batched-bytes": "^2.0.2",
@@ -70,7 +70,7 @@
70
70
  "uint8arrays": "^4.0.6"
71
71
  },
72
72
  "devDependencies": {
73
- "@libp2p/interface-compliance-tests": "4.1.4-fb8a6f188",
73
+ "@libp2p/interface-compliance-tests": "4.1.5-0f5c305af",
74
74
  "aegir": "^41.0.2",
75
75
  "cborg": "^4.0.3",
76
76
  "delay": "^6.0.0",