@amityco/ts-sdk 6.4.2 → 6.4.3-0dfdabe.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/cache/api/ingestInCache.d.ts +2 -1
  2. package/dist/cache/api/ingestInCache.d.ts.map +1 -1
  3. package/dist/commentRepository/events/onCommentReactionAdded.d.ts.map +1 -1
  4. package/dist/commentRepository/events/onCommentReactionRemoved.d.ts.map +1 -1
  5. package/dist/index.cjs.js +39 -41
  6. package/dist/index.esm.js +39 -41
  7. package/dist/index.umd.js +1 -1
  8. package/dist/postRepository/events/onPostReactionAdded.d.ts.map +1 -1
  9. package/dist/postRepository/events/onPostReactionRemoved.d.ts.map +1 -1
  10. package/dist/reactionRepository/utils/index.d.ts +1 -1
  11. package/dist/reactionRepository/utils/index.d.ts.map +1 -1
  12. package/dist/reactionRepository/utils/prepareReactionPayloadFormEvent.d.ts +3 -0
  13. package/dist/reactionRepository/utils/prepareReactionPayloadFormEvent.d.ts.map +1 -0
  14. package/dist/utils/tests/dummy/post.d.ts.map +1 -1
  15. package/package.json +1 -1
  16. package/src/cache/api/ingestInCache.ts +4 -1
  17. package/src/channelRepsitory/channelMembership/observers/tests/getMembers.test.ts +7 -1
  18. package/src/channelRepsitory/channelMembership/observers/tests/searchMembers.test.ts +7 -1
  19. package/src/commentRepository/events/onCommentReactionAdded.ts +3 -4
  20. package/src/commentRepository/events/onCommentReactionRemoved.ts +3 -4
  21. package/src/postRepository/events/onPostReactionAdded.ts +3 -4
  22. package/src/postRepository/events/onPostReactionRemoved.ts +3 -4
  23. package/src/postRepository/events/tests/onPostReactionAdded.test.ts +1 -1
  24. package/src/reactionRepository/utils/index.ts +1 -1
  25. package/src/reactionRepository/utils/prepareReactionPayloadFormEvent.ts +62 -0
  26. package/src/utils/tests/dummy/post.ts +1 -0
  27. package/dist/reactionRepository/utils/preparePayloadForCache.d.ts +0 -3
  28. package/dist/reactionRepository/utils/preparePayloadForCache.d.ts.map +0 -1
  29. package/src/reactionRepository/utils/preparePayloadForCache.ts +0 -53
package/dist/index.umd.js CHANGED
@@ -3,4 +3,4 @@ var Amity=function(e){"use strict";const t=Object.freeze({ONLY_ADMIN_CAN_POST:"O
3
3
  /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
4
4
  n.read=function(e,t,n,r,o){var s,i,a=8*o-r-1,c=(1<<a)-1,l=c>>1,u=-7,d=n?o-1:0,h=n?-1:1,f=e[t+d];for(d+=h,s=f&(1<<-u)-1,f>>=-u,u+=a;u>0;s=256*s+e[t+d],d+=h,u-=8);for(i=s&(1<<-u)-1,s>>=-u,u+=r;u>0;i=256*i+e[t+d],d+=h,u-=8);if(0===s)s=1-l;else{if(s===c)return i?NaN:1/0*(f?-1:1);i+=Math.pow(2,r),s-=l}return(f?-1:1)*i*Math.pow(2,s-r)},n.write=function(e,t,n,r,o,s){var i,a,c,l=8*s-o-1,u=(1<<l)-1,d=u>>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,p=r?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,i=u):(i=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-i))<1&&(i--,c*=2),(t+=i+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(i++,c/=2),i+d>=u?(a=0,i=u):i+d>=1?(a=(t*c-1)*Math.pow(2,o),i+=d):(a=t*Math.pow(2,d-1)*Math.pow(2,o),i=0));o>=8;e[n+f]=255&a,f+=p,a/=256,o-=8);for(i=i<<o|a,l+=o;l>0;e[n+f]=255&i,f+=p,i/=256,l-=8);e[n+f-p]|=128*g}},{}],24:[function(e,t,n){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},{}],25:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=function(){function e(e,t){this.color=!0,this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0,this.leftChild=void 0,this.rightChild=void 0,this.key=e,this.value=t}return e.prototype.rotateLeft=function(){var e=this.parent,t=this.brother,n=this.leftChild,r=this.rightChild;if(!r)throw new Error("unknown error");var o=r.leftChild,s=r.rightChild;return e&&(e.leftChild===this?e.leftChild=r:e.rightChild===this&&(e.rightChild=r)),r.parent=e,r.brother=t,r.leftChild=this,r.rightChild=s,t&&(t.brother=r),this.parent=r,this.brother=s,this.leftChild=n,this.rightChild=o,s&&(s.parent=r,s.brother=this),n&&(n.parent=this,n.brother=o),o&&(o.parent=this,o.brother=n),r},e.prototype.rotateRight=function(){var e=this.parent,t=this.brother,n=this.leftChild;if(!n)throw new Error("unknown error");var r=this.rightChild,o=n.leftChild,s=n.rightChild;return e&&(e.leftChild===this?e.leftChild=n:e.rightChild===this&&(e.rightChild=n)),n.parent=e,n.brother=t,n.leftChild=o,n.rightChild=this,t&&(t.brother=n),o&&(o.parent=n,o.brother=this),this.parent=n,this.brother=o,this.leftChild=s,this.rightChild=r,s&&(s.parent=this,s.brother=r),r&&(r.parent=this,r.brother=s),n},e.prototype.remove=function(){if(this.leftChild||this.rightChild)throw new Error("can only remove leaf node");this.parent&&(this===this.parent.leftChild?this.parent.leftChild=void 0:this===this.parent.rightChild&&(this.parent.rightChild=void 0)),this.brother&&(this.brother.brother=void 0),this.key=void 0,this.value=void 0,this.parent=void 0,this.brother=void 0},e.TreeNodeColorType={red:!0,black:!1},e}();Object.freeze(r),n.default=r},{}],26:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};function o(e){var t=this;void 0===e&&(e=[]);var n=[],s=0,i=0,a=0,c=0,l=0,u=0;this.size=function(){return u},this.empty=function(){return 0===u},this.clear=function(){s=a=i=c=l=u=0,h.call(this,o.bucketSize),u=0},this.front=function(){return n[s][i]},this.back=function(){return n[a][c]},this.forEach=function(e){if(!this.empty()){var t=0;if(s!==a){for(l=i;l<o.bucketSize;++l)e(n[s][l],t++);for(l=s+1;l<a;++l)for(var r=0;r<o.bucketSize;++r)e(n[l][r],t++);for(l=0;l<=c;++l)e(n[a][l],t++)}else for(var l=i;l<=c;++l)e(n[s][l],t++)}};var d=function(e){var t=s*o.bucketSize+i,n=t+e,r=a*o.bucketSize+c;if(n<t||n>r)throw new Error("pos should more than 0 and less than queue's size");return{curNodeBucketIndex:Math.floor(n/o.bucketSize),curNodePointerIndex:n%o.bucketSize}};this.getElementByPos=function(e){var t=d(e),r=t.curNodeBucketIndex,o=t.curNodePointerIndex;return n[r][o]},this.eraseElementByPos=function(e){var t=this;if(e<0||e>u)throw new Error("pos should more than 0 and less than queue's size");if(0===e)this.popFront();else if(e===this.size())this.popBack();else{for(var n=[],r=e+1;r<u;++r)n.push(this.getElementByPos(r));this.cut(e),this.popBack(),n.forEach((function(e){return t.pushBack(e)}))}},this.eraseElementByValue=function(e){if(!this.empty()){var t=[];this.forEach((function(n){n!==e&&t.push(n)}));for(var n=t.length,r=0;r<n;++r)this.setElementByPos(r,t[r]);this.cut(n-1)}};var h=function(e){for(var t=[],r=e*o.sigma,d=Math.max(Math.ceil(r/o.bucketSize),2),h=0;h<d;++h)t.push(new Array(o.bucketSize));var f=Math.ceil(e/o.bucketSize),p=Math.floor(d/2)-Math.floor(f/2),g=p,m=0;if(this.size())for(h=0;h<f;++h){for(var y=0;y<o.bucketSize;++y)if(t[p+h][y]=this.front(),this.popFront(),this.empty()){g=p+h,m=y;break}if(this.empty())break}n=t,s=p,i=0,a=g,c=m,l=d,u=e};this.pushBack=function(e){this.empty()||(a===l-1&&c===o.bucketSize-1&&h.call(this,this.size()),c<o.bucketSize-1?++c:a<l-1&&(++a,c=0)),++u,n[a][c]=e},this.popBack=function(){this.empty()||(1!==this.size()&&(c>0?--c:s<a&&(--a,c=o.bucketSize-1)),u>0&&--u)},this.setElementByPos=function(e,t){var r=d(e),o=r.curNodeBucketIndex,s=r.curNodePointerIndex;n[o][s]=t},this.insert=function(e,t,n){var r=this;if(void 0===n&&(n=1),0===e)for(;n--;)this.pushFront(t);else if(e===this.size())for(;n--;)this.pushBack(t);else{for(var o=[],s=e;s<u;++s)o.push(this.getElementByPos(s));for(this.cut(e-1),s=0;s<n;++s)this.pushBack(t);o.forEach((function(e){return r.pushBack(e)}))}},this.find=function(e){if(s===a){for(var t=i;t<=c;++t)if(n[s][t]===e)return!0;return!1}for(t=i;t<o.bucketSize;++t)if(n[s][t]===e)return!0;for(t=s+1;t<a;++t)for(var r=0;r<o.bucketSize;++r)if(n[t][r]===e)return!0;for(t=0;t<=c;++t)if(n[a][t]===e)return!0;return!1},this.reverse=function(){for(var e=0,t=u-1;e<t;){var n=this.getElementByPos(e);this.setElementByPos(e,this.getElementByPos(t)),this.setElementByPos(t,n),++e,--t}},this.unique=function(){if(!this.empty()){var e=[],t=this.front();this.forEach((function(n,r){0!==r&&n===t||(e.push(n),t=n)}));for(var n=0;n<u;++n)this.setElementByPos(n,e[n]);this.cut(e.length-1)}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);for(var n=0;n<u;++n)this.setElementByPos(n,t[n])},this.pushFront=function(e){this.empty()||(0===s&&0===i&&h.call(this,this.size()),i>0?--i:s>0&&(--s,i=o.bucketSize-1)),++u,n[s][i]=e},this.popFront=function(){this.empty()||(1!==this.size()&&(i<o.bucketSize-1?++i:s<a&&(++s,i=0)),u>0&&--u)},this.shrinkToFit=function(){var e=this,t=[];this.forEach((function(e){t.push(e)}));var r=t.length;n=[];for(var s=Math.ceil(r/o.bucketSize),i=0;i<s;++i)n.push(new Array(o.bucketSize));this.clear(),t.forEach((function(t){return e.pushBack(t)}))},this.cut=function(e){if(e<0)this.clear();else{var t=d(e),n=t.curNodeBucketIndex,r=t.curNodePointerIndex;a=n,c=r,u=e+1}},this[Symbol.iterator]=function(){return function(){var e,t;return r(this,(function(r){switch(r.label){case 0:if(0===u)return[2];if(s!==a)return[3,5];t=i,r.label=1;case 1:return t<=c?[4,n[s][t]]:[3,4];case 2:r.sent(),r.label=3;case 3:return++t,[3,1];case 4:return[2];case 5:t=i,r.label=6;case 6:return t<o.bucketSize?[4,n[s][t]]:[3,9];case 7:r.sent(),r.label=8;case 8:return++t,[3,6];case 9:t=s+1,r.label=10;case 10:if(!(t<a))return[3,15];e=0,r.label=11;case 11:return e<o.bucketSize?[4,n[t][e]]:[3,14];case 12:r.sent(),r.label=13;case 13:return++e,[3,11];case 14:return++t,[3,10];case 15:t=0,r.label=16;case 16:return t<=c?[4,n[a][t]]:[3,19];case 17:r.sent(),r.label=18;case 18:return++t,[3,16];case 19:return[2]}}))}()},function(){var r=o.bucketSize;e.size?r=e.size():e.length&&(r=e.length);var i=r*o.sigma;l=Math.ceil(i/o.bucketSize),l=Math.max(l,3);for(var c=0;c<l;++c)n.push(new Array(o.bucketSize));var u=Math.ceil(r/o.bucketSize);s=Math.floor(l/2)-Math.floor(u/2),a=s,e.forEach((function(e){return t.pushBack(e)}))}(),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),o.sigma=3,o.bucketSize=5e3,Object.freeze(o),n.default=o},{}],27:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../LinkList/LinkList"),i=e("../Map/Map");function a(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=a.initSize),n=n||function(e){var t,n,r=0,s="";if("number"==typeof e)r=((r=Math.floor(e))<<5)-r,r&=r;else{s="string"!=typeof e?JSON.stringify(e):e;try{for(var i=o(s),a=i.next();!a.done;a=i.next())r=(r<<5)-r+a.value.charCodeAt(0),r&=r}catch(e){t={error:e}}finally{try{a&&!a.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}}return r^=r>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,u=[],d=Math.max(a.initSize,Math.min(a.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,d=t,u=[]},this.forEach=function(e){var t=0;u.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=a.maxSize)){d=2*e;var t=[];u.forEach((function(r,o){if(!r.empty()){if(r instanceof s.default&&1===r.size()){var c=r.front(),l=c.key,h=c.value;t[n(l)&d-1]=new s.default([{key:l,value:h}])}else if(r instanceof i.default){var f=new s.default,p=new s.default;r.forEach((function(t){0==(n(t.key)&e)?f.pushBack(t):p.pushBack(t)})),f.size()>a.untreeifyThreshold?t[o]=new i.default(f):f.size()&&(t[o]=f),p.size()>a.untreeifyThreshold?t[o+e]=new i.default(p):p.size()&&(t[o+e]=p)}else{var g=new s.default,m=new s.default;r.forEach((function(t){0==(n(t.key)&e)?g.pushBack(t):m.pushBack(t)})),g.size()&&(t[o]=g),m.size()&&(t[o+e]=m)}u[o].clear()}})),u=t}};this.setElement=function(e,t){var r,c;if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=t){var f=n(e)&d-1;if(u[f]){var p=u[f].size();if(u[f]instanceof s.default){try{for(var g=o(u[f]),m=g.next();!m.done;m=g.next()){var y=m.value;if(y.key===e)return void(y.value=t)}}catch(e){r={error:e}}finally{try{m&&!m.done&&(c=g.return)&&c.call(g)}finally{if(r)throw r.error}}u[f].pushBack({key:e,value:t}),u[f].size()>=a.treeifyThreshold&&(u[f]=new i.default(u[f]))}else u[f].setElement(e,t);var v=u[f].size();l+=v-p}else++l,u[f]=new s.default([{key:e,value:t}]);l>d*a.sigma&&h.call(this,d)}else this.eraseElementByKey(e)},this.getElementByKey=function(e){var t,r,s=n(e)&d-1;if(u[s]){if(u[s]instanceof i.default)return u[s].getElementByKey(e);try{for(var a=o(u[s]),c=a.next();!c.done;c=a.next()){var l=c.value;if(l.key===e)return l.value}}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}}},this.eraseElementByKey=function(e){var t,r,c=n(e)&d-1;if(u[c]){var h=u[c].size();if(u[c]instanceof i.default)u[c].eraseElementByKey(e),u[c].size()<=a.untreeifyThreshold&&(u[c]=new s.default(u[c]));else{var f=-1;try{for(var p=o(u[c]),g=p.next();!g.done;g=p.next()){var m=g.value;if(++f,m.key===e){u[c].eraseElementByPos(f);break}}}catch(e){t={error:e}}finally{try{g&&!g.done&&(r=p.return)&&r.call(p)}finally{if(t)throw t.error}}}var y=u[c].size();l+=y-h}},this.find=function(e){var t,r,s=n(e)&d-1;if(!u[s])return!1;if(u[s]instanceof i.default)return u[s].find(e);try{for(var a=o(u[s]),c=a.next();!c.done;c=a.next())if(c.value.key===e)return!0}catch(e){t={error:e}}finally{try{c&&!c.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}return!1},this[Symbol.iterator]=function(){return function(){var e,t,n,s,i,a;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<d))return[3,10];for(;e<d&&!u[e];)++e;if(e>=d)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),i=void 0,t=o(u[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=r.sent(),i={error:s},[3,9];case 8:try{n&&!n.done&&(a=t.return)&&a.call(t)}finally{if(i)throw i.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){var t=e.key,n=e.value;return c.setElement(t,n)})),Object.freeze(this)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),n.default=a},{"../LinkList/LinkList":29,"../Map/Map":30}],28:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Set/Set"),i=e("../LinkList/LinkList");function a(e,t,n){var c=this;if(void 0===e&&(e=[]),void 0===t&&(t=a.initSize),n=n||function(e){var t=0,n="";if("number"==typeof e)t=((t=Math.floor(e))<<5)-t,t&=t;else{n="string"!=typeof e?JSON.stringify(e):e;for(var r=0;r<n.length;r++)t=(t<<5)-t+n.charCodeAt(r),t&=t}return t^=t>>>16},0!=(t&t-1))throw new Error("initBucketNum must be 2 to the power of n");var l=0,u=[],d=Math.max(a.initSize,Math.min(a.maxSize,t));this.size=function(){return l},this.empty=function(){return 0===l},this.clear=function(){l=0,d=t,u=[]},this.forEach=function(e){var t=0;u.forEach((function(n){n.forEach((function(n){e(n,t++)}))}))};var h=function(e){if(!(e>=a.maxSize)){d=2*e;var t=[];u.forEach((function(r,o){if(!r.empty()){if(r instanceof i.default&&1===r.size()){var c=r.front();if(void 0===c)throw new Error("unknown error");t[n(c)&d-1]=new i.default([c])}else if(r instanceof s.default){var l=new i.default,h=new i.default;r.forEach((function(t){0==(n(t)&e)?l.pushBack(t):h.pushBack(t)})),l.size()>a.untreeifyThreshold?t[o]=new s.default(l):l.size()&&(t[o]=l),h.size()>a.untreeifyThreshold?t[o+e]=new s.default(h):h.size()&&(t[o+e]=h)}else{var f=new i.default,p=new i.default;r.forEach((function(t){0==(n(t)&e)?f.pushBack(t):p.pushBack(t)})),f.size()&&(t[o]=f),p.size()&&(t[o+e]=p)}u[o].clear()}})),u=t}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");var t=n(e)&d-1;if(u[t]){var r=u[t].size();if(u[t]instanceof i.default){if(u[t].find(e))return;u[t].pushBack(e),u[t].size()>=a.treeifyThreshold&&(u[t]=new s.default(u[t]))}else u[t].insert(e);var o=u[t].size();l+=o-r}else u[t]=new i.default([e]),++l;l>d*a.sigma&&h.call(this,d)},this.eraseElementByValue=function(e){var t=n(e)&d-1;if(u[t]){var r=u[t].size();u[t].eraseElementByValue(e),u[t]instanceof s.default&&u[t].size()<=a.untreeifyThreshold&&(u[t]=new i.default(u[t]));var o=u[t].size();l+=o-r}},this.find=function(e){var t=n(e)&d-1;return!!u[t]&&u[t].find(e)},this[Symbol.iterator]=function(){return function(){var e,t,n,s,i,a;return r(this,(function(r){switch(r.label){case 0:e=0,r.label=1;case 1:if(!(e<d))return[3,10];for(;e<d&&!u[e];)++e;if(e>=d)return[3,10];r.label=2;case 2:r.trys.push([2,7,8,9]),i=void 0,t=o(u[e]),n=t.next(),r.label=3;case 3:return n.done?[3,6]:[4,n.value];case 4:r.sent(),r.label=5;case 5:return n=t.next(),[3,3];case 6:return[3,9];case 7:return s=r.sent(),i={error:s},[3,9];case 8:try{n&&!n.done&&(a=t.return)&&a.call(t)}finally{if(i)throw i.error}return[7];case 9:return++e,[3,1];case 10:return[2]}}))}()},e.forEach((function(e){return c.insert(e)})),Object.freeze(this)}a.initSize=16,a.maxSize=1<<30,a.sigma=.75,a.treeifyThreshold=8,a.untreeifyThreshold=6,a.minTreeifySize=64,Object.freeze(a),n.default=a},{"../LinkList/LinkList":29,"../Set/Set":33}],29:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}};Object.defineProperty(n,"__esModule",{value:!0});var o=function(){function e(e){this.value=void 0,this.pre=void 0,this.next=void 0,this.value=e}return e}();function s(e){var t=this;void 0===e&&(e=[]);var n=0,s=void 0,i=void 0;this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){s=i=void 0,n=0},this.front=function(){return null==s?void 0:s.value},this.back=function(){return null==i?void 0:i.value},this.forEach=function(e){for(var t=s,n=0;t;){if(void 0===t.value)throw new Error("unknown error");e(t.value,n++),t=t.next}},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var t=s;e--&&t;)t=t.next;if(!t||void 0===t.value)throw new Error("unknown error");return t.value},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("erase pos must more then 0 and less then the list length");if(0===e)this.popFront();else if(e===n-1)this.popBack();else{for(var t=s;e--;){if(!(null==t?void 0:t.next))throw new Error("unknown error");t=t.next}if(!t||!t.pre||!t.next)throw new Error("unknown error");var r=t.pre,o=t.next;o.pre=r,r.next=o,n>0&&--n}},this.eraseElementByValue=function(e){for(;s&&s.value===e;)this.popFront();for(;i&&i.value===e;)this.popBack();if(s)for(var t=s;t;){if(t.value===e){var r=t.pre,o=t.next;o&&(o.pre=r),r&&(r.next=o),n>0&&--n}t=t.next}},this.pushBack=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new o(e);i?(i.next=t,t.pre=i,i=t):s=i=t},this.popBack=function(){i&&(n>0&&--n,i&&(s===i?s=i=void 0:(i=i.pre)&&(i.next=void 0)))},this.setElementByPos=function(e,t){if(null==t)throw new Error("you can't set null or undefined here");if(e<0||e>=n)throw new Error("pos must more then 0 and less then the list length");for(var r=s;e--;){if(!r)throw new Error("unknown error");r=r.next}r&&(r.value=t)},this.insert=function(e,t,r){if(void 0===r&&(r=1),null==t)throw new Error("you can't insert null or undefined here");if(e<0||e>n)throw new Error("insert pos must more then 0 and less then or equal to the list length");if(r<0)throw new Error("insert size must more than 0");if(0===e)for(;r--;)this.pushFront(t);else if(e===n)for(;r--;)this.pushBack(t);else{for(var i=s,a=1;a<e;++a){if(!(null==i?void 0:i.next))throw new Error("unknown error");i=null==i?void 0:i.next}if(!i)throw new Error("unknown error");var c=i.next;for(n+=r;r--;)i.next=new o(t),i.next.pre=i,i=i.next;i.next=c,c&&(c.pre=i)}},this.find=function(e){for(var t=s;t;){if(t.value===e)return!0;t=t.next}return!1},this.reverse=function(){for(var e=s,t=i,r=0;e&&t&&2*r<n;){var o=e.value;e.value=t.value,t.value=o,e=e.next,t=t.pre,++r}},this.unique=function(){for(var e=s;e;){for(var t=e;t&&t.next&&t.value===t.next.value;)t=t.next,n>0&&--n;e.next=t.next,e.next&&(e.next.pre=e),e=e.next}},this.sort=function(e){var t=[];this.forEach((function(e){t.push(e)})),t.sort(e);var n=s;t.forEach((function(e){n&&(n.value=e,n=n.next)}))},this.pushFront=function(e){if(null==e)throw new Error("you can't push null or undefined here");++n;var t=new o(e);s?(t.next=s,s.pre=t,s=t):s=i=t},this.popFront=function(){s&&(n>0&&--n,s&&(s===i?s=i=void 0:(s=s.next)&&(s.pre=void 0)))},this.merge=function(e){var t=this,r=s;e.forEach((function(e){for(;r&&void 0!==r.value&&r.value<=e;)r=r.next;if(void 0===r)t.pushBack(e),r=i;else if(r===s)t.pushFront(e),r=s;else{++n;var a=r.pre;a&&(a.next=new o(e),a.next.pre=a,a.next.next=r,r&&(r.pre=a.next))}}))},this[Symbol.iterator]=function(){return function(){var e;return r(this,(function(t){switch(t.label){case 0:e=s,t.label=1;case 1:if(void 0===e)return[3,3];if(!e.value)throw new Error("unknown error");return[4,e.value];case 2:return t.sent(),e=e.next,[3,1];case 3:return[2]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.freeze(s),n.default=s},{}],30:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function i(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var i=0,a=new s.default;a.color=s.default.TreeNodeColorType.black,this.size=function(){return i},this.empty=function(){return 0===i},this.clear=function(){i=0,a.key=a.value=void 0,a.leftChild=a.rightChild=a.brother=void 0};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty()){var e=c(a);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.back=function(){if(!this.empty()){var e=l(a);if(void 0===e.key||void 0===e.value)throw new Error("unknown error");return{key:e.key,value:e.value}}},this.forEach=function(e){var t,n,r=0;try{for(var s=o(this),i=s.next();!i.done;i=s.next())e(i.value,r++)}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var s=o(this),i=s.next();!i.done;i=s.next()){var a=i.value;if(r===e)return a;++r}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown Error")};var u=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r<0?u(e.rightChild,n):u(e.leftChild,n)||{key:e.key,value:e.value}}};this.lowerBound=function(e){return u(a,e)};var d=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)<=0?d(e.rightChild,n):d(e.leftChild,n)||{key:e.key,value:e.value}};this.upperBound=function(e){return d(a,e)};var h=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value){var r=t(e.key,n);return 0===r?{key:e.key,value:e.value}:r>0?h(e.leftChild,n):h(e.rightChild,n)||{key:e.key,value:e.value}}};this.reverseLowerBound=function(e){return h(a,e)};var f=function(e,n){if(e&&void 0!==e.key&&void 0!==e.value)return t(e.key,n)>=0?f(e.leftChild,n):f(e.rightChild,n)||{key:e.key,value:e.value}};this.reverseUpperBound=function(e){return f(a,e)};var p=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();a===t&&(a=r),p(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),a===t&&(a=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,p(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),a===n&&(a=r),p(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),a===t&&(a=r),p(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),a===t&&(a=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,p(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),a===n&&(a=r),p(e))))}else e.color=s.default.TreeNodeColorType.black},g=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n;var r=e.value;e.value=t.value,t.value=r,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,r=e.value,e.value=t.value,t.value=r,e=t)}p(t),t&&t.remove(),--i,a.color=s.default.TreeNodeColorType.black},m=function(e,t){return!(!e||void 0===e.key)&&(!!m(e.leftChild,t)||!!t(e)||m(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=i)throw new Error("pos must more than 0 and less than set's size");var t=0;m(a,(function(n){return e===t?(g(n),!0):(++t,!1)}))},this.eraseElementByKey=function(e){if(!this.empty()){var n=b(a,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&g(n)}};var y=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?y(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?y(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},v=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,v(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var o=r.rotateRight();r===a&&(a=o)}else e===t.rightChild&&(o=t.rotateLeft(),r===a&&(a=o),v(t));else t===r.rightChild&&(e===t.leftChild?(o=t.rotateRight(),r===a&&(a=o),v(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,o=r.rotateLeft(),r===a&&(a=o)))}};this.setElement=function(e,n){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(null!=n){if(this.empty())return++i,a.key=e,a.value=n,void(a.color=s.default.TreeNodeColorType.black);var r=y(a,e);void 0===r.key||0!==t(r.key,e)?(++i,r.key=e,r.value=n,v(r),a.color=s.default.TreeNodeColorType.black):r.value=n}else this.eraseElementByKey(e)};var b=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?b(e.leftChild,n):r>0?b(e.rightChild,n):e}};this.find=function(e){return!!b(a,e)},this.getElementByKey=function(e){var t=b(a,e);if(void 0===(null==t?void 0:t.key)||void 0===(null==t?void 0:t.value))throw new Error("unknown error");return t.value},this.union=function(e){var t=this;e.forEach((function(e){var n=e.key,r=e.value;return t.setElement(n,r)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(a)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key&&void 0!==e.value?[5,o(w(e.leftChild))]:[2];case 1:return t.sent(),[4,{key:e.key,value:e.value}];case 2:return t.sent(),[5,o(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(a)},e.forEach((function(e){var t=e.key,r=e.value;return n.setElement(t,r)})),Object.freeze(this)}Object.freeze(i),n.default=i},{"../Base/TreeNode":25}],31:[function(e,t,n){function r(e,t){void 0===e&&(e=[]),t=t||function(e,t){return e>t?-1:e<t?1:0};var n=[];e.forEach((function(e){return n.push(e)}));var r=n.length,o=function(e,t){if(e<0||e>=r)throw new Error("unknown error");if(t<0||t>=r)throw new Error("unknown error");var o=n[e];n[e]=n[t],n[t]=o},s=function(e){if(e<0||e>=r)throw new Error("unknown error");var s=2*e+1,i=2*e+2;s<r&&t(n[e],n[s])>0&&o(e,s),i<r&&t(n[e],n[i])>0&&o(e,i)};!function(){for(var e=Math.floor((r-1)/2);e>=0;--e)for(var s=e,i=2*s+1;i<r;){var a=i+1,c=i;if(a<r&&t(n[i],n[a])>0&&(c=a),t(n[s],n[c])<=0)break;o(s,c),i=2*(s=c)+1}}(),this.size=function(){return r},this.empty=function(){return 0===r},this.clear=function(){r=0,n.length=0},this.push=function(e){if(n.push(e),1!=++r)for(var o=r-1;o>0;){var i=Math.floor((o-1)/2);if(t(n[i],e)<=0)break;s(i),o=i}},this.pop=function(){if(!this.empty())if(1!==this.size()){var e=n[r-1];--r;for(var o=0;o<this.size();){var s=2*o+1,i=2*o+2;if(s>=this.size())break;var a=s;if(i<this.size()&&t(n[s],n[i])>0&&(a=i),t(n[a],e)>=0)break;n[o]=n[a],o=a}n[o]=e}else--r},this.top=function(){return n[0]},Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],32:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0});var r=e("../LinkList/LinkList");function o(e){void 0===e&&(e=[]);var t=new r.default(e);this.size=function(){return t.size()},this.empty=function(){return t.empty()},this.clear=function(){t.clear()},this.push=function(e){t.pushBack(e)},this.pop=function(){t.popFront()},this.front=function(){return t.front()},Object.freeze(this)}Object.freeze(o),n.default=o},{"../LinkList/LinkList":29}],33:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(n,"__esModule",{value:!0});var s=e("../Base/TreeNode");function i(e,t){var n=this;void 0===e&&(e=[]),t=t||function(e,t){return e<t?-1:e>t?1:0};var i=0,a=new s.default;a.color=s.default.TreeNodeColorType.black,this.size=function(){return i},this.empty=function(){return 0===i},this.clear=function(){i=0,a.key=void 0,a.leftChild=a.rightChild=a.brother=a.parent=void 0,a.color=s.default.TreeNodeColorType.black};var c=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.leftChild?c(e.leftChild):e},l=function(e){if(!e||void 0===e.key)throw new Error("unknown error");return e.rightChild?l(e.rightChild):e};this.front=function(){if(!this.empty())return c(a).key},this.back=function(){if(!this.empty())return l(a).key},this.forEach=function(e){var t,n,r=0;try{for(var s=o(this),i=s.next();!i.done;i=s.next())e(i.value,r++)}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}},this.getElementByPos=function(e){var t,n;if(e<0||e>=this.size())throw new Error("pos must more than 0 and less than set's size");var r=0;try{for(var s=o(this),i=s.next();!i.done;i=s.next()){var a=i.value;if(r===e)return a;++r}}catch(e){t={error:e}}finally{try{i&&!i.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}throw new Error("unknown error")};var u=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(e.color!==s.default.TreeNodeColorType.red){var n=e.brother;if(!n)throw new Error("unknown error");if(e===t.leftChild)if(n.color===s.default.TreeNodeColorType.red){n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red;var r=t.rotateLeft();a===t&&(a=r),u(e)}else n.color===s.default.TreeNodeColorType.black&&(n.rightChild&&n.rightChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=t.rotateLeft(),a===t&&(a=r),e.color=s.default.TreeNodeColorType.black):n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||!n.leftChild||n.leftChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,u(t)):(n.color=s.default.TreeNodeColorType.red,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=n.rotateRight(),a===n&&(a=r),u(e)));else e===t.rightChild&&(n.color===s.default.TreeNodeColorType.red?(n.color=s.default.TreeNodeColorType.black,t.color=s.default.TreeNodeColorType.red,r=t.rotateRight(),a===t&&(a=r),u(e)):n.color===s.default.TreeNodeColorType.black&&(n.leftChild&&n.leftChild.color===s.default.TreeNodeColorType.red?(n.color=t.color,t.color=s.default.TreeNodeColorType.black,n.leftChild&&(n.leftChild.color=s.default.TreeNodeColorType.black),r=t.rotateRight(),a===t&&(a=r),e.color=s.default.TreeNodeColorType.black):n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||!n.rightChild||n.rightChild.color!==s.default.TreeNodeColorType.red?n.leftChild&&n.leftChild.color!==s.default.TreeNodeColorType.black||n.rightChild&&n.rightChild.color!==s.default.TreeNodeColorType.black||(n.color=s.default.TreeNodeColorType.red,u(t)):(n.color=s.default.TreeNodeColorType.red,n.rightChild&&(n.rightChild.color=s.default.TreeNodeColorType.black),r=n.rotateLeft(),a===n&&(a=r),u(e))))}else e.color=s.default.TreeNodeColorType.black},d=function(e){for(var t=e;t.leftChild||t.rightChild;){if(t.rightChild){t=c(t.rightChild);var n=e.key;e.key=t.key,t.key=n,e=t}t.leftChild&&(t=l(t.leftChild),n=e.key,e.key=t.key,t.key=n,e=t)}u(t),t&&t.remove(),--i,a.color=s.default.TreeNodeColorType.black},h=function(e,t){return!(!e||void 0===e.key)&&(!!h(e.leftChild,t)||!!t(e)||h(e.rightChild,t))};this.eraseElementByPos=function(e){if(e<0||e>=i)throw new Error("pos must more than 0 and less than set's size");var t=0;h(a,(function(n){return e===t?(d(n),!0):(++t,!1)}))},this.eraseElementByValue=function(e){if(!this.empty()){var n=g(a,e);void 0!==n&&void 0!==n.key&&0===t(n.key,e)&&d(n)}};var f=function(e,n){if(!e||void 0===e.key)throw new Error("unknown error");var r=t(n,e.key);return r<0?e.leftChild?f(e.leftChild,n):(e.leftChild=new s.default,e.leftChild.parent=e,e.leftChild.brother=e.rightChild,e.rightChild&&(e.rightChild.brother=e.leftChild),e.leftChild):r>0?e.rightChild?f(e.rightChild,n):(e.rightChild=new s.default,e.rightChild.parent=e,e.rightChild.brother=e.leftChild,e.leftChild&&(e.leftChild.brother=e.rightChild),e.rightChild):e},p=function(e){var t=e.parent;if(!t){if(e===a)return;throw new Error("unknown error")}if(t.color!==s.default.TreeNodeColorType.black&&t.color===s.default.TreeNodeColorType.red){var n=t.brother,r=t.parent;if(!r)throw new Error("unknown error");if(n&&n.color===s.default.TreeNodeColorType.red)n.color=t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,p(r);else if(!n||n.color===s.default.TreeNodeColorType.black)if(t===r.leftChild)if(e===t.leftChild){t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red;var o=r.rotateRight();r===a&&(a=o)}else e===t.rightChild&&(o=t.rotateLeft(),r===a&&(a=o),p(t));else t===r.rightChild&&(e===t.leftChild?(o=t.rotateRight(),r===a&&(a=o),p(t)):e===t.rightChild&&(t.color=s.default.TreeNodeColorType.black,r.color=s.default.TreeNodeColorType.red,o=r.rotateLeft(),r===a&&(a=o)))}};this.insert=function(e){if(null==e)throw new Error("to avoid some unnecessary errors, we don't suggest you insert null or undefined here");if(this.empty())return++i,a.key=e,void(a.color=s.default.TreeNodeColorType.black);var n=f(a,e);void 0!==n.key&&0===t(n.key,e)||(++i,n.key=e,p(n),a.color=s.default.TreeNodeColorType.black)};var g=function(e,n){if(e&&void 0!==e.key){var r=t(n,e.key);return r<0?g(e.leftChild,n):r>0?g(e.rightChild,n):e}};this.find=function(e){var n=g(a,e);return void 0!==n&&void 0!==n.key&&0===t(n.key,e)};var m=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r<0)return m(e.rightChild,n);var o=m(e.leftChild,n);return void 0!==o?o:e.key}};this.lowerBound=function(e){return m(a,e)};var y=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)<=0)return y(e.rightChild,n);var r=y(e.leftChild,n);return void 0!==r?r:e.key}};this.upperBound=function(e){return y(a,e)};var v=function(e,n){if(e&&void 0!==e.key){var r=t(e.key,n);if(0===r)return e.key;if(r>0)return v(e.leftChild,n);var o=v(e.rightChild,n);return void 0!==o?o:e.key}};this.reverseLowerBound=function(e){return v(a,e)};var b=function(e,n){if(e&&void 0!==e.key){if(t(e.key,n)>=0)return b(e.leftChild,n);var r=b(e.rightChild,n);return void 0!==r?r:e.key}};this.reverseUpperBound=function(e){return b(a,e)},this.union=function(e){var t=this;e.forEach((function(e){return t.insert(e)}))},this.getHeight=function(){if(this.empty())return 0;var e=function(t){return t?Math.max(e(t.leftChild),e(t.rightChild))+1:1};return e(a)};var w=function(e){return r(this,(function(t){switch(t.label){case 0:return e&&void 0!==e.key?[5,o(w(e.leftChild))]:[2];case 1:return t.sent(),[4,e.key];case 2:return t.sent(),[5,o(w(e.rightChild))];case 3:return t.sent(),[2]}}))};this[Symbol.iterator]=function(){return w(a)},e.forEach((function(e){return n.insert(e)})),Object.freeze(this)}Object.freeze(i),n.default=i},{"../Base/TreeNode":25}],34:[function(e,t,n){function r(e){var t=this;void 0===e&&(e=[]);var n=0,r=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,r.length=0},this.push=function(e){r.push(e),++n},this.pop=function(){r.pop(),n>0&&--n},this.top=function(){return r[n-1]},e.forEach((function(e){return t.push(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(r),n.default=r},{}],35:[function(e,t,n){var r=this&&this.__generator||function(e,t){var n,r,o,s,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(e){return function(t){return c([e,t])}}function c(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&s[0]?r.return:s[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,s[1])).done)return o;switch(r=0,o&&(s=[2&s[0],o.value]),s[0]){case 0:case 1:o=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((o=(o=i.trys).length>0&&o[o.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!o||s[1]>o[0]&&s[1]<o[3])){i.label=s[1];break}if(6===s[0]&&i.label<o[1]){i.label=o[1],o=s;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(s);break}o[2]&&i.ops.pop(),i.trys.pop();continue}s=t.call(e,i)}catch(e){s=[6,e],r=0}finally{n=o=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}},o=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,s=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)i.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(o)throw o.error}}return i},s=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,s=t.length;o<s;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},i=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function a(e){var t=this;void 0===e&&(e=[]);var n=0,a=[];this.size=function(){return n},this.empty=function(){return 0===n},this.clear=function(){n=0,a.length=0},this.front=function(){if(!this.empty())return a[0]},this.back=function(){if(!this.empty())return a[n-1]},this.forEach=function(e){a.forEach(e)},this.getElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");return a[e]},this.eraseElementByPos=function(e){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");for(var t=e;t<n-1;++t)a[t]=a[t+1];this.popBack()},this.eraseElementByValue=function(e){var t=[];this.forEach((function(n){n!==e&&t.push(n)})),t.forEach((function(e,t){a[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.pushBack=function(e){a.push(e),++n},this.popBack=function(){a.pop(),n>0&&--n},this.setElementByPos=function(e,t){if(e<0||e>=n)throw new Error("pos must more than 0 and less than vector's size");a[e]=t},this.insert=function(e,t,r){if(void 0===r&&(r=1),e<0||e>n)throw new Error("pos must more than 0 and less than or equal to vector's size");a.splice.apply(a,s([e,0],o(new Array(r).fill(t)),!1)),n+=r},this.find=function(e){return a.includes(e)},this.reverse=function(){a.reverse()},this.unique=function(){var e,t=[];this.forEach((function(n,r){0!==r&&n===e||(t.push(n),e=n)})),t.forEach((function(e,t){a[t]=e}));for(var r=t.length;n>r;)this.popBack()},this.sort=function(e){a.sort(e)},this[Symbol.iterator]=function(){return function(){return r(this,(function(e){switch(e.label){case 0:return[5,i(a)];case 1:return[2,e.sent()]}}))}()},e.forEach((function(e){return t.pushBack(e)})),Object.freeze(this)}Object.defineProperty(n,"__esModule",{value:!0}),Object.freeze(a),n.default=a},{}],36:[function(e,t,n){Object.defineProperty(n,"__esModule",{value:!0}),n.HashMap=n.HashSet=n.Map=n.Set=n.PriorityQueue=n.Deque=n.LinkList=n.Queue=n.Stack=n.Vector=void 0;var r=e("./Vector/Vector");n.Vector=r.default;var o=e("./Stack/Stack");n.Stack=o.default;var s=e("./Queue/Queue");n.Queue=s.default;var i=e("./LinkList/LinkList");n.LinkList=i.default;var a=e("./Deque/Deque");n.Deque=a.default;var c=e("./PriorityQueue/PriorityQueue");n.PriorityQueue=c.default;var l=e("./Set/Set");n.Set=l.default;var u=e("./Map/Map");n.Map=u.default;var d=e("./HashSet/HashSet");n.HashSet=d.default;var h=e("./HashMap/HashMap");n.HashMap=h.default},{"./Deque/Deque":26,"./HashMap/HashMap":27,"./HashSet/HashSet":28,"./LinkList/LinkList":29,"./Map/Map":30,"./PriorityQueue/PriorityQueue":31,"./Queue/Queue":32,"./Set/Set":33,"./Stack/Stack":34,"./Vector/Vector":35}],37:[function(e,t,n){const r=e("yallist"),o=Symbol("max"),s=Symbol("length"),i=Symbol("lengthCalculator"),a=Symbol("allowStale"),c=Symbol("maxAge"),l=Symbol("dispose"),u=Symbol("noDisposeOnSet"),d=Symbol("lruList"),h=Symbol("cache"),f=Symbol("updateAgeOnGet"),p=()=>1;class g{constructor(e){if("number"==typeof e&&(e={max:e}),e||(e={}),e.max&&("number"!=typeof e.max||e.max<0))throw new TypeError("max must be a non-negative number");this[o]=e.max||1/0;const t=e.length||p;if(this[i]="function"!=typeof t?p:t,this[a]=e.stale||!1,e.maxAge&&"number"!=typeof e.maxAge)throw new TypeError("maxAge must be a number");this[c]=e.maxAge||0,this[l]=e.dispose,this[u]=e.noDisposeOnSet||!1,this[f]=e.updateAgeOnGet||!1,this.reset()}set max(e){if("number"!=typeof e||e<0)throw new TypeError("max must be a non-negative number");this[o]=e||1/0,v(this)}get max(){return this[o]}set allowStale(e){this[a]=!!e}get allowStale(){return this[a]}set maxAge(e){if("number"!=typeof e)throw new TypeError("maxAge must be a non-negative number");this[c]=e,v(this)}get maxAge(){return this[c]}set lengthCalculator(e){"function"!=typeof e&&(e=p),e!==this[i]&&(this[i]=e,this[s]=0,this[d].forEach((e=>{e.length=this[i](e.value,e.key),this[s]+=e.length}))),v(this)}get lengthCalculator(){return this[i]}get length(){return this[s]}get itemCount(){return this[d].length}rforEach(e,t){t=t||this;for(let n=this[d].tail;null!==n;){const r=n.prev;C(this,e,n,t),n=r}}forEach(e,t){t=t||this;for(let n=this[d].head;null!==n;){const r=n.next;C(this,e,n,t),n=r}}keys(){return this[d].toArray().map((e=>e.key))}values(){return this[d].toArray().map((e=>e.value))}reset(){this[l]&&this[d]&&this[d].length&&this[d].forEach((e=>this[l](e.key,e.value))),this[h]=new Map,this[d]=new r,this[s]=0}dump(){return this[d].map((e=>!y(this,e)&&{k:e.key,v:e.value,e:e.now+(e.maxAge||0)})).toArray().filter((e=>e))}dumpLru(){return this[d]}set(e,t,n){if((n=n||this[c])&&"number"!=typeof n)throw new TypeError("maxAge must be a number");const r=n?Date.now():0,a=this[i](t,e);if(this[h].has(e)){if(a>this[o])return b(this,this[h].get(e)),!1;const i=this[h].get(e).value;return this[l]&&(this[u]||this[l](e,i.value)),i.now=r,i.maxAge=n,i.value=t,this[s]+=a-i.length,i.length=a,this.get(e),v(this),!0}const f=new w(e,t,a,r,n);return f.length>this[o]?(this[l]&&this[l](e,t),!1):(this[s]+=f.length,this[d].unshift(f),this[h].set(e,this[d].head),v(this),!0)}has(e){if(!this[h].has(e))return!1;const t=this[h].get(e).value;return!y(this,t)}get(e){return m(this,e,!0)}peek(e){return m(this,e,!1)}pop(){const e=this[d].tail;return e?(b(this,e),e.value):null}del(e){b(this,this[h].get(e))}load(e){this.reset();const t=Date.now();for(let n=e.length-1;n>=0;n--){const r=e[n],o=r.e||0;if(0===o)this.set(r.k,r.v);else{const e=o-t;e>0&&this.set(r.k,r.v,e)}}}prune(){this[h].forEach(((e,t)=>m(this,t,!1)))}}const m=(e,t,n)=>{const r=e[h].get(t);if(r){const t=r.value;if(y(e,t)){if(b(e,r),!e[a])return}else n&&(e[f]&&(r.value.now=Date.now()),e[d].unshiftNode(r));return t.value}},y=(e,t)=>{if(!t||!t.maxAge&&!e[c])return!1;const n=Date.now()-t.now;return t.maxAge?n>t.maxAge:e[c]&&n>e[c]},v=e=>{if(e[s]>e[o])for(let t=e[d].tail;e[s]>e[o]&&null!==t;){const n=t.prev;b(e,t),t=n}},b=(e,t)=>{if(t){const n=t.value;e[l]&&e[l](n.key,n.value),e[s]-=n.length,e[h].delete(n.key),e[d].removeNode(t)}};class w{constructor(e,t,n,r,o){this.key=e,this.value=t,this.length=n,this.now=r,this.maxAge=o||0}}const C=(e,t,n,r)=>{let o=n.value;y(e,o)&&(b(e,n),e[a]||(o=void 0)),o&&t.call(r,o.value,o.key,e)};t.exports=g},{yallist:83}],38:[function(e,t,n){(function(e){(function(){const n=t.exports;n.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=e.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=e.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=e.from([n.codes.connect<<n.CMD_SHIFT]),n.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function r(t){return[0,1,2].map((r=>[0,1].map((o=>[0,1].map((s=>{const i=e.alloc(1);return i.writeUInt8(n.codes[t]<<n.CMD_SHIFT|(o?n.DUP_MASK:0)|r<<n.QOS_SHIFT|s,0,!0),i}))))))}n.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},n.PUBLISH_HEADER=r("publish"),n.SUBSCRIBE_HEADER=r("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=r("unsubscribe"),n.ACKS={unsuback:r("unsuback"),puback:r("puback"),pubcomp:r("pubcomp"),pubrel:r("pubrel"),pubrec:r("pubrec")},n.SUBACK_HEADER=e.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=e.from([3]),n.VERSION4=e.from([4]),n.VERSION5=e.from([5]),n.VERSION131=e.from([131]),n.VERSION132=e.from([132]),n.QOS=[0,1,2].map((t=>e.from([t]))),n.EMPTY={pingreq:e.from([n.codes.pingreq<<4,0]),pingresp:e.from([n.codes.pingresp<<4,0]),disconnect:e.from([n.codes.disconnect<<4,0])}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],39:[function(e,t,n){(function(n){(function(){const r=e("./writeToStream"),o=e("events");function s(e,t){const n=new i;return r(e,n,t),n.concat()}class i extends o{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let o,s=0;for(o=0;o<r.length&&void 0!==r[o];o++)"string"!=typeof r[o]?t[o]=r[o].length:t[o]=n.byteLength(r[o]),e+=t[o];const i=n.allocUnsafe(e);for(o=0;o<r.length&&void 0!==r[o];o++)"string"!=typeof r[o]?(r[o].copy(i,s),s+=t[o]):(i.write(r[o],s),s+=t[o]);return i}}t.exports=s}).call(this)}).call(this,e("buffer").Buffer)},{"./writeToStream":44,buffer:17,events:22}],40:[function(e,t,n){n.parser=e("./parser").parser,n.generate=e("./generate"),n.writeToStream=e("./writeToStream")},{"./generate":39,"./parser":43,"./writeToStream":44}],41:[function(e,t,n){(function(e){(function(){const n=65536,r={},o=e.isBuffer(e.from([1,2]).subarray(0,1));function s(t){const n=e.allocUnsafe(2);return n.writeUInt8(t>>8,0),n.writeUInt8(255&t,1),n}function i(){for(let e=0;e<n;e++)r[e]=s(e)}function a(t){const n=4;let r=0,s=0;const i=e.allocUnsafe(n);do{r=t%128|0,(t=t/128|0)>0&&(r|=128),i.writeUInt8(r,s++)}while(t>0&&s<n);return t>0&&(s=0),o?i.subarray(0,s):i.slice(0,s)}function c(t){const n=e.allocUnsafe(4);return n.writeUInt32BE(t,0),n}t.exports={cache:r,generateCache:i,generateNumber:s,genBufVariableByteInt:a,generate4ByteBuffer:c}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],42:[function(e,t,n){class r{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}t.exports=r},{}],43:[function(e,t,n){const r=e("bl"),o=e("events"),s=e("./packet"),i=e("./constants"),a=e("debug")("mqtt-packet:parser");class c extends o{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){a("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new s,this.error=null,this._list=r(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),a("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,a("parse: state complete. _stateCounter is now: %d",this._stateCounter),a("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return a("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0);return this.packet.cmd=i.types[e>>i.CMD_SHIFT],this.packet.retain=0!=(e&i.RETAIN_MASK),this.packet.qos=e>>i.QOS_SHIFT&i.QOS_MASK,this.packet.dup=0!=(e&i.DUP_MASK),a("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),a("_parseLength %d",e.value),!!e}_parsePayload(){a("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return a("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,n,r;a("_parseConnect");const o={},s=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(s.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(s.protocolVersion=this._list.readUInt8(this._pos),s.protocolVersion>=128&&(s.bridgeMode=!0,s.protocolVersion=s.protocolVersion-128),3!==s.protocolVersion&&4!==s.protocolVersion&&5!==s.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(o.username=this._list.readUInt8(this._pos)&i.USERNAME_MASK,o.password=this._list.readUInt8(this._pos)&i.PASSWORD_MASK,o.will=this._list.readUInt8(this._pos)&i.WILL_FLAG_MASK,o.will&&(s.will={},s.will.retain=0!=(this._list.readUInt8(this._pos)&i.WILL_RETAIN_MASK),s.will.qos=(this._list.readUInt8(this._pos)&i.WILL_QOS_MASK)>>i.WILL_QOS_SHIFT),s.clean=0!=(this._list.readUInt8(this._pos)&i.CLEAN_SESSION_MASK),this._pos++,s.keepalive=this._parseNum(),-1===s.keepalive)return this._emitError(new Error("Packet too short"));if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.properties=e)}const l=this._parseString();if(null===l)return this._emitError(new Error("Packet too short"));if(s.clientId=l,a("_parseConnect: packet.clientId: %s",s.clientId),o.will){if(5===s.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(s.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(s.will.topic=e,a("_parseConnect: packet.will.topic: %s",s.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));s.will.payload=t,a("_parseConnect: packet.will.paylaod: %s",s.will.payload)}if(o.username){if(r=this._parseString(),null===r)return this._emitError(new Error("Cannot parse username"));s.username=r,a("_parseConnect: packet.username: %s",s.username)}if(o.password){if(n=this._parseBuffer(),null===n)return this._emitError(new Error("Cannot parse password"));s.password=n}return this.settings=s,a("_parseConnect: complete"),s}_parseConnack(){a("_parseConnack");const e=this.packet;if(this._list.length<1)return null;if(e.sessionPresent=!!(this._list.readUInt8(this._pos++)&i.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}a("_parseConnack: complete")}_parsePublish(){a("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),a("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){a("_parseSubscribe");const e=this.packet;let t,n,r,o,s,c,l;if(1!==e.qos)return this._emitError(new Error("Wrong subscribe header"));if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));n=this._parseByte(),r=n&i.SUBSCRIBE_OPTIONS_QOS_MASK,c=0!=(n>>i.SUBSCRIBE_OPTIONS_NL_SHIFT&i.SUBSCRIBE_OPTIONS_NL_MASK),s=0!=(n>>i.SUBSCRIBE_OPTIONS_RAP_SHIFT&i.SUBSCRIBE_OPTIONS_RAP_MASK),o=n>>i.SUBSCRIBE_OPTIONS_RH_SHIFT&i.SUBSCRIBE_OPTIONS_RH_MASK,l={topic:t,qos:r},5===this.settings.protocolVersion?(l.nl=c,l.rap=s,l.rh=o):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),a("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){a("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseUnsubscribe(){a("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));a("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){a("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;)this.packet.granted.push(this._list.readUInt8(this._pos++))}}_parseConfirmation(){a("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion&&(e.length>2?(e.reasonCode=this._parseByte(),a("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)):e.reasonCode=0,e.length>3)){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return!0}_parseDisconnect(){const e=this.packet;if(a("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?e.reasonCode=this._parseByte():e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return a("_parseDisconnect result: true"),!0}_parseAuth(){a("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));e.reasonCode=this._parseByte();const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),a("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(a("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),n=t+this._pos;if(-1===t||n>this._list.length||n>this.packet.length)return null;const r=this._list.toString("utf8",this._pos,n);return this._pos+=t,a("_parseString: result: %s",r),r}_parseStringPair(){return a("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const n=this._list.slice(this._pos,t);return this._pos+=e,a("_parseBuffer: result: %o",n),n}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,a("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,a("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){a("_parseVarByteNum");const t=4;let n,r=0,o=1,s=0,c=!1;const l=this._pos?this._pos:0;for(;r<t&&l+r<this._list.length;){if(n=this._list.readUInt8(l+r++),s+=o*(n&i.VARBYTEINT_MASK),o*=128,0==(n&i.VARBYTEINT_FIN_MASK)){c=!0;break}if(this._list.length<=r)break}return!c&&r===t&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),l&&(this._pos+=r),c=!!c&&(e?{bytes:r,value:s}:s),a("_parseVarByteNum: result: %o",c),c}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),a("_parseByte: result: %o",e),e}_parseByType(e){switch(a("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){a("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,n={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=i.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"!==t)n[t]?(Array.isArray(n[t])||(n[t]=[n[t]]),n[t].push(this._parseByType(i.propertiesTypes[t]))):n[t]=this._parseByType(i.propertiesTypes[t]);else{n[t]||(n[t]=Object.create(null));const e=this._parseByType(i.propertiesTypes[t]);if(n[t][e.name])if(Array.isArray(n[t][e.name]))n[t][e.name].push(e.value);else{const r=n[t][e.name];n[t][e.name]=[r],n[t][e.name].push(e.value)}else n[t][e.name]=e.value}}return n}_newPacket(){return a("_newPacket"),this.packet&&(this._list.consume(this.packet.length),a("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),a("_newPacket: new packet"),this.packet=new s,this._pos=0,!0}_emitError(e){a("_emitError"),this.error=e,this.emit("error",e)}}t.exports=c},{"./constants":38,"./packet":42,bl:15,debug:18,events:22}],44:[function(e,t,n){(function(n){(function(){const r=e("./constants"),o=n.allocUnsafe(0),s=n.from([0]),i=e("./numbers"),a=e("process-nextick-args").nextTick,c=e("debug")("mqtt-packet:writeToStream"),l=i.cache,u=i.generateNumber,d=i.generateCache,h=i.genBufVariableByteInt,f=i.generate4ByteBuffer;let p=M,g=!0;function m(e,t,n){switch(c("generate called"),t.cork&&(t.cork(),a(y,t)),g&&(g=!1,d()),c("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return v(e,t);case"connack":return b(e,t,n);case"publish":return w(e,t,n);case"puback":case"pubrec":case"pubrel":case"pubcomp":return C(e,t,n);case"subscribe":return _(e,t,n);case"suback":return k(e,t,n);case"unsubscribe":return S(e,t,n);case"unsuback":return A(e,t,n);case"pingreq":case"pingresp":return E(e,t);case"disconnect":return I(e,t,n);case"auth":return O(e,t,n);default:return t.emit("error",new Error("Unknown command")),!1}}function y(e){e.uncork()}function v(e,t,o){const s=e||{},i=s.protocolId||"MQTT";let a=s.protocolVersion||4;const c=s.will;let l=s.clean;const u=s.keepalive||0,d=s.clientId||"",h=s.username,f=s.password,g=s.properties;void 0===l&&(l=!0);let m=0;if(!i||"string"!=typeof i&&!n.isBuffer(i))return t.emit("error",new Error("Invalid protocolId")),!1;if(m+=i.length+2,3!==a&&4!==a&&5!==a)return t.emit("error",new Error("Invalid protocol version")),!1;if(m+=1,("string"==typeof d||n.isBuffer(d))&&(d||a>=4)&&(d||l))m+=n.byteLength(d)+2;else{if(a<4)return t.emit("error",new Error("clientId must be supplied before 3.1.1")),!1;if(1*l==0)return t.emit("error",new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof u||u<0||u>65535||u%1!=0)return t.emit("error",new Error("Invalid keepalive")),!1;if(m+=2,m+=1,5===a){var y=N(t,g);if(!y)return!1;m+=y.length}if(c){if("object"!=typeof c)return t.emit("error",new Error("Invalid will")),!1;if(!c.topic||"string"!=typeof c.topic)return t.emit("error",new Error("Invalid will topic")),!1;if(m+=n.byteLength(c.topic)+2,m+=2,c.payload){if(!(c.payload.length>=0))return t.emit("error",new Error("Invalid will payload")),!1;"string"==typeof c.payload?m+=n.byteLength(c.payload):m+=c.payload.length}var v={};if(5===a){if(!(v=N(t,c.properties)))return!1;m+=v.length}}let b=!1;if(null!=h){if(!$(h))return t.emit("error",new Error("Invalid username")),!1;b=!0,m+=n.byteLength(h)+2}if(null!=f){if(!b)return t.emit("error",new Error("Username is required to use password")),!1;if(!$(f))return t.emit("error",new Error("Invalid password")),!1;m+=q(f)+2}t.write(r.CONNECT_HEADER),x(t,m),B(t,i),s.bridgeMode&&(a+=128),t.write(131===a?r.VERSION131:132===a?r.VERSION132:4===a?r.VERSION4:5===a?r.VERSION5:r.VERSION3);let w=0;return w|=null!=h?r.USERNAME_MASK:0,w|=null!=f?r.PASSWORD_MASK:0,w|=c&&c.retain?r.WILL_RETAIN_MASK:0,w|=c&&c.qos?c.qos<<r.WILL_QOS_SHIFT:0,w|=c?r.WILL_FLAG_MASK:0,w|=l?r.CLEAN_SESSION_MASK:0,t.write(n.from([w])),p(t,u),5===a&&y.write(),B(t,d),c&&(5===a&&v.write(),R(t,c.topic),B(t,c.payload)),null!=h&&B(t,h),null!=f&&B(t,f),!0}function b(e,t,o){const i=o?o.protocolVersion:4,a=e||{},c=5===i?a.reasonCode:a.returnCode,l=a.properties;let u=2;if("number"!=typeof c)return t.emit("error",new Error("Invalid return code")),!1;let d=null;if(5===i){if(d=N(t,l),!d)return!1;u+=d.length}return t.write(r.CONNACK_HEADER),x(t,u),t.write(a.sessionPresent?r.SESSIONPRESENT_HEADER:s),t.write(n.from([c])),null!=d&&d.write(),!0}function w(e,t,s){c("publish: packet: %o",e);const i=s?s.protocolVersion:4,a=e||{},l=a.qos||0,u=a.retain?r.RETAIN_MASK:0,d=a.topic,h=a.payload||o,f=a.messageId,g=a.properties;let m=0;if("string"==typeof d)m+=n.byteLength(d)+2;else{if(!n.isBuffer(d))return t.emit("error",new Error("Invalid topic")),!1;m+=d.length+2}if(n.isBuffer(h)?m+=h.length:m+=n.byteLength(h),l&&"number"!=typeof f)return t.emit("error",new Error("Invalid messageId")),!1;l&&(m+=2);let y=null;if(5===i){if(y=N(t,g),!y)return!1;m+=y.length}return t.write(r.PUBLISH_HEADER[l][a.dup?1:0][u?1:0]),x(t,m),p(t,q(d)),t.write(d),l>0&&p(t,f),null!=y&&y.write(),c("publish: payload: %o",h),t.write(h)}function C(e,t,o){const s=o?o.protocolVersion:4,i=e||{},a=i.cmd||"puback",c=i.messageId,l=i.dup&&"pubrel"===a?r.DUP_MASK:0;let u=0;const d=i.reasonCode,h=i.properties;let f=5===s?3:2;if("pubrel"===a&&(u=1),"number"!=typeof c)return t.emit("error",new Error("Invalid messageId")),!1;let g=null;if(5===s&&"object"==typeof h){if(g=U(t,h,o,f),!g)return!1;f+=g.length}return t.write(r.ACKS[a][u][l][0]),x(t,f),p(t,c),5===s&&t.write(n.from([d])),null!==g&&g.write(),!0}function _(e,t,o){c("subscribe: packet: ");const s=o?o.protocolVersion:4,i=e||{},a=i.dup?r.DUP_MASK:0,l=i.messageId,u=i.subscriptions,d=i.properties;let h=0;if("number"!=typeof l)return t.emit("error",new Error("Invalid messageId")),!1;h+=2;let f=null;if(5===s){if(f=N(t,d),!f)return!1;h+=f.length}if("object"!=typeof u||!u.length)return t.emit("error",new Error("Invalid subscriptions")),!1;for(let e=0;e<u.length;e+=1){const r=u[e].topic,o=u[e].qos;if("string"!=typeof r)return t.emit("error",new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof o)return t.emit("error",new Error("Invalid subscriptions - invalid qos")),!1;if(5===s){if("boolean"!=typeof(u[e].nl||!1))return t.emit("error",new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(u[e].rap||!1))return t.emit("error",new Error("Invalid subscriptions - invalid Retain as Published")),!1;const n=u[e].rh||0;if("number"!=typeof n||n>2)return t.emit("error",new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=n.byteLength(r)+2+1}c("subscribe: writing to stream: %o",r.SUBSCRIBE_HEADER),t.write(r.SUBSCRIBE_HEADER[1][a?1:0][0]),x(t,h),p(t,l),null!==f&&f.write();let g=!0;for(const e of u){const o=e.topic,i=e.qos,a=+e.nl,c=+e.rap,l=e.rh;let u;R(t,o),u=r.SUBSCRIBE_OPTIONS_QOS[i],5===s&&(u|=a?r.SUBSCRIBE_OPTIONS_NL:0,u|=c?r.SUBSCRIBE_OPTIONS_RAP:0,u|=l?r.SUBSCRIBE_OPTIONS_RH[l]:0),g=t.write(n.from([u]))}return g}function k(e,t,o){const s=o?o.protocolVersion:4,i=e||{},a=i.messageId,c=i.granted,l=i.properties;let u=0;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(u+=2,"object"!=typeof c||!c.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.emit("error",new Error("Invalid qos vector")),!1;u+=1}let d=null;if(5===s){if(d=U(t,l,o,u),!d)return!1;u+=d.length}return t.write(r.SUBACK_HEADER),x(t,u),p(t,a),null!==d&&d.write(),t.write(n.from(c))}function S(e,t,o){const s=o?o.protocolVersion:4,i=e||{},a=i.messageId,c=i.dup?r.DUP_MASK:0,l=i.unsubscriptions,u=i.properties;let d=0;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(d+=2,"object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.emit("error",new Error("Invalid unsubscriptions")),!1;d+=n.byteLength(l[e])+2}let h=null;if(5===s){if(h=N(t,u),!h)return!1;d+=h.length}t.write(r.UNSUBSCRIBE_HEADER[1][c?1:0][0]),x(t,d),p(t,a),null!==h&&h.write();let f=!0;for(let e=0;e<l.length;e++)f=R(t,l[e]);return f}function A(e,t,o){const s=o?o.protocolVersion:4,i=e||{},a=i.messageId,c=i.dup?r.DUP_MASK:0,l=i.granted,u=i.properties,d=i.cmd,h=0;let f=2;if("number"!=typeof a)return t.emit("error",new Error("Invalid messageId")),!1;if(5===s){if("object"!=typeof l||!l.length)return t.emit("error",new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.emit("error",new Error("Invalid qos vector")),!1;f+=1}}let g=null;if(5===s){if(g=U(t,u,o,f),!g)return!1;f+=g.length}return t.write(r.ACKS[d][h][c][0]),x(t,f),p(t,a),null!==g&&g.write(),5===s&&t.write(n.from(l)),!0}function E(e,t,n){return t.write(r.EMPTY[e.cmd])}function I(e,t,o){const s=o?o.protocolVersion:4,i=e||{},a=i.reasonCode,c=i.properties;let l=5===s?1:0,u=null;if(5===s){if(u=U(t,c,o,l),!u)return!1;l+=u.length}return t.write(n.from([r.codes.disconnect<<4])),x(t,l),5===s&&t.write(n.from([a])),null!==u&&u.write(),!0}function O(e,t,o){const s=o?o.protocolVersion:4,i=e||{},a=i.reasonCode,c=i.properties;let l=5===s?1:0;5!==s&&t.emit("error",new Error("Invalid mqtt version for auth packet"));const u=U(t,c,o,l);return!!u&&(l+=u.length,t.write(n.from([r.codes.auth<<4])),x(t,l),t.write(n.from([a])),null!==u&&u.write(),!0)}Object.defineProperty(m,"cacheNumbers",{get:()=>p===M,set(e){e?(l&&0!==Object.keys(l).length||(g=!0),p=M):(g=!1,p=j)}});const T={};function x(e,t){if(t>r.VARBYTEINT_MAX)return e.emit("error",new Error(`Invalid variable byte integer: ${t}`)),!1;let n=T[t];return n||(n=h(t),t<16384&&(T[t]=n)),c("writeVarByteInt: writing to stream: %o",n),e.write(n)}function R(e,t){const r=n.byteLength(t);return p(e,r),c("writeString: %s",t),e.write(t,"utf8")}function P(e,t,n){R(e,t),R(e,n)}function M(e,t){return c("writeNumberCached: number: %d",t),c("writeNumberCached: %o",l[t]),e.write(l[t])}function j(e,t){const n=u(t);return c("writeNumberGenerated: %o",n),e.write(n)}function F(e,t){const n=f(t);return c("write4ByteNumber: %o",n),e.write(n)}function B(e,t){"string"==typeof t?R(e,t):t?(p(e,t.length),e.write(t)):p(e,0)}function N(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){L(e,{},0)}};let o=0;function s(t,o){let s=0;switch(r.propertiesTypes[t]){case"byte":if("boolean"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=2;break;case"int8":if("number"!=typeof o||o<0||o>255)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=2;break;case"binary":if(o&&null===o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=1+n.byteLength(o)+2;break;case"int16":if("number"!=typeof o||o<0||o>65535)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=3;break;case"int32":if("number"!=typeof o||o<0||o>4294967295)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=5;break;case"var":if("number"!=typeof o||o<0||o>268435455)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=1+n.byteLength(h(o));break;case"string":if("string"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=3+n.byteLength(o.toString());break;case"pair":if("object"!=typeof o)return e.emit("error",new Error(`Invalid ${t}: ${o}`)),!1;s+=Object.getOwnPropertyNames(o).reduce(((e,t)=>{const r=o[t];return Array.isArray(r)?e+=r.reduce(((e,r)=>e+=3+n.byteLength(t.toString())+2+n.byteLength(r.toString())),0):e+=3+n.byteLength(t.toString())+2+n.byteLength(o[t].toString()),e}),0);break;default:return e.emit("error",new Error(`Invalid property ${t}: ${o}`)),!1}return s}if(t)for(const e in t){let n=0,r=0;const i=t[e];if(Array.isArray(i))for(let t=0;t<i.length;t++){if(r=s(e,i[t]),!r)return!1;n+=r}else{if(r=s(e,i),!r)return!1;n=r}if(!n)return!1;o+=n}return{length:n.byteLength(h(o))+o,write(){L(e,t,o)}}}function U(e,t,n,r){const o=["reasonString","userProperties"],s=n&&n.properties&&n.properties.maximumPacketSize?n.properties.maximumPacketSize:0;let i=N(e,t);if(s)for(;r+i.length>s;){const n=o.shift();if(!n||!t[n])return!1;delete t[n],i=N(e,t)}return i}function D(e,t,o){switch(r.propertiesTypes[t]){case"byte":e.write(n.from([r.properties[t]])),e.write(n.from([+o]));break;case"int8":e.write(n.from([r.properties[t]])),e.write(n.from([o]));break;case"binary":e.write(n.from([r.properties[t]])),B(e,o);break;case"int16":e.write(n.from([r.properties[t]])),p(e,o);break;case"int32":e.write(n.from([r.properties[t]])),F(e,o);break;case"var":e.write(n.from([r.properties[t]])),x(e,o);break;case"string":e.write(n.from([r.properties[t]])),R(e,o);break;case"pair":Object.getOwnPropertyNames(o).forEach((s=>{const i=o[s];Array.isArray(i)?i.forEach((o=>{e.write(n.from([r.properties[t]])),P(e,s.toString(),o.toString())})):(e.write(n.from([r.properties[t]])),P(e,s.toString(),i.toString()))}));break;default:return e.emit("error",new Error(`Invalid property ${t} value: ${o}`)),!1}}function L(e,t,n){x(e,n);for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&null!==t[n]){const r=t[n];if(Array.isArray(r))for(let t=0;t<r.length;t++)D(e,n,r[t]);else D(e,n,r)}}function q(e){return e?e instanceof n?e.length:n.byteLength(e):0}function $(e){return"string"==typeof e||e instanceof n}t.exports=m}).call(this)}).call(this,e("buffer").Buffer)},{"./constants":38,"./numbers":41,buffer:17,debug:18,"process-nextick-args":49}],45:[function(e,t,n){var r=1e3,o=60*r,s=60*o,i=24*s,a=7*i,c=365.25*i;function l(e){if(!((e=String(e)).length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"weeks":case"week":case"w":return n*a;case"days":case"day":case"d":return n*i;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*o;case"seconds":case"second":case"secs":case"sec":case"s":return n*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function u(e){var t=Math.abs(e);return t>=i?Math.round(e/i)+"d":t>=s?Math.round(e/s)+"h":t>=o?Math.round(e/o)+"m":t>=r?Math.round(e/r)+"s":e+"ms"}function d(e){var t=Math.abs(e);return t>=i?h(e,t,i,"day"):t>=s?h(e,t,s,"hour"):t>=o?h(e,t,o,"minute"):t>=r?h(e,t,r,"second"):e+" ms"}function h(e,t,n,r){var o=t>=1.5*n;return Math.round(e/n)+" "+r+(o?"s":"")}t.exports=function(e,t){t=t||{};var n=typeof e;if("string"===n&&e.length>0)return l(e);if("number"===n&&isFinite(e))return t.long?d(e):u(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},{}],46:[function(e,t,n){const r=e("./lib/number-allocator.js");t.exports.NumberAllocator=r},{"./lib/number-allocator.js":47}],47:[function(e,t,n){const r=e("js-sdsl").Set,o=e("debug")("number-allocator:trace"),s=e("debug")("number-allocator:error");function i(e,t){this.low=e,this.high=t}function a(e,t){if(!(this instanceof a))return new a(e,t);this.min=e,this.max=t,this.ss=new r([],((e,t)=>e.compare(t))),o("Create"),this.clear()}i.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},i.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},a.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},a.prototype.alloc=function(){if(0===this.ss.size())return o("alloc():empty"),null;const e=this.ss.front(),t=e.low;return t+1<=e.high?++e.low:this.ss.eraseElementByPos(0),o("alloc():"+t),t},a.prototype.use=function(e){const t=new i(e,e),n=this.ss.lowerBound(t);if(n){if(n.equals(t))return this.ss.eraseElementByValue(n),o("use():"+e),!0;if(n.low>e)return!1;if(n.low===e)return++n.low,o("use():"+e),!0;if(n.high===e)return--n.high,o("use():"+e),!0;const r=n.low;return n.low=e+1,this.ss.insert(new i(r,e-1)),o("use():"+e),!0}return o("use():failed"),!1},a.prototype.free=function(e){if(e<this.min||e>this.max)return void s("free():"+e+" is out of range");const t=new i(e,e),n=this.ss.lowerBound(t);if(n){if(n.low<=e&&e<=n.high)return void s("free():"+e+" has already been vacant");if(n===this.ss.front())e+1===n.low?--n.low:this.ss.insert(t);else{const r=this.ss.reverseLowerBound(t);r.high+1===e?e+1===n.low?(this.ss.eraseElementByValue(r),n.low=r.low):r.high=e:e+1===n.low?n.low=e:this.ss.insert(t)}}else{if(n===this.ss.front())return void this.ss.insert(t);const r=this.ss.reverseLowerBound(t);r.high+1===e?r.high=e:this.ss.insert(t)}o("free():"+e)},a.prototype.clear=function(){o("clear()"),this.ss.clear(),this.ss.insert(new i(this.min,this.max))},a.prototype.intervalCount=function(){return this.ss.size()},a.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},t.exports=a},{debug:18,"js-sdsl":36}],48:[function(e,t,n){var r=e("wrappy");function o(e){var t=function(){return t.called?t.value:(t.called=!0,t.value=e.apply(this,arguments))};return t.called=!1,t}function s(e){var t=function(){if(t.called)throw new Error(t.onceError);return t.called=!0,t.value=e.apply(this,arguments)},n=e.name||"Function wrapped with `once`";return t.onceError=n+" shouldn't be called more than once",t.called=!1,t}t.exports=r(o),t.exports.strict=r(s),o.proto=o((function(){Object.defineProperty(Function.prototype,"once",{value:function(){return o(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return s(this)},configurable:!0})}))},{wrappy:79}],49:[function(e,t,n){(function(e){(function(){function n(t,n,r,o){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var s,i,a=arguments.length;switch(a){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick((function(){t.call(null,n)}));case 3:return e.nextTick((function(){t.call(null,n,r)}));case 4:return e.nextTick((function(){t.call(null,n,r,o)}));default:for(s=new Array(a-1),i=0;i<s.length;)s[i++]=arguments[i];return e.nextTick((function(){t.apply(null,s)}))}}void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:n}:t.exports=e}).call(this)}).call(this,e("_process"))},{_process:50}],50:[function(e,t,n){var r,o,s=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function c(e){if(r===setTimeout)return setTimeout(e,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function l(e){if(o===clearTimeout)return clearTimeout(e);if((o===a||!o)&&clearTimeout)return o=clearTimeout,clearTimeout(e);try{return o(e)}catch(t){try{return o.call(null,e)}catch(t){return o.call(this,e)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(e){r=i}try{o="function"==typeof clearTimeout?clearTimeout:a}catch(e){o=a}}();var u,d=[],h=!1,f=-1;function p(){h&&u&&(h=!1,u.length?d=u.concat(d):f=-1,d.length&&g())}function g(){if(!h){var e=c(p);h=!0;for(var t=d.length;t;){for(u=d,d=[];++f<t;)u&&u[f].run();f=-1,t=d.length}u=null,h=!1,l(e)}}function m(e,t){this.fun=e,this.array=t}function y(){}s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];d.push(new m(e,t)),1!==d.length||h||c(g)},m.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=y,s.addListener=y,s.once=y,s.off=y,s.removeListener=y,s.removeAllListeners=y,s.emit=y,s.prependListener=y,s.prependOnceListener=y,s.listeners=function(e){return[]},s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},{}],51:[function(e,t,n){(function(e){(function(){!function(r){var o="object"==typeof n&&n&&!n.nodeType&&n,s="object"==typeof t&&t&&!t.nodeType&&t,i="object"==typeof e&&e;i.global!==i&&i.window!==i&&i.self!==i||(r=i);var a,c,l=2147483647,u=36,d=1,h=26,f=38,p=700,g=72,m=128,y="-",v=/^xn--/,b=/[^\x20-\x7E]/,w=/[\x2E\u3002\uFF0E\uFF61]/g,C={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},_=u-d,k=Math.floor,S=String.fromCharCode;function A(e){throw new RangeError(C[e])}function E(e,t){for(var n=e.length,r=[];n--;)r[n]=t(e[n]);return r}function I(e,t){var n=e.split("@"),r="";return n.length>1&&(r=n[0]+"@",e=n[1]),r+E((e=e.replace(w,".")).split("."),t).join(".")}function O(e){for(var t,n,r=[],o=0,s=e.length;o<s;)(t=e.charCodeAt(o++))>=55296&&t<=56319&&o<s?56320==(64512&(n=e.charCodeAt(o++)))?r.push(((1023&t)<<10)+(1023&n)+65536):(r.push(t),o--):r.push(t);return r}function T(e){return E(e,(function(e){var t="";return e>65535&&(t+=S((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=S(e)})).join("")}function x(e){return e-48<10?e-22:e-65<26?e-65:e-97<26?e-97:u}function R(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function P(e,t,n){var r=0;for(e=n?k(e/p):e>>1,e+=k(e/t);e>_*h>>1;r+=u)e=k(e/_);return k(r+(_+1)*e/(e+f))}function M(e){var t,n,r,o,s,i,a,c,f,p,v=[],b=e.length,w=0,C=m,_=g;for((n=e.lastIndexOf(y))<0&&(n=0),r=0;r<n;++r)e.charCodeAt(r)>=128&&A("not-basic"),v.push(e.charCodeAt(r));for(o=n>0?n+1:0;o<b;){for(s=w,i=1,a=u;o>=b&&A("invalid-input"),((c=x(e.charCodeAt(o++)))>=u||c>k((l-w)/i))&&A("overflow"),w+=c*i,!(c<(f=a<=_?d:a>=_+h?h:a-_));a+=u)i>k(l/(p=u-f))&&A("overflow"),i*=p;_=P(w-s,t=v.length+1,0==s),k(w/t)>l-C&&A("overflow"),C+=k(w/t),w%=t,v.splice(w++,0,C)}return T(v)}function j(e){var t,n,r,o,s,i,a,c,f,p,v,b,w,C,_,E=[];for(b=(e=O(e)).length,t=m,n=0,s=g,i=0;i<b;++i)(v=e[i])<128&&E.push(S(v));for(r=o=E.length,o&&E.push(y);r<b;){for(a=l,i=0;i<b;++i)(v=e[i])>=t&&v<a&&(a=v);for(a-t>k((l-n)/(w=r+1))&&A("overflow"),n+=(a-t)*w,t=a,i=0;i<b;++i)if((v=e[i])<t&&++n>l&&A("overflow"),v==t){for(c=n,f=u;!(c<(p=f<=s?d:f>=s+h?h:f-s));f+=u)_=c-p,C=u-p,E.push(S(R(p+_%C,0))),c=k(_/C);E.push(S(R(c,0))),s=P(n,w,r==o),n=0,++r}++n,++t}return E.join("")}function F(e){return I(e,(function(e){return v.test(e)?M(e.slice(4).toLowerCase()):e}))}function B(e){return I(e,(function(e){return b.test(e)?"xn--"+j(e):e}))}if(a={version:"1.4.1",ucs2:{decode:O,encode:T},decode:M,encode:j,toASCII:B,toUnicode:F},o&&s)if(t.exports==o)s.exports=a;else for(c in a)a.hasOwnProperty(c)&&(o[c]=a[c]);else r.punycode=a}(this)}).call(this)}).call(this,void 0!==Ce?Ce:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],52:[function(e,t,n){function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,n,s){t=t||"&",n=n||"=";var i={};if("string"!=typeof e||0===e.length)return i;var a=/\+/g;e=e.split(t);var c=1e3;s&&"number"==typeof s.maxKeys&&(c=s.maxKeys);var l=e.length;c>0&&l>c&&(l=c);for(var u=0;u<l;++u){var d,h,f,p,g=e[u].replace(a,"%20"),m=g.indexOf(n);m>=0?(d=g.substr(0,m),h=g.substr(m+1)):(d=g,h=""),f=decodeURIComponent(d),p=decodeURIComponent(h),r(i,f)?o(i[f])?i[f].push(p):i[f]=[i[f],p]:i[f]=p}return i};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],53:[function(e,t,n){var r=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,n,a){return t=t||"&",n=n||"=",null===e&&(e=void 0),"object"==typeof e?s(i(e),(function(i){var a=encodeURIComponent(r(i))+n;return o(e[i])?s(e[i],(function(e){return a+encodeURIComponent(r(e))})).join(t):a+encodeURIComponent(r(e[i]))})).join(t):a?encodeURIComponent(r(a))+n+encodeURIComponent(r(e)):""};var o=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function s(e,t){if(e.map)return e.map(t);for(var n=[],r=0;r<e.length;r++)n.push(t(e[r],r));return n}var i=Object.keys||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t}},{}],54:[function(e,t,n){n.decode=n.parse=e("./decode"),n.encode=n.stringify=e("./encode")},{"./decode":52,"./encode":53}],55:[function(e,t,n){function r(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var o={};function s(e,t,n){function s(e,n,r){return"string"==typeof t?t:t(e,n,r)}n||(n=Error);var i=function(e){function t(t,n,r){return e.call(this,s(t,n,r))||this}return r(t,e),t}(n);i.prototype.name=n.name,i.prototype.code=e,o[e]=i}function i(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}function a(e,t,n){return e.substr(!n||n<0?0:+n,t.length)===t}function c(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t}function l(e,t,n){return"number"!=typeof n&&(n=0),!(n+t.length>e.length)&&-1!==e.indexOf(t,n)}s("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),s("ERR_INVALID_ARG_TYPE",(function(e,t,n){var r,o;if("string"==typeof t&&a(t,"not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be",c(e," argument"))o="The ".concat(e," ").concat(r," ").concat(i(t,"type"));else{var s=l(e,".")?"property":"argument";o='The "'.concat(e,'" ').concat(s," ").concat(r," ").concat(i(t,"type"))}return o+=". Received type ".concat(typeof n)}),TypeError),s("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),s("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),s("ERR_STREAM_PREMATURE_CLOSE","Premature close"),s("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),s("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),s("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),s("ERR_STREAM_WRITE_AFTER_END","write after end"),s("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),s("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),s("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=o},{}],56:[function(e,t,n){(function(n){(function(){var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};t.exports=l;var o=e("./_stream_readable"),s=e("./_stream_writable");e("inherits")(l,o);for(var i=r(s.prototype),a=0;a<i.length;a++){var c=i[a];l.prototype[c]||(l.prototype[c]=s.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);o.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",u)))}function u(){this._writableState.ended||n.nextTick(d,this)}function d(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})}).call(this)}).call(this,e("_process"))},{"./_stream_readable":58,"./_stream_writable":60,_process:50,inherits:24}],57:[function(e,t,n){t.exports=o;var r=e("./_stream_transform");function o(e){if(!(this instanceof o))return new o(e);r.call(this,e)}e("inherits")(o,r),o.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":59,inherits:24}],58:[function(e,t,n){(function(n,r){(function(){var o;t.exports=O,O.ReadableState=I,e("events").EventEmitter;var s=function(e,t){return e.listeners(t).length},i=e("./internal/streams/stream"),a=e("buffer").Buffer,c=r.Uint8Array||function(){};function l(e){return a.from(e)}function u(e){return a.isBuffer(e)||e instanceof c}var d,h=e("util");d=h&&h.debuglog?h.debuglog("stream"):function(){};var f,p,g,m=e("./internal/streams/buffer_list"),y=e("./internal/streams/destroy"),v=e("./internal/streams/state").getHighWaterMark,b=e("../errors").codes,w=b.ERR_INVALID_ARG_TYPE,C=b.ERR_STREAM_PUSH_AFTER_EOF,_=b.ERR_METHOD_NOT_IMPLEMENTED,k=b.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;e("inherits")(O,i);var S=y.errorOrDestroy,A=["error","close","destroy","pause","resume"];function E(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function I(t,n,r){o=o||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof o),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=v(this,t,"readableHighWaterMark",r),this.buffer=new m,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.paused=!0,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(f||(f=e("string_decoder/").StringDecoder),this.decoder=new f(t.encoding),this.encoding=t.encoding)}function O(t){if(o=o||e("./_stream_duplex"),!(this instanceof O))return new O(t);var n=this instanceof o;this._readableState=new I(t,this,n),this.readable=!0,t&&("function"==typeof t.read&&(this._read=t.read),"function"==typeof t.destroy&&(this._destroy=t.destroy)),i.call(this)}function T(e,t,n,r,o){d("readableAddChunk",t);var s,i=e._readableState;if(null===t)i.reading=!1,F(e,i);else if(o||(s=R(i,t)),s)S(e,s);else if(i.objectMode||t&&t.length>0)if("string"==typeof t||i.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=l(t)),r)i.endEmitted?S(e,new k):x(e,i,t,!0);else if(i.ended)S(e,new C);else{if(i.destroyed)return!1;i.reading=!1,i.decoder&&!n?(t=i.decoder.write(t),i.objectMode||0!==t.length?x(e,i,t,!1):U(e,i)):x(e,i,t,!1)}else r||(i.reading=!1,U(e,i));return!i.ended&&(i.length<i.highWaterMark||0===i.length)}function x(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&B(e)),U(e,t)}function R(e,t){var n;return u(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new w("chunk",["string","Buffer","Uint8Array"],t)),n}Object.defineProperty(O.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),O.prototype.destroy=y.destroy,O.prototype._undestroy=y.undestroy,O.prototype._destroy=function(e,t){t(e)},O.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=a.from(e,t),t=""),n=!0),T(this,e,t,!1,n)},O.prototype.unshift=function(e){return T(this,e,null,!0,!1)},O.prototype.isPaused=function(){return!1===this._readableState.flowing},O.prototype.setEncoding=function(t){f||(f=e("string_decoder/").StringDecoder);var n=new f(t);this._readableState.decoder=n,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,o="";null!==r;)o+=n.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==o&&this._readableState.buffer.push(o),this._readableState.length=o.length,this};var P=1073741824;function M(e){return e>=P?e=P:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function j(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=M(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function F(e,t){if(d("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?B(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,N(e)))}}function B(e){var t=e._readableState;d("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(d("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(N,e))}function N(e){var t=e._readableState;d("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,V(e)}function U(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(D,e,t))}function D(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(d("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function L(e){return function(){var t=e._readableState;d("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,V(e))}}function q(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function $(e){d("readable nexttick read 0"),e.read(0)}function z(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(H,e,t))}function H(e,t){d("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),V(e),t.flowing&&!t.reading&&e.read(0)}function V(e){var t=e._readableState;for(d("flow",t.flowing);t.flowing&&null!==e.read(););}function W(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function K(e){var t=e._readableState;d("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(Q,t,e))}function Q(e,t){if(d("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function J(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}O.prototype.read=function(e){d("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return d("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?K(this):B(this),null;if(0===(e=j(e,t))&&t.ended)return 0===t.length&&K(this),null;var r,o=t.needReadable;return d("need readable",o),(0===t.length||t.length-e<t.highWaterMark)&&d("length less than watermark",o=!0),t.ended||t.reading?d("reading or ended",o=!1):o&&(d("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=j(n,t))),null===(r=e>0?W(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&K(this)),null!==r&&this.emit("data",r),r},O.prototype._read=function(e){S(this,new _("_read()"))},O.prototype.pipe=function(e,t){var r=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,d("pipe count=%d opts=%j",o.pipesCount,t);var i=t&&!1===t.end||e===n.stdout||e===n.stderr?y:c;function a(e,t){d("onunpipe"),e===r&&t&&!1===t.hasUnpiped&&(t.hasUnpiped=!0,h())}function c(){d("onend"),e.end()}o.endEmitted?n.nextTick(i):r.once("end",i),e.on("unpipe",a);var l=L(r);e.on("drain",l);var u=!1;function h(){d("cleanup"),e.removeListener("close",g),e.removeListener("finish",m),e.removeListener("drain",l),e.removeListener("error",p),e.removeListener("unpipe",a),r.removeListener("end",c),r.removeListener("end",y),r.removeListener("data",f),u=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||l()}function f(t){d("ondata");var n=e.write(t);d("dest.write",n),!1===n&&((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==J(o.pipes,e))&&!u&&(d("false write response, pause",o.awaitDrain),o.awaitDrain++),r.pause())}function p(t){d("onerror",t),y(),e.removeListener("error",p),0===s(e,"error")&&S(e,t)}function g(){e.removeListener("finish",m),y()}function m(){d("onfinish"),e.removeListener("close",g),y()}function y(){d("unpipe"),r.unpipe(e)}return r.on("data",f),E(e,"error",p),e.once("close",g),e.once("finish",m),e.emit("pipe",r),o.flowing||(d("pipe resume"),r.resume()),e},O.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};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,n)),this;if(!e){var r=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<o;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var i=J(t.pipes,e);return-1===i||(t.pipes.splice(i,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},O.prototype.on=function(e,t){var r=i.prototype.on.call(this,e,t),o=this._readableState;return"data"===e?(o.readableListening=this.listenerCount("readable")>0,!1!==o.flowing&&this.resume()):"readable"===e&&(o.endEmitted||o.readableListening||(o.readableListening=o.needReadable=!0,o.flowing=!1,o.emittedReadable=!1,d("on readable",o.length,o.reading),o.length?B(this):o.reading||n.nextTick($,this))),r},O.prototype.addListener=O.prototype.on,O.prototype.removeListener=function(e,t){var r=i.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(q,this),r},O.prototype.removeAllListeners=function(e){var t=i.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(q,this),t},O.prototype.resume=function(){var e=this._readableState;return e.flowing||(d("resume"),e.flowing=!e.readableListening,z(this,e)),e.paused=!1,this},O.prototype.pause=function(){return d("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(d("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},O.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var o in e.on("end",(function(){if(d("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(o){d("wrapped data"),n.decoder&&(o=n.decoder.write(o)),n.objectMode&&null==o||(n.objectMode||o&&o.length)&&(t.push(o)||(r=!0,e.pause()))})),e)void 0===this[o]&&"function"==typeof e[o]&&(this[o]=function(t){return function(){return e[t].apply(e,arguments)}}(o));for(var s=0;s<A.length;s++)e.on(A[s],this.emit.bind(this,A[s]));return this._read=function(t){d("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(O.prototype[Symbol.asyncIterator]=function(){return void 0===p&&(p=e("./internal/streams/async_iterator")),p(this)}),Object.defineProperty(O.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(O.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(O.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),O._fromList=W,Object.defineProperty(O.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(O.from=function(t,n){return void 0===g&&(g=e("./internal/streams/from")),g(O,t,n)})}).call(this)}).call(this,e("_process"),void 0!==Ce?Ce:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/async_iterator":61,"./internal/streams/buffer_list":62,"./internal/streams/destroy":63,"./internal/streams/from":65,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,events:22,inherits:24,"string_decoder/":75,util:16}],59:[function(e,t,n){t.exports=u;var r=e("../errors").codes,o=r.ERR_METHOD_NOT_IMPLEMENTED,s=r.ERR_MULTIPLE_CALLBACK,i=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=r.ERR_TRANSFORM_WITH_LENGTH_0,c=e("./_stream_duplex");function l(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new s);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var o=this._readableState;o.reading=!1,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}function u(e){if(!(this instanceof u))return new u(e);c.call(this,e),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},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.on("prefinish",d)}function d(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new a;if(e._transformState.transforming)throw new i;return e.push(null)}e("inherits")(u,c),u.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},u.prototype._transform=function(e,t,n){n(new o("_transform()"))},u.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var o=this._readableState;(r.needTransform||o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark)}},u.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},u.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},{"../errors":55,"./_stream_duplex":56,inherits:24}],60:[function(e,t,n){(function(n,r){(function(){function o(e){var t=this;this.next=null,this.entry=null,this.finish=function(){H(t,e)}}var s;t.exports=I,I.WritableState=E;var i={deprecate:e("util-deprecate")},a=e("./internal/streams/stream"),c=e("buffer").Buffer,l=r.Uint8Array||function(){};function u(e){return c.from(e)}function d(e){return c.isBuffer(e)||e instanceof l}var h,f=e("./internal/streams/destroy"),p=e("./internal/streams/state").getHighWaterMark,g=e("../errors").codes,m=g.ERR_INVALID_ARG_TYPE,y=g.ERR_METHOD_NOT_IMPLEMENTED,v=g.ERR_MULTIPLE_CALLBACK,b=g.ERR_STREAM_CANNOT_PIPE,w=g.ERR_STREAM_DESTROYED,C=g.ERR_STREAM_NULL_VALUES,_=g.ERR_STREAM_WRITE_AFTER_END,k=g.ERR_UNKNOWN_ENCODING,S=f.errorOrDestroy;function A(){}function E(t,n,r){s=s||e("./_stream_duplex"),t=t||{},"boolean"!=typeof r&&(r=n instanceof s),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=p(this,t,"writableHighWaterMark",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var i=!1===t.decodeStrings;this.decodeStrings=!i,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){F(n,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==t.emitClose,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new o(this)}function I(t){var n=this instanceof(s=s||e("./_stream_duplex"));if(!n&&!h.call(I,this))return new I(t);this._writableState=new E(t,this,n),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),a.call(this)}function O(e,t){var r=new _;S(e,r),n.nextTick(t,r)}function T(e,t,r,o){var s;return null===r?s=new C:"string"==typeof r||t.objectMode||(s=new m("chunk",["string","Buffer"],r)),!s||(S(e,s),n.nextTick(o,s),!1)}function x(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function R(e,t,n,r,o,s){if(!n){var i=x(t,r,o);r!==i&&(n=!0,o="buffer",r=i)}var a=t.objectMode?1:r.length;t.length+=a;var c=t.length<t.highWaterMark;if(c||(t.needDrain=!0),t.writing||t.corked){var l=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:o,isBuf:n,callback:s,next:null},l?l.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else P(e,t,!1,a,r,o,s);return c}function P(e,t,n,r,o,s,i){t.writelen=r,t.writecb=i,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new w("write")):n?e._writev(o,t.onwrite):e._write(o,s,t.onwrite),t.sync=!1}function M(e,t,r,o,s){--t.pendingcb,r?(n.nextTick(s,o),n.nextTick($,e,t),e._writableState.errorEmitted=!0,S(e,o)):(s(o),e._writableState.errorEmitted=!0,S(e,o),$(e,t))}function j(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function F(e,t){var r=e._writableState,o=r.sync,s=r.writecb;if("function"!=typeof s)throw new v;if(j(r),t)M(e,r,o,t,s);else{var i=D(r)||e.destroyed;i||r.corked||r.bufferProcessing||!r.bufferedRequest||U(e,r),o?n.nextTick(B,e,r,i,s):B(e,r,i,s)}}function B(e,t,n,r){n||N(e,t),t.pendingcb--,r(),$(e,t)}function N(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function U(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,s=new Array(r),i=t.corkedRequestsFree;i.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,P(e,t,!0,t.length,s,"",i.finish),t.pendingcb++,t.lastBufferedRequest=null,i.next?(t.corkedRequestsFree=i.next,i.next=null):t.corkedRequestsFree=new o(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,u=n.encoding,d=n.callback;if(P(e,t,!1,t.objectMode?1:l.length,l,u,d),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function D(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function L(e,t){e._final((function(n){t.pendingcb--,n&&S(e,n),t.prefinished=!0,e.emit("prefinish"),$(e,t)}))}function q(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,n.nextTick(L,e,t)))}function $(e,t){var n=D(t);if(n&&(q(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}function z(e,t,r){t.ending=!0,$(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function H(e,t,n){var r=e.entry;for(e.entry=null;r;){var o=r.callback;t.pendingcb--,o(n),r=r.next}t.corkedRequestsFree.next=e}e("inherits")(I,a),E.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(E.prototype,"buffer",{get:i.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(I,Symbol.hasInstance,{value:function(e){return!!h.call(this,e)||this===I&&e&&e._writableState instanceof E}})):h=function(e){return e instanceof this},I.prototype.pipe=function(){S(this,new b)},I.prototype.write=function(e,t,n){var r=this._writableState,o=!1,s=!r.objectMode&&d(e);return s&&!c.isBuffer(e)&&(e=u(e)),"function"==typeof t&&(n=t,t=null),s?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=A),r.ending?O(this,n):(s||T(this,r,e,n))&&(r.pendingcb++,o=R(this,r,s,e,t,n)),o},I.prototype.cork=function(){this._writableState.corked++},I.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||U(this,e))},I.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 k(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(I.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(I.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),I.prototype._write=function(e,t,n){n(new y("_write()"))},I.prototype._writev=null,I.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||z(this,r,n),this},Object.defineProperty(I.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(I.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),I.prototype.destroy=f.destroy,I.prototype._undestroy=f.undestroy,I.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),void 0!==Ce?Ce:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":55,"./_stream_duplex":56,"./internal/streams/destroy":63,"./internal/streams/state":67,"./internal/streams/stream":68,_process:50,buffer:17,inherits:24,"util-deprecate":78}],61:[function(e,t,n){(function(n){(function(){var r;function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=e("./end-of-stream"),i=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),u=Symbol("lastPromise"),d=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function p(e){var t=e[i];if(null!==t){var n=e[h].read();null!==n&&(e[u]=null,e[i]=null,e[a]=null,t(f(n,!1)))}}function g(e){n.nextTick(p,e)}function m(e,t){return function(n,r){e.then((function(){t[l]?n(f(void 0,!0)):t[d](n,r)}),r)}}var y=Object.getPrototypeOf((function(){})),v=Object.setPrototypeOf((o(r={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,r){n.nextTick((function(){e[c]?r(e[c]):t(f(void 0,!0))}))}));var r,o=this[u];if(o)r=new Promise(m(o,this));else{var s=this[h].read();if(null!==s)return Promise.resolve(f(s,!1));r=new Promise(this[d])}return this[u]=r,r}},Symbol.asyncIterator,(function(){return this})),o(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(f(void 0,!0))}))}))})),r),y),b=function(e){var t,n=Object.create(v,(o(t={},h,{value:e,writable:!0}),o(t,i,{value:null,writable:!0}),o(t,a,{value:null,writable:!0}),o(t,c,{value:null,writable:!0}),o(t,l,{value:e._readableState.endEmitted,writable:!0}),o(t,d,{value:function(e,t){var r=n[h].read();r?(n[u]=null,n[i]=null,n[a]=null,e(f(r,!1))):(n[i]=e,n[a]=t)},writable:!0}),t));return n[u]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[a];return null!==t&&(n[u]=null,n[i]=null,n[a]=null,t(e)),void(n[c]=e)}var r=n[i];null!==r&&(n[u]=null,n[i]=null,n[a]=null,r(f(void 0,!0))),n[l]=!0})),e.on("readable",g.bind(null,n)),n};t.exports=b}).call(this)}).call(this,e("_process"))},{"./end-of-stream":64,_process:50}],62:[function(e,t,n){function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function o(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function c(e,t,n){return t&&a(e.prototype,t),n&&a(e,n),e}var l=e("buffer").Buffer,u=e("util").inspect,d=u&&u.custom||"inspect";function h(e,t,n){l.prototype.copy.call(e,t,n)}t.exports=function(){function e(){i(this,e),this.head=null,this.tail=null,this.length=0}return c(e,[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value: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}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return l.alloc(0);for(var t=l.allocUnsafe(e>>>0),n=this.head,r=0;n;)h(n.data,t,r),r+=n.data.length,n=n.next;return t}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var o=t.data,s=e>o.length?o.length:e;if(s===o.length?r+=o:r+=o.slice(0,e),0==(e-=s)){s===o.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=o.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=l.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var o=n.data,s=e>o.length?o.length:e;if(o.copy(t,t.length-e,0,s),0==(e-=s)){s===o.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=o.slice(s));break}++r}return this.length-=r,t}},{key:d,value:function(e,t){return u(this,o({},t,{depth:0,customInspect:!1}))}}]),e}()},{buffer:17,util:16}],63:[function(e,t,n){(function(e){(function(){function n(t,n){var s=this,a=this._readableState&&this._readableState.destroyed,c=this._writableState&&this._writableState.destroyed;return a||c?(n?n(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,e.nextTick(i,this,t)):e.nextTick(i,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,(function(t){!n&&t?s._writableState?s._writableState.errorEmitted?e.nextTick(o,s):(s._writableState.errorEmitted=!0,e.nextTick(r,s,t)):e.nextTick(r,s,t):n?(e.nextTick(o,s),n(t)):e.nextTick(o,s)})),this)}function r(e,t){i(e,t),o(e)}function o(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function s(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function i(e,t){e.emit("error",t)}function a(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}t.exports={destroy:n,undestroy:s,errorOrDestroy:a}}).call(this)}).call(this,e("_process"))},{_process:50}],64:[function(e,t,n){var r=e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function o(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];e.apply(this,r)}}}function s(){}function i(e){return e.setHeader&&"function"==typeof e.abort}function a(e,t,n){if("function"==typeof t)return a(e,null,t);t||(t={}),n=o(n||s);var c=t.readable||!1!==t.readable&&e.readable,l=t.writable||!1!==t.writable&&e.writable,u=function(){e.writable||h()},d=e._writableState&&e._writableState.finished,h=function(){l=!1,d=!0,c||n.call(e)},f=e._readableState&&e._readableState.endEmitted,p=function(){c=!1,f=!0,l||n.call(e)},g=function(t){n.call(e,t)},m=function(){var t;return c&&!f?(e._readableState&&e._readableState.ended||(t=new r),n.call(e,t)):l&&!d?(e._writableState&&e._writableState.ended||(t=new r),n.call(e,t)):void 0},y=function(){e.req.on("finish",h)};return i(e)?(e.on("complete",h),e.on("abort",m),e.req?y():e.on("request",y)):l&&!e._writableState&&(e.on("end",u),e.on("close",u)),e.on("end",p),e.on("finish",h),!1!==t.error&&e.on("error",g),e.on("close",m),function(){e.removeListener("complete",h),e.removeListener("abort",m),e.removeListener("request",y),e.req&&e.req.removeListener("finish",h),e.removeListener("end",u),e.removeListener("close",u),e.removeListener("finish",h),e.removeListener("end",p),e.removeListener("error",g),e.removeListener("close",m)}}t.exports=a},{"../../../errors":55}],65:[function(e,t,n){t.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],66:[function(e,t,n){var r;function o(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var s=e("../../../errors").codes,i=s.ERR_MISSING_ARGS,a=s.ERR_STREAM_DESTROYED;function c(e){if(e)throw e}function l(e){return e.setHeader&&"function"==typeof e.abort}function u(t,n,s,i){i=o(i);var c=!1;t.on("close",(function(){c=!0})),void 0===r&&(r=e("./end-of-stream")),r(t,{readable:n,writable:s},(function(e){if(e)return i(e);c=!0,i()}));var u=!1;return function(e){if(!c&&!u)return u=!0,l(t)?t.abort():"function"==typeof t.destroy?t.destroy():void i(e||new a("pipe"))}}function d(e){e()}function h(e,t){return e.pipe(t)}function f(e){return e.length?"function"!=typeof e[e.length-1]?c:e.pop():c}function p(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,o=f(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new i("streams");var s=t.map((function(e,n){var i=n<t.length-1;return u(e,i,n>0,(function(e){r||(r=e),e&&s.forEach(d),i||(s.forEach(d),o(r))}))}));return t.reduce(h)}t.exports=p},{"../../../errors":55,"./end-of-stream":64}],67:[function(e,t,n){var r=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;function o(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}function s(e,t,n,s){var i=o(t,s,n);if(null!=i){if(!isFinite(i)||Math.floor(i)!==i||i<0)throw new r(s?n:"highWaterMark",i);return Math.floor(i)}return e.objectMode?16:16384}t.exports={getHighWaterMark:s}},{"../../../errors":55}],68:[function(e,t,n){t.exports=e("events").EventEmitter},{events:22}],69:[function(e,t,n){(n=t.exports=e("./lib/_stream_readable.js")).Stream=n,n.Readable=n,n.Writable=e("./lib/_stream_writable.js"),n.Duplex=e("./lib/_stream_duplex.js"),n.Transform=e("./lib/_stream_transform.js"),n.PassThrough=e("./lib/_stream_passthrough.js"),n.finished=e("./lib/internal/streams/end-of-stream.js"),n.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":56,"./lib/_stream_passthrough.js":57,"./lib/_stream_readable.js":58,"./lib/_stream_transform.js":59,"./lib/_stream_writable.js":60,"./lib/internal/streams/end-of-stream.js":64,"./lib/internal/streams/pipeline.js":66}],70:[function(e,t,n){function r(e,t,n){var r=this;this._callback=e,this._args=n,this._interval=setInterval(e,t,this._args),this.reschedule=function(e){e||(e=r._interval),r._interval&&clearInterval(r._interval),r._interval=setInterval(r._callback,e,r._args)},this.clear=function(){r._interval&&(clearInterval(r._interval),r._interval=void 0)},this.destroy=function(){r._interval&&clearInterval(r._interval),r._callback=void 0,r._interval=void 0,r._args=void 0}}function o(){if("function"!=typeof arguments[0])throw new Error("callback needed");if("number"!=typeof arguments[1])throw new Error("interval needed");var e;if(arguments.length>0){e=new Array(arguments.length-2);for(var t=0;t<e.length;t++)e[t]=arguments[t+2]}return new r(arguments[0],arguments[1],e)}t.exports=o},{}],71:[function(e,t,n){t.exports=e("./index.js")()},{"./index.js":72}],72:[function(e,t,n){(function(e){(function(){function n(t){return t instanceof e?e.from(t):new t.constructor(t.buffer.slice(),t.byteOffset,t.length)}function r(e){return(e=e||{}).circles?o(e):e.proto?s:r;function t(e,t){for(var r=Object.keys(e),o=new Array(r.length),s=0;s<r.length;s++){var i=r[s],a=e[i];"object"!=typeof a||null===a?o[i]=a:a instanceof Date?o[i]=new Date(a):ArrayBuffer.isView(a)?o[i]=n(a):o[i]=t(a)}return o}function r(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,r);if(e instanceof Map)return new Map(t(Array.from(e),r));if(e instanceof Set)return new Set(t(Array.from(e),r));var o={};for(var s in e)if(!1!==Object.hasOwnProperty.call(e,s)){var i=e[s];"object"!=typeof i||null===i?o[s]=i:i instanceof Date?o[s]=new Date(i):i instanceof Map?o[s]=new Map(t(Array.from(i),r)):i instanceof Set?o[s]=new Set(t(Array.from(i),r)):ArrayBuffer.isView(i)?o[s]=n(i):o[s]=r(i)}return o}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return t(e,s);if(e instanceof Map)return new Map(t(Array.from(e),s));if(e instanceof Set)return new Set(t(Array.from(e),s));var r={};for(var o in e){var i=e[o];"object"!=typeof i||null===i?r[o]=i:i instanceof Date?r[o]=new Date(i):i instanceof Map?r[o]=new Map(t(Array.from(i),s)):i instanceof Set?r[o]=new Set(t(Array.from(i),s)):ArrayBuffer.isView(i)?r[o]=n(i):r[o]=s(i)}return r}}function o(e){var t=[],r=[];return e.proto?i:s;function o(e,o){for(var s=Object.keys(e),i=new Array(s.length),a=0;a<s.length;a++){var c=s[a],l=e[c];if("object"!=typeof l||null===l)i[c]=l;else if(l instanceof Date)i[c]=new Date(l);else if(ArrayBuffer.isView(l))i[c]=n(l);else{var u=t.indexOf(l);i[c]=-1!==u?r[u]:o(l)}}return i}function s(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return o(e,s);if(e instanceof Map)return new Map(o(Array.from(e),s));if(e instanceof Set)return new Set(o(Array.from(e),s));var i={};for(var a in t.push(e),r.push(i),e)if(!1!==Object.hasOwnProperty.call(e,a)){var c=e[a];if("object"!=typeof c||null===c)i[a]=c;else if(c instanceof Date)i[a]=new Date(c);else if(c instanceof Map)i[a]=new Map(o(Array.from(c),s));else if(c instanceof Set)i[a]=new Set(o(Array.from(c),s));else if(ArrayBuffer.isView(c))i[a]=n(c);else{var l=t.indexOf(c);i[a]=-1!==l?r[l]:s(c)}}return t.pop(),r.pop(),i}function i(e){if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return o(e,i);if(e instanceof Map)return new Map(o(Array.from(e),i));if(e instanceof Set)return new Set(o(Array.from(e),i));var s={};for(var a in t.push(e),r.push(s),e){var c=e[a];if("object"!=typeof c||null===c)s[a]=c;else if(c instanceof Date)s[a]=new Date(c);else if(c instanceof Map)s[a]=new Map(o(Array.from(c),i));else if(c instanceof Set)s[a]=new Set(o(Array.from(c),i));else if(ArrayBuffer.isView(c))s[a]=n(c);else{var l=t.indexOf(c);s[a]=-1!==l?r[l]:i(c)}}return t.pop(),r.pop(),s}}t.exports=r}).call(this)}).call(this,e("buffer").Buffer)},{buffer:17}],73:[function(e,t,n){
5
5
  /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
6
- var r=e("buffer"),o=r.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=r:(s(r,n),n.Buffer=i),i.prototype=Object.create(o.prototype),s(o,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(o(t)):null}function o(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,o=r.isEncoding||function(e){switch((e=""+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 s(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function i(e){var t=s(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}function a(e){var t;switch(this.encoding=i(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=d,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function c(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function l(e,t,n){var r=t.length-1;if(r<n)return 0;var o=c(t[r]);return o>=0?(o>0&&(e.lastNeed=o-1),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(e.lastNeed=o-2),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(2===o?o=0:e.lastNeed=o-3),o):0}function u(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function d(e){var t=this.lastTotal-this.lastNeed,n=u(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var n=l(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function p(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function g(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function m(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}n.StringDecoder=a,a.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},a.prototype.end=f,a.prototype.text=h,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,n){var r=e("punycode"),o=e("./util");function s(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=_,n.resolveObject=k,n.format=C,n.Url=s;var i=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(l),d=["%","/","?",";","#"].concat(u),h=["/","?","#"],f=255,p=/^[+a-z0-9A-Z_-]{0,63}$/,g=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,n){if(e&&o.isObject(e)&&e instanceof s)return e;var r=new s;return r.parse(e,t,n),r}function C(e){return o.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function _(e,t){return w(e,!1,!0).resolve(t)}function k(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),a=-1!==s&&s<e.indexOf("#")?"?":"#",l=e.split(a),w=/\\/g;l[0]=l[0].replace(w,"/");var C=e=l.join(a);if(C=C.trim(),!n&&1===e.split("#").length){var _=c.exec(C);if(_)return this.path=C,this.href=C,this.pathname=_[1],_[2]?(this.search=_[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var k=i.exec(C);if(k){var S=(k=k[0]).toLowerCase();this.protocol=S,C=C.substr(k.length)}if(n||k||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var A="//"===C.substr(0,2);!A||k&&y[k]||(C=C.substr(2),this.slashes=!0)}if(!y[k]&&(A||k&&!v[k])){for(var E,I,O=-1,T=0;T<h.length;T++)-1!==(x=C.indexOf(h[T]))&&(-1===O||x<O)&&(O=x);for(-1!==(I=-1===O?C.lastIndexOf("@"):C.lastIndexOf("@",O))&&(E=C.slice(0,I),C=C.slice(I+1),this.auth=decodeURIComponent(E)),O=-1,T=0;T<d.length;T++){var x;-1!==(x=C.indexOf(d[T]))&&(-1===O||x<O)&&(O=x)}-1===O&&(O=C.length),this.host=C.slice(0,O),C=C.slice(O),this.parseHost(),this.hostname=this.hostname||"";var R="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!R)for(var P=this.hostname.split(/\./),M=(T=0,P.length);T<M;T++){var j=P[T];if(j&&!j.match(p)){for(var F="",B=0,N=j.length;B<N;B++)j.charCodeAt(B)>127?F+="x":F+=j[B];if(!F.match(p)){var U=P.slice(0,T),D=P.slice(T+1),L=j.match(g);L&&(U.push(L[1]),D.unshift(L[2])),D.length&&(C="/"+D.join(".")+C),this.hostname=U.join(".");break}}}this.hostname.length>f?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=r.toASCII(this.hostname));var q=this.port?":"+this.port:"",$=this.hostname||"";this.host=$+q,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!m[S])for(T=0,M=u.length;T<M;T++){var z=u[T];if(-1!==C.indexOf(z)){var H=encodeURIComponent(z);H===z&&(H=escape(z)),C=C.split(z).join(H)}}var V=C.indexOf("#");-1!==V&&(this.hash=C.substr(V),C=C.slice(0,V));var W=C.indexOf("?");if(-1!==W?(this.search=C.substr(W),this.query=C.substr(W+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,W)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[S]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){q=this.pathname||"";var K=this.search||"";this.path=q+K}return this.href=this.format(),this},s.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",s=!1,i="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&o.isObject(this.query)&&Object.keys(this.query).length&&(i=b.stringify(this.query));var a=this.search||i&&"?"+i||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),r&&"#"!==r.charAt(0)&&(r="#"+r),a&&"?"!==a.charAt(0)&&(a="?"+a),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(a=a.replace("#","%23"))+r},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(o.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,r=Object.keys(this),i=0;i<r.length;i++){var a=r[i];n[a]=this[a]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),l=0;l<c.length;l++){var u=c[l];"protocol"!==u&&(n[u]=e[u])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var d=Object.keys(e),h=0;h<d.length;h++){var f=d[h];n[f]=e[f]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var p=(e.pathname||"").split("/");p.length&&!(e.host=p.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),n.pathname=p.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var g=n.pathname||"",m=n.search||"";n.path=g+m}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),C=w||b||n.host&&e.pathname,_=C,k=n.pathname&&n.pathname.split("/")||[],S=(p=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(S&&(n.hostname="",n.port=null,n.host&&(""===k[0]?k[0]=n.host:k.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===p[0]?p[0]=e.host:p.unshift(e.host)),e.host=null),C=C&&(""===p[0]||""===k[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,k=p;else if(p.length)k||(k=[]),k.pop(),k=k.concat(p),n.search=e.search,n.query=e.query;else if(!o.isNullOrUndefined(e.search))return S&&(n.hostname=n.host=k.shift(),(T=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=T.shift(),n.host=n.hostname=T.shift())),n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!k.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var A=k.slice(-1)[0],E=(n.host||e.host||k.length>1)&&("."===A||".."===A)||""===A,I=0,O=k.length;O>=0;O--)"."===(A=k[O])?k.splice(O,1):".."===A?(k.splice(O,1),I++):I&&(k.splice(O,1),I--);if(!C&&!_)for(;I--;I)k.unshift("..");!C||""===k[0]||k[0]&&"/"===k[0].charAt(0)||k.unshift(""),E&&"/"!==k.join("/").substr(-1)&&k.push("");var T,x=""===k[0]||k[0]&&"/"===k[0].charAt(0);return S&&(n.hostname=n.host=x?"":k.length?k.shift():"",(T=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=T.shift(),n.host=n.hostname=T.shift())),(C=C||n.host&&k.length)&&!x&&k.unshift(""),k.length?n.pathname=k.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},s.prototype.parseHost=function(){var e=this.host,t=a.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function o(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return o}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==Ce?Ce:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),o=t[t.length-1];return"function"==typeof r&&r!==o&&Object.keys(o).forEach((function(e){r[e]=o[e]})),r}}t.exports=r},{}],80:[function(e,t,n){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,n){t.exports=o;var r=Object.prototype.hasOwnProperty;function o(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var o in n)r.call(n,o)&&(e[o]=n[o])}return e}},{}],82:[function(e,t,n){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,n){function r(e){var t=this;if(t instanceof r||(t=new r),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,o=arguments.length;n<o;n++)t.push(arguments[n]);return t}function o(e,t,n){var r=t===e.head?new a(n,null,t,e):new a(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function s(e,t){e.tail=new a(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function i(e,t){e.head=new a(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function a(e,t,n,r){if(!(this instanceof a))return new a(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=a,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},r.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)s(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},r.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},r.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,o=this.head;null!==o;)n.push(e.call(t,o.value,this)),o=o.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,o=this.tail;null!==o;)n.push(e.call(t,o.value,this)),o=o.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var o=0;null!==r;o++)n=e(n,r.value,o),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var o=this.length-1;null!==r;o--)n=e(n,r.value,o),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=0,s=this.head;null!==s&&o<e;o++)s=s.next;for(;null!==s&&o<t;o++,s=s.next)n.push(s.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=this.length,s=this.tail;null!==s&&o>t;o--)s=s.prev;for(;null!==s&&o>e;o--,s=s.prev)n.push(s.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,s=this.head;null!==s&&r<e;r++)s=s.next;var i=[];for(r=0;s&&r<t;r++)i.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),r=0;r<n.length;r++)s=o(this,s,n[r]);return i},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12)}(qi);var $i=_e(qi.exports);const zi=1e3;var Hi;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Hi||(Hi={}));const Vi=e=>{let t;return{connect:async function(n){return t&&(t.removeAllListeners(),t.end(!0)),t=$i.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:zi,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken})),t.on("connect",(()=>{t.options.reconnectPeriod=zi,(()=>{const e=[At(Ct()),At(_t()),At(kt()),At(St()),At(bt(rt()))]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||zi),8e3)})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,n){const r=(t,r)=>{var o;if(t||128===(null===(o=r[0])||void 0===o?void 0:o.qos)){const r=t?new pe(t.message,8e5,"error"):new me(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Wi=async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Ki=()=>`ascWebSdk#${Math.random().toString(16)}`,Qi=()=>{const e=(()=>{var e,t;return(null===(e=jt.versions)||void 0===e?void 0:e.node)?jt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:d}},Ji={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Gi=e=>{const t=be();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>Ji[e].includes(t))(n,e))throw new pe(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,t.emitter.emit("sessionStateChange",e),!0},Yi=async e=>{const t=be();Gi("establishing");const{accessToken:n,users:r,expiresAt:o,issuedAt:s,refreshToken:i}=await(async e=>{const t=be();t.log("client/api/getToken",e);const n=Qi(),{data:r}=await t.http.post("/api/v4/sessions",Object.assign(Object.assign({},e),{deviceInfo:n}),{headers:{"X-API-Key":t.apiKey}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:o,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:n},t.token={accessToken:n,issuedAt:s,expiresAt:o},Gi("established"),{accessToken:n,users:r,refreshToken:i}},Xi=(e={},t)=>{Object.entries(e).forEach((([e,n])=>{const r=he[e];if(!r)return;const o=ce(r);o&&n.forEach((e=>{$e([r,"get",o(e)],e,t)}))}))};function Zi(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}const ea=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!be().cache)return;return(null===(n=De(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},ta=(e,t,n="userId",r="user")=>{const o=e,s=t,i=o[s],a=Zi(o,["symbol"==typeof s?s:s+""]),c=ea(i,n,r);return Object.assign(Object.assign({},a),{[t]:c})},na=(e,t)=>{var n,r,o;return(null==t?void 0:t.isDeleted)?0:null!==(o=null!==(n=null==t?void 0:t.unreadCount)&&void 0!==n?n:null===(r=(e=>{var t;const n={entityId:e,userId:rt()._id};return null===(t=De(["channelMarker","get",ce("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.unreadCount)&&void 0!==o?o:0},ra=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=De(["messageMarker","get",ce("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}};function oa(e,t,n){var r;if(n)return n.unreadCount;const o={entityId:e,feedId:t,userId:rt()._id},s=null===(r=De(["subChannelMarker","get",ce("subChannelMarker")(o)]))||void 0===r?void 0:r.data;return s?s.unreadCount:0}const sa=(e,t)=>{t.length&&ht(e,{userMarkers:t})},ia=(e,t)=>{t.length&&ht(e,{feedMarkers:t})},aa=(e,t)=>{if(!t.length)return;ht(e,{userEntityMarkers:t});const n=function(e){var t;const n=["channel","get",e.entityId],r=null===(t=De(n))||void 0===t?void 0:t.data;if(!r)return;const o=Object.assign(Object.assign({},r),{unreadCount:na(r,e),updatedAt:(new Date).toISOString()});return $e(n,o),o}(t[0]);return n&&ht("local.channel.updated",{channels:[n]}),n},ca=(e,t)=>{if(!t.length)return;ht(e,{userFeedMarkers:t});const n=function(e){var t;const n=["subChannel","get",e.feedId],r=null===(t=De(n))||void 0===t?void 0:t.data;if(!r)return;const o=Object.assign(Object.assign({},r),{unreadCount:oa(r.channelId,r.subChannelId,e),updatedAt:(new Date).toISOString()});return $e(n,o),o}(t[0]);return n&&ht("local.message-feed.updated",{messageFeeds:[n]}),n},la=(e,t)=>{if(!t.length)return;ht(e,{contentMarkers:t});const n=function(e){var t;const n=["message","get",e.contentId],r=null===(t=De(n))||void 0===t?void 0:t.data;if(!r)return;const{readCount:o,deliveredCount:s}=ra(r,e),i=Object.assign(Object.assign({},r),{readCount:o,deliveredCount:s,updatedAt:(new Date).toISOString()});return $e(n,i),i}(t[0]);return n&&ht("local.message.updated",{messages:[n]}),n},ua=async(e,t={limit:100})=>{const n=be();n.log("channel/getChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/channels",{params:{channelIds:e,options:{token:J(t,"skiplimit")}}}),{paging:o}=r,s=Zi(r,["paging"]),{userEntityMarkers:i,userMarkers:a}=s,c=n.cache&&Date.now();n.cache&&Xi(s,{cachedAt:c}),aa("local.channelMarker.fetched",i),sa("local.userMarker.fetched",a);const l=G(o.next);return{data:i,cachedAt:c,prevPage:G(o.previous),nextPage:l}},da=["broadcast","conversation","community"],ha=({type:e})=>da.includes(e);function fa(e,t){return Object.assign(Object.assign({},e),{defaultSubChannelId:e._id,isUnreadCountSupport:ha(e),unreadCount:na(e,t)})}const pa=async e=>{let t=[];const n=e.channels.filter(ha).map((({channelId:e})=>e));if(n.length>0){(e=>{Xi({channels:e.channels.map((e=>fa(e)))})})(e);try{({data:t}=await ua(n))}catch(e){}}const r=e.channels.map((e=>{const n=null==t?void 0:t.find((({entityId:t})=>t===e.channelId));return fa(e,n)})),o=ea(e.channelUsers);return Object.assign(Object.assign({},e),{channels:r,channelUsers:o})},ga=e=>{const t=be();return dt(t,"onChannelDeleted","channel.deleted",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])}))},ma=e=>{const t=be();return dt(t,"onChannelMemberBanned","channel.banned",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o.find((e=>"banned"===e.membership)))}))},ya=e=>{const t=be();return dt(t,"client/onSessionStateChange","sessionStateChange",e)},va=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)},ba=(e,t)=>{const{log:n,cache:r}=be(),o=[e,m,t];if(!r)return;n("cache/api/isInTombstone",o);const s=De(o),{lifeSpan:i}=oe("cache_then_server",18e4);if(s&&ne(s.data,i))throw new ge("Item not found!",400400,"error")},wa=(e,t)=>{const{log:n,cache:r}=be(),o=[e,m,t],s={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:o,data:s}),ze([e,"get",t],!0),Le(o,s))},Ca=async(e,t={limit:100})=>{const n=be();n.log("channel/getMessageMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/messages",{params:{messageIds:e,options:{token:J(t,"skiplimit")}}}),{paging:o}=r,s=Zi(r,["paging"]),{contentMarkers:i,feedMarkers:a,userMarkers:c}=s,l=n.cache&&Date.now();n.cache&&Xi(s,{cachedAt:l}),ia("local.feedMarker.fetched",a),la("local.messageMarker.fetched",i),sa("local.userMarker.fetched",c);const u=G(o.next);return{data:i,cachedAt:l,prevPage:G(o.previous),nextPage:u}},_a=async(e,t={limit:100})=>{const n=be();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:J(t,"skiplimit")}}}),{paging:o}=r,s=Zi(r,["paging"]),{userEntityMarkers:i,userFeedMarkers:a,userMarkers:c}=s,l=n.cache&&Date.now();n.cache&&Xi(s,{cachedAt:l}),aa("local.channelMarker.fetched",i),ca("local.subChannelMarker.fetched",a),sa("local.userMarker.fetched",c);const u=G(o.next);return{data:a,cachedAt:l,prevPage:G(o.previous),nextPage:u}},ka=async()=>{const e=be();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();return e.cache&&Xi(t,{cachedAt:r}),sa("local.userMarker.fetched",n),{data:n[0],cachedAt:r}},Sa=["broadcast","conversation","community"],Aa=({channelType:e})=>Sa.includes(e);function Ea(e,t){var{channelId:n,channelPublicId:r,channelType:o,childCount:s,creatorId:i,creatorPublicId:a,lastMessageId:c,lastMessageTimestamp:l,messageFeedId:u,name:d}=e,h=Zi(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({},h),{channelId:r,creatorId:a,displayName:d,lastActivity:l,latestMessageId:c,messageCount:s,subChannelId:u,isUnreadCountSupport:Aa({channelType:o}),unreadCount:oa(n,u,t)})}const Ia=async e=>{let t=[];const n=e.messageFeeds.filter(Aa).map((({messageFeedId:e})=>e));if(n.length>0){(e=>{Xi({messageFeeds:e.messageFeeds.map((e=>Ea(e)))})})(e);try{({data:t}=await _a(n))}catch(e){}}const r=e.messageFeeds.map((e=>{const n=null==t?void 0:t.find((({feedId:t})=>t===e.messageFeedId));return Ea(e,n)}));return Object.assign(Object.assign({},e),{messageFeeds:r})};function Oa(e){var{excludeDefaultSubChannel:t}=e,n=Zi(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}const Ta=async e=>{const t=be();t.log("channel/getSubChannel",e),ba("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Ia(n.data),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:o}}catch(t){throw _(null==t?void 0:t.code)&&wa("subChannel",e),t}};Ta.locally=e=>{const t=be();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=De(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const xa=async e=>{const t=be();t.log("subChannel/startReadingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:a}),ia("local.feedMarker.fetched",s),aa("local.channelMarker.fetched",r),ca("local.subChannelMarker.fetched",o),sa("local.userMarker.fetched",i),!0},Ra=async e=>{const t=be();t.log("channel/stopReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:a}),ia("local.feedMarker.fetched",s),aa("local.channelMarker.fetched",r),ca("local.subChannelMarker.fetched",o),sa("local.userMarker.fetched",i),!0};let Pa=null,Ma=[];const ja={},Fa=async()=>{const e=Object.entries(ja).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&xa(e)},Ba=()=>{null==Pa||Pa(),Pa=null},Na=()=>(null===Pa&&(Pa=va(Fa,3e4)),ya((e=>{"notLoggedIn"===e&&Ba()})),()=>{Ba()}),Ua=()=>{Ma.push((()=>{const e=()=>{Fa()};return window.addEventListener("online",e),()=>window.removeEventListener("online",e)})())},Da=async e=>{const t=await(async e=>{const t=Ta.locally(e);if(t)return t.data.channelId;const{data:n}=await Ta(e);return n.channelId})(e),n=wt({channelId:t,subChannelId:e});Ma.push(At(n))},La=(e,t)=>{const n=be();return dt(n,e,e,(e=>{n.cache&&Xi(e),t(e.users[0])}))},qa=e=>La("user.deleted",e),$a=async()=>{const e=be();return e.log("client/api/disconnectClient"),await new Promise((t=>{e.ws.once("disconnect",t),e.ws.disconnect(),e.mqtt.disconnect()})),"established"===e.sessionState&&Gi("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!e.ws.connected},za=e=>{const t=be();Gi("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,$a()},Ha=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Va=e=>{const t=be(),n=Ha.map((n=>dt(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new pe(t.message,t.code,"fatal"):new ye(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Wa=e=>{const t=be();return dt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Ka=e=>{const t=ce("channelMarker")({userId:rt()._id,entityId:e.channelId});ze(["channelMarker","get",t],!0)},Qa=[],Ja=async(e,t,n)=>{var r,o,s;const i=be();let a;i.log("client/api/connectClient",Object.assign({apiKey:i.apiKey,sessionState:i.sessionState},e)),i.userId&&i.userId!==e.userId&&(await $a(),Qa.forEach((e=>e()))),null!==(r=e.deviceId)&&void 0!==r||(e.deviceId=Ki());try{const{users:n}=await Yi(e);c=i.ws,l=i.emitter,ct.forEach((e=>{c.on(e,(t=>{l.emit(e,t)}))})),await new Promise((e=>{i.ws.once("connect",e),i.ws.open()})),i.userId=e.userId,i.sessionHandler=t,a=i.accessTokenExpiryWatcher(null===(o=i.token)||void 0===o?void 0:o.expiresAt,null===(s=i.token)||void 0===s?void 0:s.issuedAt,t),ot(n[0])}catch(e){throw Gi("notLoggedIn"),e}var c,l;return!0!==(null==n?void 0:n.disableRTE)&&await gt(),Qa.push(Wa((e=>{za("globalBan"),Qa.forEach((e=>e())),a()})),(e=>{const t=be();return dt(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{za(),Qa.forEach((e=>e())),a()})),qa((e=>{e.userId===i.userId&&(za("userDeleted"),Qa.forEach((e=>e())),a())})),(e=>{const t=be();return dt(t,"client/onTokenExpired","tokenExpired",e)})((e=>{Gi(e),$a(),Qa.forEach((e=>e()))})),ga(Ka),ma(Ka),Na()),i.ws.connected},Ga=()=>{let e,t=!1;const n=be();n.log("initiating access token renewal");const r=async r=>{const{userId:o,displayName:s}=rt(),i={userId:o,displayName:s,authToken:r,deviceId:Ki()};"tokenExpired"===n.sessionState?await Ja(i,n.sessionHandler):await Yi(i),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(Ga())}),g)}}},Ya=3e5,Xa=(e,t,n)=>{const r=setInterval((()=>{if((e=>Date.now()>Date.parse(e)-Ya)(e))return ht("tokenExpired","tokenExpired"),void at((()=>n.sessionWillRenewAccessToken(Ga())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),o=Date.parse(n),s=Date.now();return s>o+.8*(r-o-Ya)&&s<r})({expiresAt:e,issuedAt:t})&&n.sessionWillRenewAccessToken(Ga())}),g);return()=>clearInterval(r)},Za=async e=>{const t=be();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:a}),ia("local.feedMarker.fetched",s),aa("local.channelMarker.fetched",r),ca("local.subChannelMarker.fetched",o),sa("local.userMarker.fetched",i),{data:n,hasMore:n.feedMarkers.length>0}},ec=e=>{const t=be();return dt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{e(t.feedMarkers[0])}))},tc=e=>{const t=be();return dt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))};function nc(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>nc(e[n],t[n])))}const rc=(e,t,n,r,o,s)=>{const{forceDispatch:i,callbackDataSelector:a,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=be();let u;l||console.log("For using Live Object feature you need to enable Cache!");let d=!1;const h=[],f=e=>{const{data:n}=e,r=Zi(e,["data"]);c&&!c(n,u)||t(Object.assign({data:a(n)},r)),u=n};return h.push(...o.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(u&&!r&&nc(u,t)||f({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=re(r,e,!0);se(t,(({error:e,data:t,loading:n,origin:r,cachedAt:o})=>{-5===o?(f({data:t,origin:r,loading:!1,error:new ge("Observing unsynced object is not supported by Live Object.",800800,"error")}),d=!0,h.forEach((e=>e()))):d||f({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}},oc=async e=>{const t=be();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{_(null==t?void 0:t.code)&&wa("channel",e)})),t}const o=await pa(r),s=t.cache&&Date.now();return t.cache&&Xi(o,{cachedAt:s}),{data:o.channels,cachedAt:s}};oc.locally=e=>{var t;const n=be();if(n.log("channel/getChannelByIds.locally",e),!n.cache)return;const r=e.map((e=>De(["channel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const sc=async e=>{const t=be();let n;t.log("channel/getChannel",e),ba("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await pa(r)}catch(t){throw _(null==t?void 0:t.code)&&wa("channel",e),t}const r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{channels:o}=n;return{data:o.find((t=>t.channelId===e)),cachedAt:r}};sc.locally=e=>{const t=be();if(t.log("channel/getChannel.locally",e),!t.cache)return;const n=De(["channel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ic=e=>{const t=be();return dt(t,"onChannelCreated","channel.created",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])}))},ac=e=>{const t=be(),n=[dt(t,"onChannelUpdated","channel.updated",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])})),dt(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{n.forEach((e=>e()))}},cc=e=>{const t=be();return dt(t,"onChannelJoined","channel.joined",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o[0])}))},lc=e=>{const t=be();return dt(t,"onChannelLeft","channel.left",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o[0])}))},uc=e=>{const t=be();return dt(t,"onChannelMuted","channel.setMuted",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])}))},dc=e=>{const t=be();return dt(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o.find((e=>"member"===e.membership)))}))},hc=e=>{const t=be();return dt(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o[0])}))},fc=e=>{const t=be();return dt(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o.find((e=>"none"===e.membership)))}))},pc=e=>!0===e&&void 0;function gc(e,t){const{channelPublicId:n,childCount:r,creatorPublicId:o,mentionedUsers:s,messageFeedId:i,myReactions:a,reactionCount:c,reactions:l,referenceId:u,segment:d,messageId:h}=e,f=Zi(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId"]),{readCount:p,deliveredCount:g}=ra(e,t);let m;u&&(m=De(["message","get",u])),m||(m=De(["message","get",h]));const y=Object.assign(Object.assign({},f),{messageId:h,channelId:n,channelSegment:d,childrenNumber:r,creatorId:o,reactions:null!=l?l:{},reactionsCount:c,subChannelId:i,uniqueId:m?m.data.uniqueId:h,readCount:p,deliveredCount:g,referenceId:u});return s&&(y.mentionees=s.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),a?y.myReactions=a:(e=>{const t=be(),n=De(["message","get",e.messageId]),r=(null==n?void 0:n.data.myReactions)||[];Object.assign(e,{myReactions:r});const o=null==e?void 0:e.latestReaction;o&&o.userId===t.userId&&("add"!==o.eventName||r.includes(o.reactionName)||Object.assign(e,{myReactions:[...r,o.reactionName]}),"remove"===o.eventName&&r.includes(o.reactionName)&&Object.assign(e,{myReactions:r.filter((e=>e!==o.reactionName))}))})(y),y}const mc=async e=>{let t=[];const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Xi({messages:e.messages.map((e=>gc(e)))});try{({data:t}=await Ca(n))}catch(e){}}return Object.assign(Object.assign({},e),{messages:e.messages.map((e=>{const n=null==t?void 0:t.find((({contentId:t})=>t===e.messageId));return gc(e,n)}))})};function yc(e){var{subChannelId:t,mentionees:n}=e,r=Zi(e,["subChannelId","mentionees"]);return Object.assign({messageFeedId:t,mentionedUsers:n},r)}function vc(e){var{page:t,sortBy:n,subChannelId:r,tags:o,includeDeleted:s}=e,i=Zi(e,["page","sortBy","subChannelId","tags","includeDeleted"]);const a=Object.assign(Object.assign({},i),{messageFeedId:r,isDeleted:pc(s),options:{token:J(t||{limit:10},"afterbeforeraw")}});return void 0!==n&&(a.options.sortBy=n),o&&(a.includeTags=o),a}const bc=(e,t=!0)=>{const n=be(),r=[dt(n,"message/onMessageCreated","message.created",(async t=>{const n=await mc(t),r=n.messages[0];Xi(n),e(r)}))];return t&&dt(n,"message/onMessageCreated","local.message.created",(t=>e(t.messages[0]))),()=>{r.forEach((e=>e()))}},wc=e=>{const t=be(),n=[dt(t,"onMessageUpdated","message.updated",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])})),dt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0]))),dt(t,"onMessageUpdated","marker.marked-message",(async t=>{const n=function(e){var t,n,r;const o=["message","get"],s=null===(n=null===(t=Ue(["user","get"]))||void 0===t?void 0:t.filter((({data:t})=>t._id===e.creatorId)))||void 0===n?void 0:n[0].data;if(!s)return;const i=null===(r=Ue(o))||void 0===r?void 0:r.filter((({data:t})=>t.subChannelId===e.feedId&&t.creatorId===s.userId));return i?i.map((({data:t})=>{const{readCount:n,deliveredCount:r}=ra(t,e),s=Object.assign(Object.assign({},t),{readCount:n,deliveredCount:r,updatedAt:(new Date).toISOString()});return $e(o,s),s})):void 0}(t.contentMarkers[0]);n&&n.forEach((t=>e(t)))}))];return()=>{n.forEach((e=>e()))}},Cc=e=>{const t=be(),n=[dt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])})),dt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},_c=e=>{const t=be();return dt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},kc=e=>{const t=be();return dt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Sc=e=>{const t=be();return dt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Ac=e=>{const t=be();return dt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Ec=e=>{const t=be();return dt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Ic=e=>{const t=be();return dt(t,"message/onMessageFetched","local.message.fetched",(t=>{Xi(t),e(t.messages[0])}))},Oc=async e=>{const t=be();t.log("channel/queryChannels",e);const n=null!=e?e:{},{page:r={limit:10},displayName:o,membership:s}=n,i=Zi(n,["page","displayName","membership"]),{data:a}=await t.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:o,filter:s,options:{token:J(r,"skiplimit")}})}),{paging:c}=a,l=Zi(a,["paging"]),u=await pa(l),{channels:d}=u,h=t.cache&&Date.now();if(t.cache){Xi(u,{cachedAt:h});const e=["channel","query",Object.assign(Object.assign({},i),{options:Object.assign({},r)})];Le(e,{channels:d.map(ce("channel")),paging:c})}const f=G(c.next);return{data:d,cachedAt:h,prevPage:G(c.previous),nextPage:f}},Tc=async e=>{const t=be();t.log("channel/queryChannelMembers",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get(`/api/v4/channels/${encodeURIComponent(o.channelId)}/users`,{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i}=s,a=Zi(s,["paging"]),c=await pa(a),{channelUsers:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c);const e=["channelUsers","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{channelUsers:l.map((({channelId:e,userId:t})=>ce("channelUsers")({channelId:e,userId:t}))),paging:i})}return{data:l,cachedAt:u,nextPage:G(i.next),prevPage:G(i.previous)}};Tc.locally=e=>{var t,n;const r=be();if(r.log("channel/queryChannelMembers.locally",e),!r.cache)return;const{page:o}=e,s=Zi(e,["page"]),i=["channelUsers","query",Object.assign(Object.assign({},s),{options:Object.assign({},o)})],{data:a,cachedAt:c}=null!==(t=De(i))&&void 0!==t?t:{};if(!(null==a?void 0:a.channelUsers.length))return;const l=a.channelUsers.map((e=>De(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),u=G(null==a?void 0:a.paging.previous),d=G(null==a?void 0:a.paging.next);return l.length===(null===(n=null==a?void 0:a.channelUsers)||void 0===n?void 0:n.length)?{data:l,cachedAt:c,prevPage:u,nextPage:d}:void 0};const xc=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["channelUsers","collection",{channelId:e.channelId}],g=t=>{let n=Ve(t,"roles",e.roles);e.memberships&&(n=n.filter((t=>!(!e.memberships.includes("muted")||!t.isMuted)||e.memberships.includes(t.membership)))),e.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),n=Ge(n,e.search));const r=e.sortBy?e.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?et:Ze),n},m=(e,n=!1)=>{var r,o;const s=null!==(r=e.data.map((e=>De(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:v,data:n?g(s):s,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},y=t=>(t,n)=>{var r;if(e.channelId!==n.channelId)return;const o=null===(r=De(d))||void 0===r?void 0:r.data;if(!o)return;const s=ce("channelUsers")({channelId:e.channelId,userId:n.userId});"none"===n.membership?o.data=o.data.filter((e=>e!==s)):o.data.includes(s)||(o.data=[s,...o.data]),Le(d,o),m(o,!0)},v=(e=!1)=>{var t,n,r;const o=null===(t=De(d))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Tc,Object.assign(Object.assign({},a),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:c}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("channelUsers"))])]),Le(d,o),m(o)}),oe(l))};return u.push(cc(y()),lc(y()),dc(y()),hc(y()),ma(y()),fc(y())),v(!0),()=>{r(`getMembers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}};var Rc=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>ht("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await pa(r);n.cache&&Xi(o);const{channelUsers:s}=o;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=be();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>ht("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await pa(r);n.cache&&Xi(o);const{channelUsers:s}=o;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},getMembers:xc,searchMembers:(e,t,n)=>xc(e,t,n)});var Pc=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=be();r.log("channel/addRole",e,t,n);const{data:o}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await pa(o);r.cache&&Xi(s);const{channelUsers:i}=s;return!!i.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=be();r.log("channel/removeRole",e,t,n);const{data:o}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await pa(o);r.cache&&Xi(s);const{channelUsers:i}=s;return!!i.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=be();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),o=await pa(r),{channelUsers:s}=o,i=n.cache&&Date.now();return n.cache&&Xi(o,{cachedAt:i}),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=be();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),o=await pa(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{channelUsers:i}=o;return{data:null==i?void 0:i.filter((e=>"member"===e.membership)),cachedAt:s}}}),Mc=Object.freeze({__proto__:null,Membership:Rc,Moderation:Pc,getChannelByIds:oc,createChannel:async e=>{const t=be();let n;t.log("user/createChannel",e),n="conversation"===(null==e?void 0:e.type)?await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0})):await t.http.post("/api/v3/channels",e);const r=await pa(n.data),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{channels:s}=r;return{data:s[0],cachedAt:o}},updateChannel:async(e,t)=>{const n=be();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),o=await pa(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{channels:i}=o;return{data:i.find((t=>t.channelId===e)),cachedAt:s}},deleteChannel:async e=>{const t=be();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await sc(e)).data},joinChannel:async e=>{const t=be();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await pa(n);t.cache&&Xi(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=be();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await pa(n);t.cache&&Xi(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=be();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new pe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:o}=r;return o},unmuteChannel:async e=>{const t=be();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},markAsRead:async e=>{const t=be();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),r=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:r}),!0},onChannelCreated:ic,onChannelUpdated:ac,onChannelDeleted:ga,onChannelJoined:cc,onChannelLeft:lc,onChannelMuted:uc,onChannelMemberAdded:dc,onChannelMemberRemoved:hc,onChannelMemberBanned:ma,onChannelMemberUnbanned:fc,observeChannel:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeChannel(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.channelId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}},s=[];return s.push(ac((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),ga((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),cc((e=>o({data:e,loading:!1,origin:"event"},"onJoin"))),lc((e=>o({data:e,loading:!1,origin:"event"},"onLeft"))),uc((e=>o({data:e,loading:!1,origin:"event"},"onMute"))),dc((e=>o({data:e,loading:!1,origin:"event"},"onMemberAdded"))),hc((e=>o({data:e,loading:!1,origin:"event"},"onMemberRemoved")))),se(re(sc,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeChannel(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=be(),n=Date.now();t(`observeChannels(tmpid: ${n}) > listen`);const r=[],o=(t,n)=>{var r,o;if(e instanceof Function)return e(t);null===(r=e.onEvent)||void 0===r||r.call(e,n,t),null===(o=e[n])||void 0===o||o.call(e,t)};return r.push(ic((e=>o(e,"onCreate"))),ac((e=>o(e,"onUpdate"))),ga((e=>o(e,"onDelete"))),cc((e=>o(e,"onJoin"))),lc((e=>o(e,"onLeft"))),uc((e=>o(e,"onMute"))),dc((e=>o(e,"onMemberAdded"))),hc((e=>o(e,"onMemberRemoved")))),()=>{t(`observeChannels(tmpid: ${n}) > dispose`),r.forEach((e=>e()))}},getChannel:(e,t)=>rc(e,t,"channelId",sc,[ac,ga,cc,lc,dc,hc,ma,fc,uc,()=>bc((()=>null))]),getChannels:(e,t,n)=>{const{log:r,cache:o,userId:s}=be();o||console.log(p);const i=Date.now();r(`getChannels(tmpid: ${i}) > listen`);const{limit:a}=e,c=Zi(e,["limit"]),l=null!=a?a:h,{policy:u=f}=null!=n?n:{},d=[],g=["channel","collection",{}],m=n=>{var r,o;let i=null!==(r=n.data.map((e=>De(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];switch(i=He(i,"isDeleted",e.isDeleted),i=He(i,"displayName",e.displayName),e.types&&(i=i.filter((t=>{var n;return null===(n=e.types)||void 0===n?void 0:n.includes(t.type)}))),e.tags&&(i=i.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),e.excludeTags&&(i=i.filter((t=>{var n;return!(null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.excludeTags)||void 0===n?void 0:n.includes(t)})))}))),e.membership&&s&&(i=We(i,e.membership,s)),e.sortBy){case"firstCreated":i=i.sort(Ze);break;case"lastCreated":i=i.sort(et);break;case"displayName":i=i.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ye);break;default:i=i.sort(tt)}t({onNextPage:b,data:i,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},v=e=>e=>{var t;const n=null===(t=De(g))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.channelId,...n.data])],Le(g,n),m(n))},b=(e=!1)=>{var t,n,r;const o=null===(t=De(g))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Oc,Object.assign(Object.assign({},c),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:l}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("channel"))])]),Le(g,o),m(o)}),oe(u,y))};return d.push(ic(v()),ga(v()),ac(v()),uc(v()),cc(v()),lc(v()),dc(v()),hc(v()),bc((()=>null))),b(!0),ze(g),()=>{r(`getChannels(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:da,isUnreadCountSupport:ha,convertFromRaw:fa,prepareChannelPayload:pa});const jc=e=>{const t=be();return dt(t,"onSubChannelCreated","message-feed.created",(async t=>{const n=await Ia(t);Xi(n),e(n.messageFeeds[0])}))},Fc=e=>{const t=be(),n=[dt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Ia(t);Xi(n),e(n.messageFeeds[0])})),dt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Bc=e=>{const t=be(),n=[dt(t,"onSubChannelDeleted","message-feed.deleted",(async t=>{const n=await Ia(t);Xi(n),e(n.messageFeeds[0])})),dt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};let Nc,Uc=[],Dc=!1,Lc=null;const qc=e=>{(!Lc||new Date(e).getTime()>new Date(Lc).getTime())&&(Lc=e)};let $c=[];const zc=e=>{$c=e},Hc=e=>$c.push(e),Vc=async()=>{if(Dc)return;if(0===$c.length)return;Dc=!0,$c=[];const e=await Za(null==Lc?(new Date).toISOString():Lc);qc(e.data.userMarkers[0].lastSyncAt),e.hasMore&&$c.push("has_more"),Dc=!1},Wc=()=>{Uc.push((()=>{const e=()=>$c.push("resume");return window.addEventListener("online",e),()=>window.removeEventListener("online",e)})(),bc((e=>{Aa(e)&&$c.push("new message")}),!1),ic((()=>$c.push("subchannel is created"))),ga((()=>$c.push("subchannel is deleted"))),cc((()=>$c.push("subchannel is joined"))),lc((()=>$c.push("subchannel is left"))),jc((()=>$c.push("subchannel is created"))),Bc((()=>$c.push("subchannel is deleted"))),ec((()=>$c.push("feed marker updated"))))},Kc=()=>{null==Nc||Nc(),Nc=void 0,zc([]),Uc.forEach((e=>e())),Uc=[]};var Qc=Object.freeze({__proto__:null,getActiveClient:be,getActiveUser:rt,setActiveUser:ot,createClient:(e,t=Bt.SG,{debugSession:n="amity",apiEndpoint:r}={})=>{var o,s;const i=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!Ft,n=Pt(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);i("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const a=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:Ut("http",t),c=null!==(s=null==r?void 0:r.mqtt)&&void 0!==s?s:Ut("mqtt",t),l=kr(a),u=(e=>{const t=Ui(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(a),h=Vi(c),f=ut(),p={version:`${d}`,apiKey:e,log:i,cache:{data:{}},http:l,ws:u,mqtt:h,emitter:f,sessionState:"notLoggedIn",accessTokenExpiryWatcher:Xa,sessionHandler:undefined,getFeedSettings:Wi,use:()=>we(p)};try{return be()}catch(e){we(p)}return p},login:Ja,logout:$a,isConnected:()=>{var e,t;const n=be();return n.log("client/api/isConnected",n),!!(n.userId&&(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&n.ws.connected)},getFeedSettings:Wi,renewal:Ga,markerSync:Za,onConnectionError:Va,onClientDisconnected:e=>Va((({code:t})=>{800211===t&&e()})),onClientBanned:Wa,onSessionStateChange:ya,getTotalUnreadCount:e=>{const{_id:t}=rt();if(!t)throw new pe("The _id has not been defined in ActiveUser",8e5,"error");return rc(t,e,"userId",ka,[tc],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0},callbackFilter:(e,t)=>(null==e?void 0:e.unreadCount)!==(null==t?void 0:t.unreadCount)})},getMarkerSyncEvents:()=>$c,setMarkerSyncEvents:zc,pushMarkerSyncEvent:Hc,markerSyncTrigger:Vc,startUnreadSync:async()=>{await(async()=>{const{data:e}=await ka();qc(e.lastSyncAt)})(),Hc("start syncing"),Nc||(Nc=va(Vc,2e3)),Wc()},stopUnreadSync:Kc,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Kc())});const Jc=async e=>{const t=be();let n={};if(e){const{token:t,limit:r}=e;n={limit:r,token:t}}t.log("user/queryBlockedUsers");const{data:r}=await t.http.get("/api/v4/me/user-blocks",{params:n}),{paging:o}=r,s=Zi(r,["paging"]),{users:i}=s,a=t.cache&&Date.now();if(t.cache){Xi(s,{cachedAt:a});Le(["blockedUsers","query",n],{users:i.map(ce("user")),paging:o})}const{next:c,previous:l,total:u}=o,d=Y(c);return{data:i,prevPage:Y(l),nextPage:d,total:u,cachedAt:a}};Jc.locally=(e={})=>{var t,n,r;const o=be();if(o.log("user/queryBlockedUsers.locally"),!o.cache)return;let s={};if(e){const{token:t,limit:n}=e;s={token:t,limit:n}}const i=["blockedUsers","query",s],{data:a,cachedAt:c}=null!==(t=De(i))&&void 0!==t?t:{},l=null!==(n=null==a?void 0:a.users.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[],u=Y(null==a?void 0:a.paging.next),d=Y(null==a?void 0:a.paging.previous);return l.length>0&&l.length===(null===(r=null==a?void 0:a.users)||void 0===r?void 0:r.length)?{data:l,nextPage:u,prevPage:d,total:null==a?void 0:a.paging.total,cachedAt:c}:void 0};const Gc=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getBlockedUsers(tmpid: ${s}) > listen`);const{limit:i,token:a}=e,c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["blockedUsers","collection",{}],g=(e=!1)=>{var n,r;const o=null===(n=De(d))||void 0===n?void 0:n.data,s=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Jc,{limit:c,token:J(e||null==o?void 0:o.params.page,"afterbeforeraw")});se(i,(({data:e,loading:n,error:r,nextPage:o,total:i})=>{const a={loading:n,error:r,params:{page:o,total:i},data:s};e&&(a.data=[...new Set([...s,...e.map(ce("user"))])]),Le(d,a),(e=>{var n,r;const o=null!==(n=e.data.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];t({onNextPage:g,data:o,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})})(a)}),oe(l,y))};return u.push((()=>{})),g(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),u.forEach((e=>e())),ze(d)}},Yc=(e,t)=>{const n=be();return dt(n,e,e,(e=>{var r,o;if(n.cache){Xi(e);[...null!==(r=Ue(["followers","query"]))&&void 0!==r?r:[],...null!==(o=Ue(["followings","query"]))&&void 0!==o?o:[]].filter((({key:t})=>t[2].userId===e.follows[0].from||t[2].userId===e.follows[0].to)).forEach((({key:e,data:t})=>$e(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},Xc=e=>Yc("follow.created",e),Zc=e=>Yc("follow.unfollowed",e),el=e=>Yc("follow.followerDeleted",e),tl=e=>Yc("follow.requested",e),nl=e=>Yc("follow.requestCanceled",e),rl=e=>Yc("follow.accepted",e),ol=e=>Yc("follow.requestDeclined",e),sl=async e=>{var t,n;const r=be();r.log("follow/getFollowInfo",e);const{data:o}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=r.cache&&Date.now(),i="follows"in o?Object.assign(Object.assign({},o.followCounts[0]),{status:null===(n=null===(t=o.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):o.followCounts[0];return r.cache&&Le(["followInfo","get",e],i,{cachedAt:s}),{data:i,cachedAt:s}};sl.locally=e=>{const t=be();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=De(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const il=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([sl(t.from),sl(t.to)]);e(n),e(r)},n=[Yc("follow.created",t),Yc("follow.requested",t),Yc("follow.accepted",t),Yc("follow.unfollowed",t),Yc("follow.requestCanceled",t),Yc("follow.requestDeclined",t),Yc("follow.followerDeleted",t)];return()=>{n.forEach((e=>e()))}},al=async(e,t)=>{const n=be();n.log(`follow/queryF${e.substring(1)}`,t);const{userId:r,page:o}=t,s=Zi(t,["userId","page"]),{data:i}=await n.http.get(n.userId===r?`/api/v4/me/${e}`:`/api/v4/users/${r}/${e}`,{params:Object.assign(Object.assign({},s),{token:J(o,"afterbeforeraw")})}),{paging:a}=i,c=Zi(i,["paging"]),{follows:l}=c,u=n.cache&&Date.now();if(n.cache){Xi(c,{cachedAt:u});const t=["follow","query",Object.assign(Object.assign({},s),{userId:r,options:Object.assign({},o),type:e})];Le(t,{follows:l.map(ce("follow")),paging:a})}const d=Y(a.next);return{data:l,cachedAt:u,prevPage:Y(a.previous),nextPage:d}};al.locally=(e,t)=>{var n,r;const o=be();if(o.log(`follow/queryF${e.substring(1)}.locally`,t),!o.cache)return;const{page:s}=t,i=Zi(t,["page"]),a=["follow","query",Object.assign(Object.assign({},i),{options:Object.assign({},s),type:e})],{data:c,cachedAt:l}=null!==(n=De(a))&&void 0!==n?n:{};if(!(null==c?void 0:c.follows.length))return;const u=c.follows.map((e=>De(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),d=Y(null==c?void 0:c.paging.previous),h=Y(null==c?void 0:c.paging.next);return u.length===(null===(r=null==c?void 0:c.follows)||void 0===r?void 0:r.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};const cl=async e=>al("followers",e);cl.locally=e=>al.locally("followers",e);const ll=async e=>al("following",e);ll.locally=e=>al.locally("following",e);var ul=Object.freeze({__proto__:null,blockUser:async e=>{const t=be();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:s}=n,i={follows:o};return t.cache&&(Xi(i,{cachedAt:r}),$e(["followInfo","get",e],s[0],{cachedAt:r})),ht("follow.unfollowed",i),n},unBlockUser:async e=>{const t=be();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:s}=n,i={follows:o};return t.cache&&(Xi(i,{cachedAt:r}),$e(["followInfo","get",e],s[0],{cachedAt:r})),ht("follow.created",i),n},getBlockedUsers:(e,t,n)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),Gc(e,t,n)),follow:async e=>{const t=be();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:r}),ht("accepted"===n.follows[0].status?"follow.created":"follow.requested",n),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=be();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&Xi(n),ht("follow.unfollowed",n),!0},acceptFollower:async e=>{const t=be();t.log("follow/acceptFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Xi(n),ht("follow.accepted",n),!0},declineFollower:async e=>{const t=be();t.log("follow/declineFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Xi(n),ht("follow.requestDeclined",n),!0},onUserFollowed:Xc,onUserUnfollowed:Zc,onFollowerDeleted:el,onFollowerRequested:tl,onFollowRequestCanceled:nl,onFollowRequestAccepted:rl,onFollowRequestDeclined:ol,onFollowInfoUpdated:il,observeFollowInfo:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeFollowInfo(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=[];return i.push(il((t=>((t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.userId)===e&&s(t,n)})({data:t,loading:!1,origin:"event"},"onUpdate")))),se(re(sl,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observeFollowInfo(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFollowers(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(n.from===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(tl((e=>s(e,"onRequested"))),rl((e=>s(e,"onAccepted"))),ol((e=>s(e,"onDeclined"))),nl((e=>s(e,"onCanceled"))),Xc((e=>s(e,"onFollowed"))),Zc((e=>s(e,"onUnfollowed"))),el((e=>s(e,"onDeleted")))),()=>{n(`observeFollowers(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFollowings(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(n.to===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(tl((e=>s(e,"onRequested"))),rl((e=>s(e,"onAccepted"))),ol((e=>s(e,"onDeclined"))),nl((e=>s(e,"onCanceled"))),Xc((e=>s(e,"onFollowed"))),Zc((e=>s(e,"onUnfollowed"))),el((e=>s(e,"onDeleted")))),()=>{n(`observeFollowings(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},getFollowers:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["follow","collection",{userId:e.userId,type:"follower"}],p=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(s=He(s,"status",e.status)),t({onNextPage:m,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.userId===n.to&&o&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?o.data=o.data.filter((e=>e!==ce("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(o.data=[...new Set([ce("follow")(n),...o.data])]),Le(d,o),p(o))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(cl,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("follow"))])]),Le(d,o),p(o)}),oe(l))};return u.push(tl(g("onRequested")),rl(g("onAccepted")),ol(g("onDeclined")),nl(g("onCanceled")),Xc(g("onFollowed")),Zc(g("onUnfollowed")),el(g("onDeleted"))),m(!0),()=>{r(`getFollowers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowings(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["follow","collection",{userId:e.userId,type:"following"}],p=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(s=He(s,"status",e.status)),t({onNextPage:m,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.userId===n.from&&o&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?o.data=o.data.filter((e=>e!==ce("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(o.data=[...new Set([ce("follow")(n),...o.data])]),Le(d,o),p(o))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(ll,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("follow"))])]),Le(d,o),p(o)}),oe(l))};return u.push(tl(g("onRequested")),rl(g("onAccepted")),ol(g("onDeclined")),nl(g("onCanceled")),Xc(g("onFollowed")),Zc(g("onUnfollowed")),el(g("onDeleted"))),m(!0),()=>{r(`getFollowings(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},getFollowInfo:(e,t)=>rc(e,t,"userId",sl,[il],{forceDispatch:!0})});const dl=async e=>{const t=be();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("user.fetched",r),{data:r.users,cachedAt:o}};dl.locally=e=>{var t;const n=be();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>De(["user","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const hl=e=>La("user.updated",e),fl=e=>La("user.flagged",e),pl=e=>La("user.unflagged",e),gl=e=>La("user.flagCleared",e),ml=e=>La("user.fetched",e),yl=async e=>{const t=be();let n;t.log("user/getUser",e),ba("user",e);try{n=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&wa("user",e),t}const r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{users:o}=n;return ht("user.fetched",n),{data:o.find((t=>t.userId===e)),cachedAt:r}};yl.locally=e=>{const t=be();return t.log("user/getUser.locally",e),t.cache&&De(["user","get",e])};const vl=async(e={})=>{const t=be();t.log("user/queryUsers",e);const{page:n={limit:10},displayName:r,filter:o="all",sortBy:s="displayName"}=e,i=Zi(e,["page","displayName","filter","sortBy"]),{data:a}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},i),{keyword:r,filter:o,sortBy:s,options:{token:J(n,"skiplimit")}})}),{paging:c}=a,l=Zi(a,["paging"]),{users:u}=l,d=t.cache&&Date.now();if(t.cache){Xi(l,{cachedAt:d});const t=["user","query",Object.assign(Object.assign({},e),{options:Object.assign({},n)})];Le(t,{users:u.map(ce("user")),paging:c})}ht("user.fetched",a);return{data:u,cachedAt:d,prevPage:G(c.previous),nextPage:G(c.next)}};vl.locally=(e={})=>{var t,n,r;const o=be();if(o.log("user/queryUsers.locally",e),!o.cache)return;const{page:s={limit:10}}=null!=e?e:{},i=["user","query",Object.assign(Object.assign({},e),{options:Object.assign({},s)})],{data:a,cachedAt:c}=null!==(t=De(i))&&void 0!==t?t:{},l=null!==(n=null==a?void 0:a.users.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[],u=G(null==a?void 0:a.paging.previous),d=G(null==a?void 0:a.paging.next);return l.length>0&&l.length===(null===(r=null==a?void 0:a.users)||void 0===r?void 0:r.length)?{data:l,cachedAt:c,prevPage:u,nextPage:d}:void 0};const bl=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`liveUsers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["user","collection",{}],g=t=>{let n=He(t,"displayName",e.displayName);switch(e.sortBy){case"firstCreated":n=n.sort(Ze);break;case"lastCreated":n=n.sort(et);break;default:n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ye)}return n},m=(e,n=!1)=>{var r,o;const s=null!==(r=e.data.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:v,data:n?g(s):s,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},y=e=>e=>{var t;const n=null===(t=De(d))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Le(d,n),m(n,!0))},v=(e=!1)=>{var t,n,r;const o=null===(t=De(d))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(vl,Object.assign(Object.assign({},a),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:c}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("user"))])]),Le(d,o),m(o)}),oe(l))};return u.push(hl(y()),qa(y()),fl(y()),pl(y()),gl(y())),v(!0),()=>{r(`liveUsers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}};var wl=Object.freeze({__proto__:null,Relationship:ul,getUserByIds:dl,updateUser:async(e,t)=>{const n=be();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{users:s}=r;return ht("user.updated",r),{data:s.find((t=>t.userId===e)),cachedAt:o}},flagUser:async e=>{const t=be();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Xi(n),ht("user.flagged",n),!!n},unflagUser:async e=>{const t=be();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Xi(n),ht("user.unflagged",n),!!n},isUserFlaggedByMe:async e=>{var t,n;const r=be();r.log("user/isUserFlaggedByMe",e);const{result:o,isFlagByMe:s}=null!==(t=await Di(r,"user.isFlagByMe",{userId:e}))&&void 0!==t?t:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n},onUserUpdated:hl,onUserDeleted:qa,onUserFlagged:fl,onUserUnflagged:pl,onUserFlagCleared:gl,getUser:(e,t)=>rc(e,t,"userId",yl,[ml,hl,qa,fl,pl,gl]),getUsers:bl,observeUser:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeUser(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.userId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}},s=[];return s.push(hl((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),qa((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),fl((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),pl((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),gl((e=>o({data:e,loading:!1,origin:"event"},"onFlagCleared")))),se(re(yl,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeUser(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},getBlockedUsers:Gc,searchUserByDisplayName:(e,t,n)=>bl(Object.assign(Object.assign({},e),{filter:"all"}),t,n)});const Cl=async e=>{const t=be();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Xi({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};Cl.locally=e=>{const t=be();if(t.log("file/getFile.locally",e),!t.cache)return;const n=De(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};var _l=Object.freeze({__proto__:null,getFile:Cl,uploadFile:async(e,t)=>{const n=be();if(n.log("file/uploadFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/files",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},deleteFile:async e=>{const t=be();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),ze(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:async(e,t,n)=>{const r=be();if(r.log("file/uploadVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),i=r.cache&&Date.now();return r.cache&&Xi({files:s},{cachedAt:i}),{data:s,cachedAt:i}},uploadImage:async(e,t)=>{const n=be();if(n.log("file/uploadImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/images",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},createImage:async(e,t)=>{const n=be();if(n.log("file/createImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/images",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},createFile:async(e,t)=>{const n=be();if(n.log("file/createFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/files",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},createVideo:async(e,t,n)=>{const r=be();if(r.log("file/createVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),i=r.cache&&Date.now();return r.cache&&Xi({files:s},{cachedAt:i}),{data:s,cachedAt:i}},observeFile:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFile(tmpid: ${r}) > listen`);return se(re(Cl,e),(n=>n.data&&((n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.fileId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}})(n,"onFetch"))),()=>{n(`observeFile(tmpid: ${r}) > dispose`)}}});const kl=async e=>{const t=be();t.log("role/queryRoles",e);const n=null!=e?e:{},{page:r={limit:10},displayName:o,sortBy:s}=n,i=Zi(n,["page","displayName","sortBy"]),{data:a}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:o,sortBy:s,options:{token:J(r,"skiplimit")}})}),{paging:c}=a,l=Zi(a,["paging"]),{roles:u}=l,d=t.cache&&Date.now();t.cache&&Xi(l,{cachedAt:d});const h=G(c.next);return{data:u,cachedAt:d,prevPage:G(c.previous),nextPage:h}};kl.locally=e=>{be().log("role/queryRoles.locally",e)};const Sl=async e=>{const t=be();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Xi({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Sl.locally=e=>{const t=be();if(t.log("role/getRole.locally",e),!t.cache)return;const n=De(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Al=(e,t)=>{"message"===e?ht("local.message.updated",{messages:[t]}):"post"===e?ht("post.updated",{posts:[t]}):"comment"===e&&ht("comment.updated",{comments:[t]})},El=async(e,t=!1)=>{const n=be();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),ba("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await mc(t)}catch(t){throw _(null==t?void 0:t.code)&&wa("message",e),t}const o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{messages:s}=r;return ht("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:o}};El.locally=e=>{const t=be();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=De(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Il=async e=>{const t=be();let n;t.log("post/getPost",e),ba("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&wa("post",e),t}const r=ta(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:o}};Il.locally=e=>{const t=be();if(t.log("post/getPost.locally",e),!t.cache)return;const n=De(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ol=async e=>{const t=be();let n;t.log("comment/getComment",e),ba("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&wa("comment",e),t}const r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{comments:o}=n;return{data:o.find((t=>t.commentId===e)),cachedAt:r}};Ol.locally=e=>{const t=be();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=De(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Tl=(e,t)=>{var n,r;if(be().userId!==t.reactor.userId)return;let o,s;if("post.addReaction"===e||"post.removeReaction"===e){const e=t.posts[0];s=null===(n=De(["post","get",e.postId]))||void 0===n?void 0:n.data,o=e}else{const e=t.comments[0];s=null===(r=De(["comment","get",e.commentId]))||void 0===r?void 0:r.data,o=e}if(s&&s.myReactions)if("post.addReaction"===e||"comment.addReaction"===e){if(s.myReactions.includes(t.reactor.reactionName))return;Object.assign(o,{myReactions:[...s.myReactions,t.reactor.reactionName]})}else{if(!s.myReactions.includes(t.reactor.reactionName))return;Object.assign(o,{myReactions:s.myReactions.filter((e=>e!==t.reactor.reactionName))})}},xl=async(e,t,n)=>{const r=be();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}),r.cache){const n=De([e,"get",t]);(null==n?void 0:n.data)&&Le([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};xl.optimistically=(e,t,n)=>{var r,o,s,i,a;const c=be();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=De([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const u=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(o=l.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return $e([e,"get",t],u,{cachedAt:-5}),Al(e,u),null!==(a=null===(i=null==u?void 0:u.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==a&&a};const Rl=async(e,t,n)=>{const r=be();if(r.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}}),r.cache){const n=De([e,"get",t]);(null==n?void 0:n.data)&&Le([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};Rl.optimistically=(e,t,n)=>{var r,o,s,i,a;const c=be();if(c.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=De([e,"get",t]);if(!(null==l?void 0:l.data)||!(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const u=Object.assign(Object.assign({},l.data),{reactionsCount:Math.max(0,l.data.reactionsCount-1),myReactions:(null!==(o=l.data.myReactions)&&void 0!==o?o:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:Math.max(0,(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)-1)})});return $e([e,"get",t],u,{cachedAt:-5}),Al(e,u),null!==(a=!(null===(i=null==u?void 0:u.myReactions)||void 0===i?void 0:i.includes(n)))&&void 0!==a&&a};const Pl=(e,t)=>{const n=be();return dt(n,e,e,(r=>{var o;if(n.cache){const{communities:n}=r,s=Zi(r,["communities"]),i=ta(s,"communityUsers");Xi(i),(null==n?void 0:n[0])&&!["post.updated"].includes(e)&&ht("community.updated",{communities:n,categories:[],communityUsers:[],feeds:[],files:[],users:[]});const a=De(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(o=Ue(["post","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===a.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>$e(e,t,{cachedAt:-1})))}t(a.data)}else t(r.posts[0])}))},Ml=e=>Pl("post.created",e),jl=e=>Pl("post.updated",e),Fl=e=>Pl("post.deleted",e),Bl=e=>Pl("post.approved",e),Nl=e=>Pl("post.declined",e),Ul=e=>Pl("post.flagged",e),Dl=e=>Pl("post.unflagged",e),Ll=e=>{const t=be();return dt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){Tl("post.addReaction",n);const t=Zi(n,["reactor"]);Xi(t);const r=De(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},ql=e=>{const t=be();return dt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){Tl("post.removeReaction",n);const t=Zi(n,["reactor"]);Xi(t);const r=De(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},$l=(e,t)=>{const n=be();return dt(n,e,e,(r=>{var o;if(n.cache){Xi(r);const n=De(["comment","get",r.comments[0].commentId]);if(["comment.created"].includes(e)){const e=null===(o=Ue(["comment","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>$e(e,t,{cachedAt:-1})))}t(n.data)}else t(r.comments[0])}))},zl=e=>$l("comment.created",e),Hl=e=>$l("comment.updated",e),Vl=e=>$l("comment.deleted",e),Wl=e=>$l("comment.flagged",e),Kl=e=>$l("comment.unflagged",e),Ql=e=>{const t=be();return dt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){Tl("comment.addReaction",n);const t=Zi(n,["reactor"]);Xi(t);const r=De(["comment","get",n.comments[0].commentId]);e(r.data)}else e(n.comments[0])}))},Jl=e=>{const t=be();return dt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){Tl("comment.removeReaction",n);const t=Zi(n,["reactor"]);Xi(t);const r=De(["comment","get",n.comments[0].commentId]);e(r.data)}else e(n.comments[0])}))},Gl=(e,t,n)=>{const r=be(),o=(r,o,s)=>{r===e&&o===t&&n(s)};if("message"===e){const e=async e=>{const t=await mc(e);if(!t.messages[0].latestReaction)return;const n=t.messages[0].latestReaction,{eventName:r,referenceId:s,referenceType:i,userDisplayName:a}=n,c=Zi(n,["eventName","referenceId","referenceType","userDisplayName"]);"add"===r&&(Xi(t),Xi({reactions:[c]}),o("message",t.messages[0].messageId,c))};return dt(r,"reaction/onReactorAdded","message.updated",e)}if("post"===e){return dt(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("post",e.posts[0].postId,t)}))}return dt(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},Yl=(e,t,n)=>{const r=be(),o=(r,o,s)=>{r===e&&o===t&&n(s)};if("message"===e){const e=async e=>{const t=await mc(e);if(!t.messages[0].latestReaction)return;const n=t.messages[0].latestReaction,{eventName:r,referenceId:s,referenceType:i}=n,a=Zi(n,["eventName","referenceId","referenceType"]);"remove"===r&&(Xi(t),Xi({reactions:[a]}),o("message",t.messages[0].messageId,a))};return dt(r,"reaction/onReactorRemoved","message.updated",e)}if("post"===e){return dt(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("post",e.posts[0].postId,t)}))}return dt(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},Xl=async e=>{const t=be();t.log("reaction/queryReactions",e);const n=null!=e?e:{},{page:r={limit:10}}=n,o=Zi(n,["page"]),{data:s}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},o),{options:{token:J(r,"afterbeforeraw")}})}),{paging:i}=s,a=Zi(s,["paging"]),{reactions:c}=a;Xi(Object.assign(Object.assign({},a),{reactions:c[0].reactors}));const l=Y(i.next);return{data:c,prevPage:Y(i.previous),nextPage:l}};var Zl=Object.freeze({__proto__:null,addReaction:xl,removeReaction:Rl,onReactionAdded:(e,t,n)=>{const r=r=>{ce(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await mc(e),o=De(["message","get",n.messages[0].messageId]),s=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xi(n),s&&r(n.messages[0])};return dt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Ll(r):Ql(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{ce(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await mc(e),o=De(["message","get",n.messages[0].messageId]),s=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xi(n),s&&r(n.messages[0])};return dt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?ql(r):Jl(r)},onReactorAdded:Gl,onReactorRemoved:Yl,getReactions:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`liveReactions(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],p=e=>{var n,r;const o=null!==(n=e.data.map((e=>De(["reaction","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];t({onNextPage:m,data:o,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},g=e=>t=>{var n;const r=null===(n=De(d))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),Le(d,r),p(r))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(Xl,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e[0].reactors.map(ce("reaction"))])]),Le(d,o),p(o)}),oe(l))};return u.push(Gl(a.referenceType,a.referenceId,g("onAdded")),Yl(a.referenceType,a.referenceId,g("onRemoved"))),m(!0),()=>{r(`liveReactions(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}}),eu={post:{domainName:"posts",eventName:"v3/post.isflagbyme",primaryKey:"postId"},comment:{domainName:"comments",eventName:"v3/comment.isflagbyme",primaryKey:"commentId"},message:{domainName:"messages",eventName:"v3/message.isFlaggedByMe",primaryKey:"messageId"},user:{domainName:"users",eventName:"user.isFlagByMe",primaryKey:"userId"}};const tu=async e=>{const t=be();t.log("message/getMessages",e);const{data:n}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),r=await mc(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{messages:s}=r;return ht("local.message.fetched",{messages:s}),{data:s,cachedAt:o}};tu.locally=e=>{var t;const n=be();if(n.log("message/getMessages.locally",e),!n.cache)return;const r=e.map((e=>De(["message","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};var nu={},ru={},ou={};Object.defineProperty(ou,"__esModule",{value:!0}),ou.bytesToString=ou.stringToBytes=ou.NIL=ou.X500=ou.OID=ou.URL=ou.DNS=ou.hexToByte=ou.byteToHex=void 0;let su=[],iu={};for(var au=0;au<256;au++)su[au]=(au+256).toString(16).substr(1),iu[su[au]]=au;ou.byteToHex=su,ou.hexToByte=iu,ou.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ou.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",ou.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",ou.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",ou.NIL="00000000-0000-0000-0000-000000000000";ou.stringToBytes=e=>{e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t};ou.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(ru,"__esModule",{value:!0}),ru.parse=void 0;const cu=ou;ru.parse=(e,t,n)=>{let r=t&&n||0,o=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,(e=>(o<16&&t&&(t[r+o++]=cu.hexToByte[e]),"")));o<16;)t[r+o++]=0;return t};var lu={};Object.defineProperty(lu,"__esModule",{value:!0}),lu.unparse=void 0;const uu=ou;lu.unparse=(e,t)=>{let n=t||0,r=uu.byteToHex;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]};var du={},hu={};Object.defineProperty(hu,"__esModule",{value:!0});hu.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;var fu=Ce&&Ce.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(du,"__esModule",{value:!0}),du.validate=void 0;const pu=fu(hu);du.validate=e=>"string"==typeof e&&pu.default.test(e);var gu={};Object.defineProperty(gu,"__esModule",{value:!0}),gu.version=void 0;const mu=du;gu.version=e=>{if(!mu.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var yu={},vu={};Object.defineProperty(vu,"__esModule",{value:!0}),vu.stringify=void 0;const bu=du,wu=[];for(let e=0;e<256;++e)wu.push((e+256).toString(16).substr(1));vu.stringify=(e,t=0)=>{const n=(wu[e[t+0]]+wu[e[t+1]]+wu[e[t+2]]+wu[e[t+3]]+"-"+wu[e[t+4]]+wu[e[t+5]]+"-"+wu[e[t+6]]+wu[e[t+7]]+"-"+wu[e[t+8]]+wu[e[t+9]]+"-"+wu[e[t+10]]+wu[e[t+11]]+wu[e[t+12]]+wu[e[t+13]]+wu[e[t+14]]+wu[e[t+15]]).toLowerCase();if(!bu.validate(n))throw TypeError("Stringified UUID is invalid");return n};var Cu={};Object.defineProperty(Cu,"__esModule",{value:!0}),Cu.rng=void 0;Cu.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(yu,"__esModule",{value:!0}),yu.v1=void 0;const _u=vu,ku=Cu;let Su,Au,Eu=0,Iu=0;yu.v1=(e,t,n=0)=>{let r=t&&n||0;const o=t||new Uint8Array(16);let s=e&&e.node?e.node:Su,i=e&&e.clockseq?e.clockseq:Au;if(null==s||null==i){const t=e&&e.random?e.random:e&&e.rng?e.rng():ku.rng();null==s&&(s=Su=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==i&&(i=Au=16383&(t[6]<<8|t[7]))}let a=e&&e.msecs?e.msecs:Date.now(),c=e&&e.nsecs?e.nsecs:Iu+1;const l=a-Eu+(c-Iu)/1e4;if(l<0&&e&&!e.clockseq&&(i=i+1&16383),(l<0||a>Eu)&&e&&!e.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Eu=a,Iu=c,Au=i,a+=122192928e5;const u=(1e4*(268435455&a)+c)%4294967296;o[r++]=u>>>24&255,o[r++]=u>>>16&255,o[r++]=u>>>8&255,o[r++]=255&u;const d=a/4294967296*1e4&268435455;o[r++]=d>>>8&255,o[r++]=255&d,o[r++]=d>>>24&15|16,o[r++]=d>>>16&255,o[r++]=i>>>8|128,o[r++]=255&i;for(let e=0;e<6;++e)o[r+e]=s[e];return t||_u.stringify(o)};var Ou={};Object.defineProperty(Ou,"__esModule",{value:!0}),Ou.v4=void 0;const Tu=lu,xu=Cu;Ou.v4=(e,t,n)=>{let r=t&&n||0,o=xu.rng();if(!e||e instanceof String||(e.random&&(o=e.random),e.rng&&(o=e.rng())),o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var s=0;s<16;s++)t[r+s]=o[s];return t||Tu.unparse(o)};var Ru={},Pu={};Object.defineProperty(Pu,"__esModule",{value:!0}),Pu.v35=void 0;const Mu=vu,ju=ru,Fu=ou;Pu.v35=(e,t,n)=>(e,r,o,s=0)=>{if("string"==typeof e&&(e=Fu.stringToBytes(e)),"string"==typeof r&&(r=ju.parse(r)),r&&16!==r.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let i=new Uint8Array(16+e.length);if(i.set(r),i.set(e,r.length),i=Fu.stringToBytes(n(Fu.bytesToString(i))),i[6]=15&i[6]|t,i[8]=63&i[8]|128,o)for(let e=0;e<16;++e)o[s+e]=i[e];return o||Mu.stringify(i)};var Bu={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.any_hmac_sha1=e.b64_hmac_sha1=e.hex_hmac_sha1=e.any_sha1=e.b64_sha1=e.hex_sha1=void 0;let t=0,n="";e.hex_sha1=e=>s(r(c(e))),e.default=e.hex_sha1;e.b64_sha1=e=>i(r(c(e)));e.any_sha1=(e,t)=>a(r(c(e)),t);e.hex_hmac_sha1=(e,t)=>s(o(c(e),c(t)));e.b64_hmac_sha1=(e,t)=>i(o(c(e),c(t)));e.any_hmac_sha1=(e,t,n)=>a(o(c(e),c(t)),n);const r=e=>u(d(l(e),8*e.length)),o=(e,t)=>{let n=l(e);n.length>16&&(n=d(n,8*e.length));let r=Array(16),o=Array(16);for(var s=0;s<16;s++)r[s]=909522486^n[s],o[s]=1549556828^n[s];var i=d(r.concat(l(t)),512+8*t.length);return u(d(o.concat(i),672))},s=e=>{for(var n,r=t?"0123456789ABCDEF":"0123456789abcdef",o="",s=0;s<e.length;s++)n=e.charCodeAt(s),o+=r.charAt(n>>>4&15)+r.charAt(15&n);return o},i=e=>{for(var t="",r=e.length,o=0;o<r;o+=3)for(var s=e.charCodeAt(o)<<16|(o+1<r?e.charCodeAt(o+1)<<8:0)|(o+2<r?e.charCodeAt(o+2):0),i=0;i<4;i++)8*o+6*i>8*e.length?t+=n:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(s>>>6*(3-i)&63);return t},a=(e,t)=>{var n,r,o,s,i=t.length,a=[],c=Array(Math.ceil(e.length/2));for(n=0;n<c.length;n++)c[n]=e.charCodeAt(2*n)<<8|e.charCodeAt(2*n+1);for(;c.length>0;){for(s=[],o=0,n=0;n<c.length;n++)o=(o<<16)+c[n],o-=(r=Math.floor(o/i))*i,(s.length>0||r>0)&&(s[s.length]=r);a[a.length]=o,c=s}var l="";for(n=a.length-1;n>=0;n--)l+=t.charAt(a[n]);var u=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(n=l.length;n<u;n++)l=t[0]+l;return l},c=e=>{for(var t,n,r="",o=-1;++o<e.length;)t=e.charCodeAt(o),n=o+1<e.length?e.charCodeAt(o+1):0,t>=55296&&t<=56319&&n>=56320&&n<=57343&&(t=65536+((1023&t)<<10)+(1023&n),o++),t<=127?r+=String.fromCharCode(t):t<=2047?r+=String.fromCharCode(192|t>>>6&31,128|63&t):t<=65535?r+=String.fromCharCode(224|t>>>12&15,128|t>>>6&63,128|63&t):t<=2097151&&(r+=String.fromCharCode(240|t>>>18&7,128|t>>>12&63,128|t>>>6&63,128|63&t));return r},l=e=>{for(var t=Array(e.length>>2),n=0;n<t.length;n++)t[n]=0;for(n=0;n<8*e.length;n+=8)t[n>>5]|=(255&e.charCodeAt(n/8))<<24-n%32;return t},u=e=>{for(var t="",n=0;n<32*e.length;n+=8)t+=String.fromCharCode(e[n>>5]>>>24-n%32&255);return t},d=(e,t)=>{e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n=Array(80),r=1732584193,o=-271733879,s=-1732584194,i=271733878,a=-1009589776,c=0;c<e.length;c+=16){for(var l=r,u=o,d=s,m=i,y=a,v=0;v<80;v++){n[v]=v<16?e[c+v]:g(n[v-3]^n[v-8]^n[v-14]^n[v-16],1);let t=p(p(g(r,5),h(v,o,s,i)),p(p(a,n[v]),f(v)));a=i,i=s,s=g(o,30),o=r,r=t}r=p(r,l),o=p(o,u),s=p(s,d),i=p(i,m),a=p(a,y)}return[r,o,s,i,a]},h=(e,t,n,r)=>e<20?t&n|~t&r:e<40?t^n^r:e<60?t&n|t&r|n&r:t^n^r,f=e=>e<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514,p=(e,t)=>{var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n},g=(e,t)=>e<<t|e>>>32-t}(Bu);var Nu=Ce&&Ce.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.v5=void 0;const Uu=Pu,Du=Nu(Bu);Ru.v5=Uu.v35("v5",80,Du.default),Object.defineProperty(nu,"__esModule",{value:!0});const Lu=ru,qu=lu,$u=du,zu=gu,Hu=yu,Vu=Ou,Wu=Ru,Ku=ou;var Qu=nu.default={parse:Lu.parse,unparse:qu.unparse,validate:$u.validate,version:zu.version,v1:Hu.v1,v4:Vu.v4,v5:Wu.v5,NIL:Ku.NIL,DNS:Ku.DNS,URL:Ku.URL,OID:Ku.OID,X500:Ku.X500};const Ju=()=>`LOCAL_${Qu.v4().toString()}`;let Gu;const Yu=async e=>{const t=be();t.log("message/createMessage",e);const n=e.referenceId||Gu||Ju();Gu=void 0;const{data:r}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},yc(e)),{referenceId:n})),o=await mc(r),{messages:s}=o,i=t.cache&&Date.now();return t.cache&&(ze(["message","get",n]),Xi(o,{cachedAt:i})),ht("local.message.created",{messages:s}),{data:s[0],cachedAt:i}};Yu.optimistically=e=>{var t,n,{referenceId:r}=e,o=Zi(e,["referenceId"]);const s=be();if(!s.cache)return;Gu=r||Ju();const i=Object.assign({messageId:Gu,uniqueId:Gu},o);s.log("message/createMessage.optimistically",i);const a=De(["subChannel","get",o.subChannelId]);if(a&&($e(["subChannel","get",o.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=De(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&$e(["channel","get",a.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const c=(new Date).toISOString(),l=Object.assign({creatorId:s.userId,channelSegment:(null!==(n=null==a?void 0:a.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:c,updatedAt:c},i);return Le(["message","get",l.messageId],l,{cachedAt:-5}),ht("local.message.created",{messages:[l]}),{cachedAt:-5,data:l}};const Xu=async(e,t)=>{const n=be();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,yc(t)),o=await mc(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{messages:i}=o;return ht("local.message.updated",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Xu.optimistically=(e,t)=>{const n=be();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=De(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return $e(["message","get",e],o,{cachedAt:-1}),ht("local.message.updated",{messages:[o]}),{data:o,cachedAt:-1}};const Zu=async(e,t)=>{const n=be();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,yc(t)),o=await mc(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{messages:i}=o;return ht("local.message.updated",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Zu.optimistically=(e,t)=>{const n=be();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=De(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return $e(["message","get",e],o,{cachedAt:-1}),ht("local.message.updated",{messages:[o]}),{data:o,cachedAt:-1}};const ed=async e=>{const t=be();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await El(e);return ht("local.message.deleted",{messages:[n.data]}),n.data};ed.optimistically=e=>{be().log("message/deleteMessage.optimistically",e);const t=De(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return $e(["message","get",e],n,{cachedAt:-1}),ht("local.message.deleted",{messages:[n]}),{data:n,cachedAt:-1}};const td=async e=>{const t=be();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await El(e);return ht("local.message.deleted",{messages:[n.data]}),n.data};td.optimistically=e=>{be().log("message/softDeleteMessage.optimistically",e);const t=De(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return $e(["message","get",e],n,{cachedAt:-1}),ht("local.message.deleted",{messages:[n]}),{data:n,cachedAt:-1}};const nd=async e=>{const t=be();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,o=Zi(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},o),{options:{token:J(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:a}=s,c=Zi(s,["paging","publicUserIds"]),l=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:l});const e=["read-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];Le(e,{users:a,paging:i})}let u=[];a.length>0&&({data:u}=await dl(a));return{data:u,cachedAt:l,prevPage:G(i.previous),nextPage:G(i.next)}};nd.locally=e=>{var t;const n=be();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,o=Zi(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=De(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:a,prevPage:G(null==i?void 0:i.paging.previous),nextPage:G(null==i?void 0:i.paging.next)}};const rd=async e=>{const t=be();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,o=Zi(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},o),{options:{token:J(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:a}=s,c=Zi(s,["paging","publicUserIds"]),l=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:l});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];Le(e,{users:a,paging:i})}let u=[];a.length>0&&({data:u}=await dl(a));return{data:u,cachedAt:l,prevPage:G(i.previous),nextPage:G(i.next)}};rd.locally=e=>{var t;const n=be();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,o=Zi(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=De(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:a,prevPage:G(null==i?void 0:i.paging.previous),nextPage:G(null==i?void 0:i.paging.next)}};const od=async e=>{const t=be();t.log("message/queryMessages",e);const n=vc(e),{data:r}=await t.http.get("/api/v5/messages",{params:n}),{paging:o}=r,s=Zi(r,["paging"]),i=await mc(s),{messages:a}=i,c=t.cache&&Date.now();if(t.cache){Xi(i,{cachedAt:c});Le(["message","query",n],{messages:a.map(ce("message")),paging:o})}ht("local.message.fetched",{messages:a});const l=Y(o.next);return{data:a,cachedAt:c,prevPage:Y(o.previous),nextPage:l}};var sd=Object.freeze({__proto__:null,getMessageByIds:tu,createMessage:Yu,updateMessage:Xu,editMessage:Zu,deleteMessage:ed,softDeleteMessage:td,markAsDelivered:async(e,t)=>{const n=be();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),o=n.cache&&Date.now();return n.cache&&Xi(r,{cachedAt:o}),!0},getReadUsers:nd,getDeliveredUsers:rd,flagMessage:async e=>{const t=be();t.log("message/flag",e);const{data:n}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await mc(n);Xi(e)}return ht("message.flagged",n),!!n},unflagMessage:async e=>{const t=be();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await mc(n);Xi(e)}return ht("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=be();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreated:bc,onMessageUpdated:wc,onMessageDeleted:Cc,onMessageFlagged:_c,onMessageUnflagged:kc,onMessageFlagCleared:Sc,onMessageReactionAdded:Ac,onMessageReactionRemoved:Ec,onMessageFetched:Ic,getMessage:(e,t)=>rc(e,t,"messageId",El,[Ic,wc,Cc,_c,kc,Sc,Ac,Ec]),getMessages:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getMessages(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["message","collection",e],g=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["message","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.includeDeleted||(s=He(s,"isDeleted",!1)),t({onNextPage:v,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},m=t=>t=>{var n;const r=null===(n=De(d))||void 0===n?void 0:n.data;e.subChannelId===(null==t?void 0:t.subChannelId)&&r&&(r.data=[...new Set([t.messageId,...r.data])],Le(d,r),g(r))},v=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(od,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("message"))])]),Le(d,o),g(o)}),oe(l,y))};return u.push(Ic(m()),bc(m()),wc(m()),Cc(m()),_c(m()),kc(m()),Sc(m()),Ac(m()),Ec(m())),v(!0),u.push((()=>ze(d))),()=>{r(`getMessages(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},observeMessage:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeMessage(tmpid: ${o}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const s=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.messageId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}},i=[];return i.push(wc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Cc((e=>s({data:e,loading:!1,origin:"event"},"onDelete")))),"no_fetch"!==n&&se(re(El,e),(e=>e.data&&s(e,"onFetch")),oe(n)),()=>{r(`observeMessages(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeMessages(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.subChannelId)===e){if(t instanceof Function)return t(n);null===(s=t.onEvent)||void 0===s||s.call(t,r,n),null===(i=t[r])||void 0===i||i.call(t,n)}};return o.push(bc((e=>s({data:e,loading:!1,origin:"event"},"onCreate"))),wc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Cc((e=>s({data:e,loading:!1,origin:"event"},"onDelete")))),()=>{n(`observeMessages(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},convertFromRaw:gc,prepareMessagePayload:mc,convertParams:yc,convertQueryParams:vc});const id=async e=>{const t=be();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Ia(n.data),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:o}};id.locally=e=>{var t;const n=be();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>De(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const ad=async(e,t=!1)=>{const n=be(),r=await Ta(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const o=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:fe(r.data.updatedAt)});return t?setTimeout((()=>{wa("subChannel",e)}),0):$e(["subChannel","get",e],o),ht("local.message-feed.deleted",{messageFeeds:[o]}),o},cd=e=>dt(be(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0])));function ld(e,t){const n=[...e,...t];if(0===n.length)return[];const r=de(n[0]),o=new Map;return n.forEach((e=>o.set(e[r],e))),Array.from(o.values())}const ud=async e=>{const t=be();t.log("channel/querySubChannels",e);const n=Oa(e),{page:r={limit:10},channelId:o,includeDeleted:s}=n,i=Zi(n,["page","channelId","includeDeleted"]),a=(await t.http.get(`/api/v5/message-feeds/channel/${o}`,{params:Object.assign(Object.assign({},i),{isDeleted:pc(s),options:{token:J(r,"skiplimit")}})})).data,{paging:c}=a,l=Zi(a,["paging"]),u=await Ia(l),d=u.messageFeeds,h=t.cache&&Date.now();if(t.cache){Xi(u,{cachedAt:h});const e=["subChannel","query",Object.assign(Object.assign({channelId:o},i),{options:Object.assign({},r)})];Le(e,{subChannels:d.map(ce("subChannel")),paging:c})}ht("local.message-feed.fetched",u);const f=G(c.next);return{data:d,cachedAt:h,prevPage:G(c.previous),nextPage:f}};ud.locally=e=>{var t,n,r;be().log("channel/querySubChannels.locally",e);const o=null!==(t=Oa(e))&&void 0!==t?t:{},{page:s={limit:10},channelId:i}=o,a=Zi(o,["page","channelId"]),c=["subChannel","query",Object.assign(Object.assign({channelId:i},a),{options:Object.assign({},s)})],{data:l,cachedAt:u}=null!==(n=De(c))&&void 0!==n?n:{};if(!(null==l?void 0:l.subChannels.length))return;const d=l.subChannels.map((e=>De(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)),h=G(null==l?void 0:l.paging.previous),f=G(null==l?void 0:l.paging.next);return d.length===(null===(r=null==l?void 0:l.subChannels)||void 0===r?void 0:r.length)?{data:d,cachedAt:u,prevPage:h,nextPage:f}:void 0};var dd=Object.freeze({__proto__:null,getSubChannelByIds:id,createSubChannel:async e=>{const t=be();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Ia(n.data),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:o}},updateSubChannel:async(e,t)=>{const n=be();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),o=await Ia(r.data),s=n.cache&&Date.now();return n.cache&&Xi(o,{cachedAt:s}),ht("message-feed.updated",r.data),{data:o.messageFeeds[0],cachedAt:s}},deleteSubChannel:ad,hardDeleteSubChannel:async e=>{be().log("channel/hardDeleteSubChannel",e);return await ad(e,!0)},softDeleteSubChannel:async e=>{be().log("channel/softDeleteSubChannel",e);return await ad(e,!1)},startReadingAPI:xa,stopReadingAPI:Ra,onSubChannelCreated:jc,onSubChannelUpdated:Fc,onSubChannelDeleted:Bc,getSubChannel:(e,t)=>rc(e,t,"subChannelId",Ta,[cd,Fc,Bc]),getSubChannels:(e,t,n)=>{const{log:r,cache:o}=be(),s=Date.now();r(`getSubChannels(tmpid: ${s}) > listen`),o||console.log(p);const{limit:i=h}=e,a=Zi(e,["limit"]),{policy:c=f}=null!=n?n:{};let l;const u=[],d=n=>{var r;let o=n.data;e.includeDeleted||(o=He(o,"isDeleted",!1)),o.sort(tt),t({onNextPage:m,data:o,hasNextPage:!!(null===(r=n.params)||void 0===r?void 0:r.page),loading:n.loading,error:n.error})},g=t=>n=>{e.channelId===n.channelId&&l&&function(e,t,n){const r=de(t),o=e.find((e=>e[r]===t[r]));return o?!nc(o,t):"onCreate"===n}(l.data,n,t)&&(l.data="onCreate"===t?[n,...l.data]:l.data.map((e=>e.subChannelId===n.subChannelId?n:e)),d(l))},m=()=>{var e;const t=l?l.data:[];if(t.length>0&&!(null==l?void 0:l.params.page))return;const n=re(ud,Object.assign(Object.assign({},a),{page:null!==(e=null==l?void 0:l.params.page)&&void 0!==e?e:{limit:i}}));se(n,(({data:e,error:n,loading:r,nextPage:o})=>{l={loading:r,error:n,params:{page:o},data:e?ld(t,e):t},d(l)}),oe(c,y))};return u.push(jc(g("onCreate")),Bc(g("onDelete")),cd(g("onFetch")),Fc(g("onUpdate"))),m(),()=>{r(`getSubChannels(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},markReadEngineOnLoginHandler:Na,startReading:async e=>{ja[e]=!0,0===Ma.length&&(Ua(),Da(e));try{return await Fa()}catch(t){return ja[e]=!1,!1}},stopReading:e=>(ja[e]=!1,Ma.forEach((e=>e())),Ma=[],Ra(e))});const hd=e=>{var t;return null!==(t=Object.keys(n).find((t=>e.needApprovalOnPostCreation===n[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===n[t].onlyAdminCanPost)))&&void 0!==t?t:r},fd=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Zi(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:hd({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)})),n=ea(e.communityUsers);return Object.assign(Object.assign({},e),{communities:t,communityUsers:n})},pd=e=>{const{postSetting:t}=e,r=Zi(e,["postSetting"]);return Object.assign(Object.assign({},r),t?n[t]:void 0)},gd=async e=>{const t=be();t.log("community/getCommunities",e);const{data:n}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),r=fd(n),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:r.communities,cachedAt:o}};gd.locally=e=>{var t;const n=be();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>De(["community","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const md=async e=>{const t=be();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communities:s}=r;return{data:s.find((t=>t.communityId===e)),cachedAt:o}};md.locally=e=>{const t=be();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=De(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const yd=async e=>{const t=be();t.log("channel/getTopTrendingCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),o=fd(r),{communities:s}=o,i=t.cache&&Date.now();if(t.cache){Xi(o,{cachedAt:i});Le(["community","top-trending",{params:{options:{limit:n}}}],{communities:s.map(ce("community"))})}return{data:s,cachedAt:i}};yd.locally=e=>{var t,n;const r=be();if(r.log("community/getTopTrendingCommunities.locally",e),!r.cache)return;const{limit:o=5}=null!=e?e:{},s=["community","top-trending",{params:{options:{limit:o}}}],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{};if(!(null==i?void 0:i.communities.length))return;const c=i.communities.map((e=>De(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return c.length===(null===(n=null==i?void 0:i.communities)||void 0===n?void 0:n.length)?{data:c,cachedAt:a}:void 0};const vd=async e=>{const t=be();t.log("channel/getRecommendedCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/recommended",{params:{options:{limit:n}}}),o=fd(r),{communities:s}=o,i=t.cache&&Date.now();if(t.cache){Xi(o,{cachedAt:i});Le(["community","recommended",{params:{options:{limit:n}}}],{communities:s.map(ce("community"))})}return{data:s,cachedAt:i}};vd.locally=e=>{var t,n;const r=be();if(r.log("community/getRecommendedCommunities.locally",e),!r.cache)return;const{limit:o=5}=null!=e?e:{},s=["community","recommended",{params:{options:{limit:o}}}],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{};if(!(null==i?void 0:i.communities.length))return;const c=i.communities.map((e=>De(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return c.length===(null===(n=null==i?void 0:i.communities)||void 0===n?void 0:n.length)?{data:c,cachedAt:a}:void 0};const bd=(e,t)=>{const n=be();return dt(n,e,e,(e=>{const r=fd(e);if(n.cache){Xi(r);const e=De(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},wd=e=>bd("community.created",e),Cd=e=>bd("community.updated",e),_d=e=>bd("community.deleted",e);function kd(e,t){return e.map((e=>{const n=t.some((t=>function(e,t){const{userId:n}=rt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:n})}))}function Sd(e,t,n){return!!e.permissions.some((e=>e===n))||t.users.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function Ad(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers[0]:"community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership))[0]:"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership))[0]:"community.userUnbanned"===e?t.communityUsers.filter((e=>!Sd(e,t,"BAN_COMMUNITY_USER")))[0]:t.communityUsers.filter((e=>!Sd(e,t,"ADD_COMMUNITY_USER")))[0]}const Ed=(e,t)=>{const n=be();return dt(n,e,e,(r=>{const o=fd(r),{communities:s,communityUsers:i}=o,a=kd(s,i);if(o.communities=a,n.cache){Xi(o);const n=De(["community","get",o.communities[0].communityId]),r=De(["communityUsers","get",ce("communityUsers")(Ad(e,o))]);t(n.data,r.data)}else t(o.communities[0],Ad(e,o))}))},Id=e=>Ed("community.userAdded",e),Od=e=>Ed("community.userRemoved",e),Td=e=>Ed("community.userBanned",e),xd=e=>Ed("community.userChanged",e),Rd=e=>Ed("community.userUnbanned",e),Pd=e=>Ed("community.roleAdded",e),Md=e=>Ed("community.roleRemoved",e),jd=e=>Ed("community.joined",e),Fd=e=>Ed("community.left",e),Bd=async e=>{const t=be();t.log("channel/queryCommunities",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),s=null!=o?o:{},{displayName:i,membership:a,includeDeleted:c}=s,l=Zi(s,["displayName","membership","includeDeleted"]),{data:u}=await t.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},l),{isDeleted:pc(c),keyword:i,filter:a,options:{token:J(r,"skiplimit")}})}),{paging:d}=u,h=Zi(u,["paging"]),f=fd(h),{communities:p}=f,g=t.cache&&Date.now();if(t.cache){Xi(f,{cachedAt:g});const e=["community","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{communities:p.map(ce("community")),paging:d})}const m=G(d.next);return{data:p,cachedAt:g,prevPage:G(d.previous),nextPage:m}};var Nd=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/addRoles",e,t,n);const{data:o}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=ta(o,"communityUsers");r.cache&&Xi(s);const{communityUsers:i}=s;return!!i.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/removeRoles",e,t,n);const{data:o}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=ta(o,"communityUsers");r.cache&&Xi(s);const{communityUsers:i}=s;return!!i.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=be();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{communityUsers:i}=o;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=be();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{communityUsers:i}=o;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:s}}});const Ud=async e=>{const t=be();t.log("community/queryCommunityMembers",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i}=s,a=Zi(s,["paging"]),c=ta(a,"communityUsers"),{communityUsers:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:u});const e=["communityUsers","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{communityUsers:l.map((({communityId:e,userId:t})=>ce("communityUsers")({communityId:e,userId:t}))),paging:i})}return{data:l,cachedAt:u,nextPage:G(i.next),prevPage:G(i.previous)}};Ud.locally=e=>{var t,n;const r=be();if(r.log("community/queryCommunityMembers",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,i=Zi(o,["page"]),a=["communityUsers","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.communityUsers.length))return;const u=c.communityUsers.map((e=>De(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.communityUsers)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};var Dd=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});ht("community.userAdded",r);const o=ta(r,"communityUsers");n.cache&&Xi(o);const{communityUsers:s}=o;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=be();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});ht("community.userRemoved",r);const o=ta(r,"communityUsers");n.cache&&Xi(o);const{communityUsers:s}=o;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getMembers:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["communityUsers","collection",{communityId:e.communityId}],g=t=>{let n=Ve(t,"roles",e.roles);e.membership&&(n=n.filter((({communityMembership:t})=>e.membership.includes(t)))),e.search&&(n=Ge(n,e.search));const r=e.sortBy?e.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?et:Ze),n},m=(e,n=!1)=>{var r,o;const s=null!==(r=e.data.map((e=>De(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:v,data:n?g(s):s,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},y=t=>(t,n)=>{var r;if(e.communityId!==n.communityId)return;const o=null===(r=De(d))||void 0===r?void 0:r.data;if(!o)return;const s=ce("communityUsers")({communityId:e.communityId,userId:n.userId});o.data=[...new Set([s,...o.data])],Le(d,o),m(o,!0)},v=(e=!1)=>{var t,n,r;const o=null===(t=De(d))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Ud,Object.assign(Object.assign({},a),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:c}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("communityUsers"))])]),Le(d,o),m(o)}),oe(l))};return u.push(Fd(y()),jd(y()),Td(y()),Rd(y()),xd(y()),Pd(y()),Md(y())),v(!0),()=>{r(`getMembers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},onCommunityUserAdded:Id,onCommunityUserRemoved:Od,onCommunityUserBanned:Td,onCommunityUserChanged:xd,onCommunityUserUnbanned:Rd,onCommunityUserRoleAdded:Pd,onCommunityUserRoleRemoved:Md,onCommunityJoined:jd,onCommunityLeft:Fd}),Ld=Object.freeze({__proto__:null,Moderation:Nd,Membership:Dd,getCommunityByIds:gd,createCommunity:async e=>{const t=be();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",pd(e));ht("community.created",n);const r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communities:s}=r;return{data:s[0],cachedAt:o}},updateCommunity:async(e,t)=>{const n=be();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,pd(t));ht("community.updated",r);const o=fd(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{communities:i}=o;return{data:i.find((t=>t.communityId===e)),cachedAt:s}},deleteCommunity:async e=>{const t=be();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await md(e);return ht("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),n.data},joinCommunity:async e=>{const t=be();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);ht("community.joined",n);const r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=be();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);ht("community.left",n);const r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:yd,getRecommendedCommunities:vd,onCommunityCreated:wd,onCommunityUpdated:Cd,onCommunityDeleted:_d,observeCommunity:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeCommunity(tmpid: ${r}) > listen`);const o=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},s=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.communityId)===e&&o(t,n)},i=[];return i.push(Cd((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),_d((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),jd((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Fd((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),Id((e=>s({data:e,loading:!1,origin:"event"},"onUserAdded"))),Od((e=>s({data:e,loading:!1,origin:"event"},"onUserRemoved"))),Td((e=>s({data:e,loading:!1,origin:"event"},"onUserBanned"))),Rd((e=>s({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),se(re(md,e),(e=>(e.data||e.error)&&o(e,"onFetch"))),()=>{n(`observeCommunity(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:o,userId:s}=be();o||console.log(p);const i=Date.now();r(`getCommunities(tmpid: ${i}) > listen`);const{limit:a}=e,c=Zi(e,["limit"]),l=null!=a?a:h,{policy:u=f}=null!=n?n:{},d=[],g=["community","collection",{}],m=n=>{var r,o;let i=null!==(r=n.data.map((e=>De(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];i=He(i,"displayName",e.displayName),e.includeDeleted||(i=He(i,"isDeleted",!1)),e.categoryId&&(i=i.filter((t=>{var n;return null===(n=t.categoryIds)||void 0===n?void 0:n.includes(e.categoryId)}))),e.tags&&(i=i.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),e.membership&&s&&(i=Qe(i,e.membership,s));const a=e.sortBy||"lastCreated";"lastCreated"!==a&&"firstCreated"!==a||(i=i.sort("lastCreated"===a?et:Ze)),"displayName"===a&&(i=i.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ye)),t({onNextPage:b,data:i,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},v=e=>e=>{var t;const n=null===(t=De(g))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Le(g,n),m(n))},b=(e=!1)=>{var t,n,r;const o=null===(t=De(g))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Bd,Object.assign(Object.assign({},c),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:l}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("community"))])]),Le(g,o),m(o)}),oe(u,y))};return d.push(wd(v()),_d(v()),Cd(v()),jd(v()),Fd(v()),xd(v())),b(!0),d.push((()=>ze(g))),()=>{r(`getCommunities(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},getCommunity:(e,t)=>rc(e,t,"communityId",md,[Cd,_d,jd,Fd,Td,Rd,xd])});const qd=async e=>{const t=be();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{categories:o}=n;return{data:o.find((t=>t.categoryId===e)),cachedAt:r}};qd.locally=e=>{const t=be();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=De(["category","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $d=async e=>{const t=be();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r={limit:10},includeDeleted:o}=n,s=Zi(n,["page","includeDeleted"]),{data:i}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},s),{isDeleted:pc(o),options:{token:J(r,"skiplimit")}})}),{paging:a}=i,c=Zi(i,["paging"]),{categories:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:u});const e=["category","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})];Le(e,{categories:l.map(ce("category")),paging:a})}const d=G(a.next);return{data:l,cachedAt:u,prevPage:G(a.previous),nextPage:d}};$d.locally=e=>{var t,n;const r=be();if(r.log("category/queryCategories.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s={limit:10}}=o,i=Zi(o,["page"]),a=["category","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.categories.length))return;const u=c.categories.map((e=>De(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.categories)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};var zd=Object.freeze({__proto__:null,getCategory:qd,getCategories:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getCategories(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["category","collection",{}],g=(n=!1)=>{var r,o,s;const i=null===(r=De(d))||void 0===r?void 0:r.data,u=null!==(o=null==i?void 0:i.data)&&void 0!==o?o:[];if(!n&&u.length>0&&!(null==i?void 0:i.params.page))return;const h=re($d,Object.assign(Object.assign({},a),{page:null!==(s=n||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:c}}));se(h,(({data:n,error:r,loading:o,nextPage:s})=>{const i={loading:o,error:r,params:{page:s},data:u};n&&(i.data=[...new Set([...u,...n.map(ce("category"))])]),Le(d,i),(n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["category","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];switch(e.includeDeleted||(s=He(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(Ze);break;case"lastCreated":s=s.sort(et);break;default:s=s.sort(Xe)}t({onNextPage:g,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})})(i)}),oe(l))};return u.push((()=>{})),g(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}});const Hd=async e=>{const t=be();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{useCustomRanking:r,page:o}=n,s=Zi(n,["useCustomRanking","page"]);r&&console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead');const{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{options:{token:J(o,"skiplimit")}})}),{paging:a}=i,c=Zi(i,["paging"]),l=ta(c,"communityUsers"),{posts:u}=l,d=t.cache&&Date.now();if(t.cache){Xi(l);const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:Object.assign({},o)})];Le(e,{posts:u.map(ce("post")),paging:a})}const h=G(a.next);return{data:u,cachedAt:d,prevPage:G(a.previous),nextPage:h}};Hd.locally=e=>{var t,n;const r=be();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,i=Zi(o,["page"]),a=["globalFeed","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const u=c.posts.map((e=>De(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};const Vd=async e=>{const t=be();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i}=s,a=Zi(s,["paging"]),c=ta(a,"communityUsers"),{posts:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c);const e=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{posts:l.map(ce("post")),paging:i})}const d=G(i.next);return{data:l,cachedAt:u,prevPage:G(i.previous),nextPage:d}};Vd.locally=e=>{var t,n;const r=be();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,i=Zi(o,["page"]),a=["customGlobalFeed","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const u=c.posts.map((e=>De(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};var Wd=Object.freeze({__proto__:null,queryGlobalFeed:Hd,getCustomRankingGlobalFeed:Vd});const Kd=async e=>{const t=be();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{_(null==t?void 0:t.code)&&wa("post",e)})),t}const o=ta(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Xi(o,{cachedAt:s}),{data:o.posts,cachedAt:s}};Kd.locally=e=>{var t;const n=be();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>De(["post","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const Qd=async(e,t=!1)=>{const n=be(),r=await Il(e);if(await n.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===r.data.targetType){const e=await md(r.data.targetId);ht("community.updated",{communities:[e.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},r.data),{isDeleted:!0});return ht("post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{wa("post",e)}),0):$e(["post","get",e],{isDeleted:!0}),o},Jd=async e=>{const t=be();t.log("post/queryPosts",e);const{page:n={limit:10},includeDeleted:r}=e,o=Zi(e,["page","includeDeleted"]),{dataTypes:s,matchingOnlyParentPost:i}=o,{data:a}=await t.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},o),{isDeleted:pc(r),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length),options:{token:J(n,"afterbeforeraw")}})}),{paging:c}=a,l=Zi(a,["paging"]),u=ta(l,"communityUsers"),{posts:d}=l,h=t.cache&&Date.now();if(t.cache){Xi(u,{cachedAt:h});const e=["post","query",Object.assign(Object.assign({},o),{options:Object.assign({},n)})];Le(e,{posts:d.map(ce("post")),paging:c})}const f=Y(c.next);return{data:d,cachedAt:h,prevPage:Y(c.previous),nextPage:f}};var Gd=Object.freeze({__proto__:null,getPostByIds:Kd,createPost:async e=>{const t=be();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);ht("post.created",n);const r=ta(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{posts:s}=r;return{data:s[0],cachedAt:o}},updatePost:async(e,t)=>{const n=be();n.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s}),ht("post.updated",o);const{posts:i}=o;return{data:i.find((t=>t.postId===e)),cachedAt:s}},editPost:async(e,t)=>{const n=be();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s}),ht("post.updated",o);const{posts:i}=o;return{data:i.find((t=>t.postId===e)),cachedAt:s}},deletePost:Qd,softDeletePost:async e=>{be().log("post/softDeletePost",e);return await Qd(e,!1)},hardDeletePost:async e=>{be().log("post/hardDeletePost",e);return await Qd(e,!0)},approvePost:async e=>{const t=be();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);ht("post.approved",n),"community"===n.posts[0].targetType&&ht("community.updated",n);const r=ta(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:r.posts.find((t=>t.postId===e)),cachedAt:o}},declinePost:async e=>{const t=be();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&ht("community.updated",n),ht("post.declined",n);const r=ta(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:n.posts.find((t=>t.postId===e)),cachedAt:o}},flagPost:async e=>{const t=be();t.log("post/flagPost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Xi(ta(n,"communityUsers")),ht("post.flagged",n),!!n},unflagPost:async e=>{const t=be();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Xi(ta(n,"communityUsers")),ht("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{var t,n;const r=be();r.log("post/isPostFlaggedByMe",e);const{result:o,isFlagByMe:s}=null!==(t=await Di(r,"v3/post.isflagbyme",{postId:e}))&&void 0!==t?t:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n},onPostCreated:Ml,onPostUpdated:jl,onPostDeleted:Fl,onPostApproved:Bl,onPostDeclined:Nl,onPostFlagged:Ul,onPostUnflagged:Dl,onPostReactionAdded:Ll,onPostReactionRemoved:ql,observePosts:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observePosts(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(e.targetId===n.targetId&&e.targetType===n.targetType){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(Ml((e=>s(e,"onCreate"))),jl((e=>s(e,"onUpdate"))),Fl((e=>s(e,"onDelete"))),Bl((e=>s(e,"onApproved"))),Nl((e=>s(e,"onDeclined"))),Ul((e=>s(e,"onFlagged"))),Dl((e=>s(e,"onUnflagged"))),Ll((e=>s(e,"onReactionAdded"))),ql((e=>s(e,"onReactionRemoved")))),()=>{n(`observePosts(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observePost:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observePost(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.postId)===e&&s(t,n)},a=[];return a.push(jl((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Fl((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Bl((e=>i({data:e,loading:!1,origin:"event"},"onApproved"))),Nl((e=>i({data:e,loading:!1,origin:"event"},"onDeclined"))),Ul((e=>i({data:e,loading:!1,origin:"event"},"onFlagged"))),Dl((e=>i({data:e,loading:!1,origin:"event"},"onUnflagged"))),Ll((e=>i({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ql((e=>i({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),se(re(Il,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observePosts(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getPost:(e,t)=>rc(e,t,"postId",Il,[Bl,Nl,Fl,Ul,Ll,ql,Dl,jl]),getPosts:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getPosts(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["post","collection",{targetId:e.targetId,targetType:e.targetType}],g=n=>{var r,o,s;let i=null!==(r=n.data.map((e=>De(["post","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];const a=e.sortBy?e.sortBy:"lastCreated";i=i.sort("lastCreated"===a?et:Ze),e.includeDeleted||(i=He(i,"isDeleted",!1)),e.tags&&(i=i.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),"community"===e.targetType&&e.feedType&&(i=Ke(i,e.feedType)),(null===(o=e.dataTypes)||void 0===o?void 0:o.length)&&(i=Je(i,e.dataTypes)),t({onNextPage:v,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})},m=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.targetId===n.targetId&&e.targetType===n.targetType&&o&&(o.data="onDeclined"===t?o.data.filter((e=>e!==n.postId)):[...new Set([n.postId,...o.data])],Le(d,o),g(o))},v=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(Jd,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("post"))])]),Le(d,o),g(o)}),oe(l,y))};return u.push(Ml(m("onCreate")),Bl(m("onApproved")),Nl(m("onDeclined")),Fl(m("onDelete")),jl(m("onUpdate")),Ul(m("onFlagged")),Dl(m("onUnflagged")),Ll(m("onReactionAdded")),ql(m("onReactionRemoved"))),v(!0),u.push((()=>ze(d))),()=>{r(`getPosts(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}});const Yd=async e=>{const t=be();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{_(null==t?void 0:t.code)&&wa("comment",e)})),t}const o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:r.comments,cachedAt:o}};Yd.locally=e=>{var t;const n=be();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>De(["comment","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const Xd=async(e,t=!1)=>{const n=be(),r=await Ol(e);await n.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const o=Object.assign(Object.assign({},r.data),{isDeleted:!0}),s=await Il(r.data.referenceId);return ht("post.updated",{posts:[s.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),ht("comment.deleted",{comments:[o],commentChildren:[],files:[],users:[]}),t?at((()=>wa("comment",e))):$e(["comment","get",e],{isDeleted:!0}),o},Zd=async e=>{const t=be();t.log("comment/queryComments",e);const{page:n={limit:10},includeDeleted:r}=e,o=Zi(e,["page","includeDeleted"]),s={type:o.sortBy?"pagination":void 0,token:J(n,o.sortBy?"skiplimit":"afterbefore")},{data:i}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},o),{isDeleted:pc(r),options:s})}),{paging:a}=i,c=Zi(i,["paging"]),{comments:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:u});const e=["comment","query",Object.assign(Object.assign({},o),{options:Object.assign({},n)})];Le(e,{comments:l.map(ce("comment")),paging:a})}const d=G(a.next);return{data:l,cachedAt:u,prevPage:G(a.previous),nextPage:d}};var eh=Object.freeze({__proto__:null,getCommentByIds:Yd,createComment:async e=>{const t=be();t.log("comment/createComment",e);const{data:n}=await t.http.post("/api/v3/comments",e),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const o=await Il(e.referenceId);ht("post.updated",{posts:[o.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),ht("comment.created",n);const{comments:s}=n;return{data:s[0],cachedAt:r}},updateComment:async(e,t)=>{const n=be();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o}),ht("comment.updated",r);const{comments:s}=r;return{data:s.find((t=>t.commentId===e)),cachedAt:o}},deleteComment:Xd,softDeleteComment:async e=>{be().log("comment/softDeleteComment",e);return Xd(e)},hardDeleteComment:async e=>{be().log("comment/hardDeleteComment",e);return Xd(e,!0)},flagComment:async e=>{const t=be();t.log("comment/flagComment",e);const{data:n}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Xi(n),ht("comment.flagged",n),!!n},unflagComment:async e=>{const t=be();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Xi(n),ht("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{var t,n;const r=be();r.log("comment/isCommentFlaggedByMe",e);const{result:o,isFlagByMe:s}=null!==(t=await Di(r,"v3/comment.isflagbyme",{commentId:e}))&&void 0!==t?t:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n},onCommentCreated:zl,onCommentUpdated:Hl,onCommentDeleted:Vl,onCommentFlagged:Wl,onCommentUnflagged:Kl,onCommentReactionAdded:Ql,onCommentReactionRemoved:Jl,observeComments:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeComments(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(n.referenceId===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(zl((e=>s(e,"onCreate"))),Hl((e=>s(e,"onUpdate"))),Vl((e=>s(e,"onDelete"))),Wl((e=>s(e,"onFlagged"))),Kl((e=>s(e,"onUnflagged"))),Ql((e=>s(e,"onReactionAdded"))),Jl((e=>s(e,"onReactionRemoved")))),()=>{n(`observeComments(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeComment:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeComment(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.commentId)===e&&s(t,n)},a=[];return a.push(Hl((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Vl((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Wl((e=>i({data:e,loading:!1,origin:"event"},"onFlagged"))),Kl((e=>i({data:e,loading:!1,origin:"event"},"onUnflagged"))),Ql((e=>i({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Jl((e=>i({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),se(re(Ol,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observeComment(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getComment:(e,t)=>rc(e,t,"commentId",Ol,[Vl,Wl,Ql,Jl,Kl,Hl]),getComments:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getComments(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId}],p=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["comment","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.includeDeleted||(s=He(s,"isDeleted",!1));const i=e.sortBy?e.sortBy:"lastCreated";s=s.sort("lastCreated"===i?et:Ze),t({onNextPage:m,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.referenceId===n.referenceId&&e.referenceType===n.referenceType&&o&&("onCreate"===t?o.data=[...new Set([n.commentId,...o.data])]:"onDelete"===t&&(o.data=o.data.filter((e=>e!==n.commentId))),Le(d,o),p(o))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(Zd,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,prevPage:r,nextPage:o})=>{const s={loading:n,error:t,params:{page:a.sortBy?o:r},data:i};e&&(s.data=[...new Set([...i,...e.map(ce("comment"))])]),Le(d,s),p(s)}),oe(l,y))};return u.push(zl(g("onCreate")),Hl(g("onUpdate")),Vl(g("onDelete")),Wl(g("onFlagged")),Kl(g("onUnflagged")),Ql(g("onReactionAdded")),Jl(g("onReactionRemoved"))),m(!0),u.push((()=>ze(d))),()=>{r(`getComments(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}});const th=async e=>{const t=be();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}};th.locally=e=>{const t=be();if(t.log("stream/getStream",e),!t.cache)return;const n=De(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const nh=async e=>{const t=be();t.log("stream/getStreams",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i,results:a}=s,{videoStreamings:c}=a,l=t.cache&&Date.now();t.cache&&Xi(a,{cachedAt:l});const u=G(i.next);return{data:c,cachedAt:l,prevPage:G(i.previous),nextPage:u}};nh.locally=e=>{be().log("stream/getStreams.locally",e)};var rh=Object.freeze({__proto__:null,getStream:th,getStreams:nh,createStream:async e=>{const t=be();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o[0],cachedAt:r}},updateStream:async(e,t)=>{const n=be();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:o}},deleteStream:async e=>{const t=be();t.log("stream/deleteStream",e);const n=await th(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:o}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return $e(["stream","get",e],s),o},disposeStream:async e=>{const t=be();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}},onStreamStarted:e=>{const t=be();return dt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Xi(t),e(t.videoStreamings[0])}))},onStreamStopped:e=>{const t=be();return dt(t,"stream/onStreamStarted","video-streaming.didStop",(t=>{Xi(t),e(t.videoStreamings[0])}))},onStreamRecorded:e=>{const t=be();return dt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Xi(t),e(t.videoStreamings[0])}))}});const oh=async e=>{const t=be();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}};oh.locally=e=>{const t=be();if(t.log("poll/getPoll",e),!t.cache)return;const n=De(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const sh=e=>{const t=be();return dt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Xi(n),e(n.polls[0])}))},ih=e=>{const t=be();return dt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Xi(n),e(n.polls[0])}))};var ah=Object.freeze({__proto__:null,getPoll:oh,createPoll:async e=>{const t=be();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{polls:o}=n;return{data:o[0],cachedAt:r}},closePoll:async e=>{const t=be();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r}),ht("poll.updated",n);const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=be();t.log("poll/deletePoll",e);const n=await oh(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:o}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return $e(["poll","get",e],s),ht("poll.deleted",{polls:[s],users:[]}),o},votePoll:async(e,t)=>{const n=be();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{polls:s}=r;return ht("poll.updated",r),{data:s.find((t=>t.pollId===e)),cachedAt:o}},onPollUpdated:sh,onPollDeleted:ih,observePoll:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observePoll(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.pollId)===e&&s(t,n)},a=[];return a.push(sh((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),ih((e=>i({data:e,loading:!1,origin:"event"},"onDelete")))),se(re(oh,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observePoll(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}}});return e.API_REGIONS=Bt,e.CategoryRepository=zd,e.ChannelRepository=Mc,e.Client=Qc,e.CommentRepository=eh,e.CommunityPostSettingMaps=n,e.CommunityPostSettings=t,e.CommunityRepository=Ld,e.ContentFeedType=o,e.DefaultCommunityPostSetting=r,e.FeedRepository=Wd,e.FileRepository=_l,e.FileType=s,e.MessageContentType=l,e.MessageRepository=sd,e.PollRepository=ah,e.PostContentType=u,e.PostRepository=Gd,e.ReactionRepository=Zl,e.StreamRepository=rh,e.SubChannelRepository=dd,e.UserRepository=wl,e.VERSION=d,e.VideoResolution=i,e.VideoSize=c,e.VideoTranscodingStatus=a,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:o}=be();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(await Ne.setItem(`${e}#${o}`,JSON.stringify(s)),!0)},e.createQuery=re,e.createReport=async(e,t)=>{const n=be();n.log("report/createReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.post((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=eu[e];return`/api/v3/${n}/${encodeURIComponent(t)}/flag`})());if(n.cache)if("message"===e){const e=await mc(r);Xi(e)}else Xi("post"===e?ta(r,"communityUsers"):r);return ht(`${e}.flagged`,r),!!r},e.createUserToken=async(e,t,n)=>{const r=Ki(),o=Qi(),s=kr(Ut("http",t)),{data:i}=await s.post("/api/v4/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},o),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:i.accessToken}},e.deleteReport=async(e,t)=>{const n=be();n.log("report/deleteReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.delete((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=eu[e];return`/api/v3/${n}/${encodeURIComponent(t)}/unflag`})());if(n.cache)if("message"===e){const e=await mc(r);Xi(e)}else Xi("post"===e?ta(r,"communityUsers"):r);return ht(`${e}.unflagged`,r),!!r},e.disableCache=()=>{const e=be();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=ze,e.enableCache=(e={},t)=>{const n=be();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=We,e.filterByCommunityMembership=Qe,e.filterByFeedType=Ke,e.filterByPostDataTypes=Je,e.filterByPropEquality=He,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Ve,e.filterBySearchTerm=Ge,e.getChannelMarkers=ua,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>yt(t,n),e.getMarkedMessageTopic=wt,e.getMessageMarkers=Ca,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=rt();return`${vt(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=rt();return`${vt(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=Ct,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Sl,e.getSmartFeedChannelTopic=_t,e.getSmartFeedMessageTopic=St,e.getSmartFeedSubChannelTopic=kt,e.getSubChannelMarkers=_a,e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserMarker=ka,e.getUserTopic=bt,e.isAfterBefore=W,e.isAfterBeforeRaw=K,e.isCachable=te,e.isFetcher=X,e.isFresh=ne,e.isLocal=e=>te(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=Z,e.isOffline=ee,e.isPaged=Q,e.isReportedByMe=async(e,t)=>{var n,r;const o=be();o.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{eventName:s,primaryKey:i}=eu[e];if("message"===e){const{data:e}=await o.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`);return e.result}const{result:a,isFlagByMe:c}=null!==(n=await Di(o,s,{[i]:t}))&&void 0!==n?n:{};return null!==(r=null!=a?a:c)&&void 0!==r&&r},e.isSkip=V,e.mergeInCache=qe,e.onChannelMarkerFetched=e=>{const t=be();return dt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{e(t.userEntityMarkers[0])}))},e.onFeedMarkerFetched=e=>{const t=be();return dt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=ec,e.onMessageMarked=e=>{const t=be();return dt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{e(t.contentMarkers[0])}))},e.onMessageMarkerFetched=e=>{const t=be();return dt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},e.onSubChannelMarkerFetched=e=>{const t=be();return dt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{e(t.userFeedMarkers[0])}))},e.onSubChannelMarkerUpdated=e=>{const t=be();return dt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers[0])}))},e.onUserMarkerFetched=tc,e.pullFromCache=De,e.pushToCache=Le,e.queryCache=Ue,e.queryOptions=oe,e.queryRoles=kl,e.restoreCache=async(e="amitySdk")=>{var t;const n=be();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=null!==(t=await Ne.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let o={};try{o=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},o),n.cache.data),!0},e.runQuery=se,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Ye,e.sortByFirstCreated=Ze,e.sortByLastActivity=tt,e.sortByLastCreated=et,e.sortByName=Xe,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=At,e.toPage=G,e.toPageRaw=Y,e.toToken=J,e.upsertInCache=$e,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=be();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},await Ne.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({});
6
+ var r=e("buffer"),o=r.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function i(e,t,n){return o(e,t,n)}o.from&&o.alloc&&o.allocUnsafe&&o.allocUnsafeSlow?t.exports=r:(s(r,n),n.Buffer=i),i.prototype=Object.create(o.prototype),s(o,i),i.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return o(e,t,n)},i.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=o(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},i.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return o(e)},i.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},{buffer:17}],74:[function(e,t,n){function r(e){var t=e._readableState;return t?t.objectMode||"number"==typeof e._duplexState?e.read():e.read(o(t)):null}function o(e){return e.buffer.length?e.buffer.head?e.buffer.head.data.length:e.buffer[0].length:e.length}t.exports=r},{}],75:[function(e,t,n){var r=e("safe-buffer").Buffer,o=r.isEncoding||function(e){switch((e=""+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 s(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function i(e){var t=s(e);if("string"!=typeof t&&(r.isEncoding===o||!o(e)))throw new Error("Unknown encoding: "+e);return t||e}function a(e){var t;switch(this.encoding=i(e),this.encoding){case"utf16le":this.text=p,this.end=g,t=4;break;case"utf8":this.fillLast=d,t=4;break;case"base64":this.text=m,this.end=y,t=3;break;default:return this.write=v,void(this.end=b)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function c(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function l(e,t,n){var r=t.length-1;if(r<n)return 0;var o=c(t[r]);return o>=0?(o>0&&(e.lastNeed=o-1),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(e.lastNeed=o-2),o):--r<n||-2===o?0:(o=c(t[r]))>=0?(o>0&&(2===o?o=0:e.lastNeed=o-3),o):0}function u(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}function d(e){var t=this.lastTotal-this.lastNeed,n=u(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function h(e,t){var n=l(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function p(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function g(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function m(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function y(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function v(e){return e.toString(this.encoding)}function b(e){return e&&e.length?this.write(e):""}n.StringDecoder=a,a.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},a.prototype.end=f,a.prototype.text=h,a.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":73}],76:[function(e,t,n){var r=e("punycode"),o=e("./util");function s(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}n.parse=w,n.resolve=_,n.resolveObject=k,n.format=C,n.Url=s;var i=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,c=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),u=["'"].concat(l),d=["%","/","?",";","#"].concat(u),h=["/","?","#"],f=255,p=/^[+a-z0-9A-Z_-]{0,63}$/,g=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},y={javascript:!0,"javascript:":!0},v={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function w(e,t,n){if(e&&o.isObject(e)&&e instanceof s)return e;var r=new s;return r.parse(e,t,n),r}function C(e){return o.isString(e)&&(e=w(e)),e instanceof s?e.format():s.prototype.format.call(e)}function _(e,t){return w(e,!1,!0).resolve(t)}function k(e,t){return e?w(e,!1,!0).resolveObject(t):t}s.prototype.parse=function(e,t,n){if(!o.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var s=e.indexOf("?"),a=-1!==s&&s<e.indexOf("#")?"?":"#",l=e.split(a),w=/\\/g;l[0]=l[0].replace(w,"/");var C=e=l.join(a);if(C=C.trim(),!n&&1===e.split("#").length){var _=c.exec(C);if(_)return this.path=C,this.href=C,this.pathname=_[1],_[2]?(this.search=_[2],this.query=t?b.parse(this.search.substr(1)):this.search.substr(1)):t&&(this.search="",this.query={}),this}var k=i.exec(C);if(k){var S=(k=k[0]).toLowerCase();this.protocol=S,C=C.substr(k.length)}if(n||k||C.match(/^\/\/[^@\/]+@[^@\/]+/)){var A="//"===C.substr(0,2);!A||k&&y[k]||(C=C.substr(2),this.slashes=!0)}if(!y[k]&&(A||k&&!v[k])){for(var E,I,O=-1,T=0;T<h.length;T++)-1!==(x=C.indexOf(h[T]))&&(-1===O||x<O)&&(O=x);for(-1!==(I=-1===O?C.lastIndexOf("@"):C.lastIndexOf("@",O))&&(E=C.slice(0,I),C=C.slice(I+1),this.auth=decodeURIComponent(E)),O=-1,T=0;T<d.length;T++){var x;-1!==(x=C.indexOf(d[T]))&&(-1===O||x<O)&&(O=x)}-1===O&&(O=C.length),this.host=C.slice(0,O),C=C.slice(O),this.parseHost(),this.hostname=this.hostname||"";var R="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!R)for(var P=this.hostname.split(/\./),M=(T=0,P.length);T<M;T++){var j=P[T];if(j&&!j.match(p)){for(var F="",B=0,N=j.length;B<N;B++)j.charCodeAt(B)>127?F+="x":F+=j[B];if(!F.match(p)){var U=P.slice(0,T),D=P.slice(T+1),L=j.match(g);L&&(U.push(L[1]),D.unshift(L[2])),D.length&&(C="/"+D.join(".")+C),this.hostname=U.join(".");break}}}this.hostname.length>f?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=r.toASCII(this.hostname));var q=this.port?":"+this.port:"",$=this.hostname||"";this.host=$+q,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==C[0]&&(C="/"+C))}if(!m[S])for(T=0,M=u.length;T<M;T++){var z=u[T];if(-1!==C.indexOf(z)){var H=encodeURIComponent(z);H===z&&(H=escape(z)),C=C.split(z).join(H)}}var V=C.indexOf("#");-1!==V&&(this.hash=C.substr(V),C=C.slice(0,V));var W=C.indexOf("?");if(-1!==W?(this.search=C.substr(W),this.query=C.substr(W+1),t&&(this.query=b.parse(this.query)),C=C.slice(0,W)):t&&(this.search="",this.query={}),C&&(this.pathname=C),v[S]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){q=this.pathname||"";var K=this.search||"";this.path=q+K}return this.href=this.format(),this},s.prototype.format=function(){var e=this.auth||"";e&&(e=(e=encodeURIComponent(e)).replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",s=!1,i="";this.host?s=e+this.host:this.hostname&&(s=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&o.isObject(this.query)&&Object.keys(this.query).length&&(i=b.stringify(this.query));var a=this.search||i&&"?"+i||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||v[t])&&!1!==s?(s="//"+(s||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):s||(s=""),r&&"#"!==r.charAt(0)&&(r="#"+r),a&&"?"!==a.charAt(0)&&(a="?"+a),t+s+(n=n.replace(/[?#]/g,(function(e){return encodeURIComponent(e)})))+(a=a.replace("#","%23"))+r},s.prototype.resolve=function(e){return this.resolveObject(w(e,!1,!0)).format()},s.prototype.resolveObject=function(e){if(o.isString(e)){var t=new s;t.parse(e,!1,!0),e=t}for(var n=new s,r=Object.keys(this),i=0;i<r.length;i++){var a=r[i];n[a]=this[a]}if(n.hash=e.hash,""===e.href)return n.href=n.format(),n;if(e.slashes&&!e.protocol){for(var c=Object.keys(e),l=0;l<c.length;l++){var u=c[l];"protocol"!==u&&(n[u]=e[u])}return v[n.protocol]&&n.hostname&&!n.pathname&&(n.path=n.pathname="/"),n.href=n.format(),n}if(e.protocol&&e.protocol!==n.protocol){if(!v[e.protocol]){for(var d=Object.keys(e),h=0;h<d.length;h++){var f=d[h];n[f]=e[f]}return n.href=n.format(),n}if(n.protocol=e.protocol,e.host||y[e.protocol])n.pathname=e.pathname;else{for(var p=(e.pathname||"").split("/");p.length&&!(e.host=p.shift()););e.host||(e.host=""),e.hostname||(e.hostname=""),""!==p[0]&&p.unshift(""),p.length<2&&p.unshift(""),n.pathname=p.join("/")}if(n.search=e.search,n.query=e.query,n.host=e.host||"",n.auth=e.auth,n.hostname=e.hostname||e.host,n.port=e.port,n.pathname||n.search){var g=n.pathname||"",m=n.search||"";n.path=g+m}return n.slashes=n.slashes||e.slashes,n.href=n.format(),n}var b=n.pathname&&"/"===n.pathname.charAt(0),w=e.host||e.pathname&&"/"===e.pathname.charAt(0),C=w||b||n.host&&e.pathname,_=C,k=n.pathname&&n.pathname.split("/")||[],S=(p=e.pathname&&e.pathname.split("/")||[],n.protocol&&!v[n.protocol]);if(S&&(n.hostname="",n.port=null,n.host&&(""===k[0]?k[0]=n.host:k.unshift(n.host)),n.host="",e.protocol&&(e.hostname=null,e.port=null,e.host&&(""===p[0]?p[0]=e.host:p.unshift(e.host)),e.host=null),C=C&&(""===p[0]||""===k[0])),w)n.host=e.host||""===e.host?e.host:n.host,n.hostname=e.hostname||""===e.hostname?e.hostname:n.hostname,n.search=e.search,n.query=e.query,k=p;else if(p.length)k||(k=[]),k.pop(),k=k.concat(p),n.search=e.search,n.query=e.query;else if(!o.isNullOrUndefined(e.search))return S&&(n.hostname=n.host=k.shift(),(T=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=T.shift(),n.host=n.hostname=T.shift())),n.search=e.search,n.query=e.query,o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n;if(!k.length)return n.pathname=null,n.search?n.path="/"+n.search:n.path=null,n.href=n.format(),n;for(var A=k.slice(-1)[0],E=(n.host||e.host||k.length>1)&&("."===A||".."===A)||""===A,I=0,O=k.length;O>=0;O--)"."===(A=k[O])?k.splice(O,1):".."===A?(k.splice(O,1),I++):I&&(k.splice(O,1),I--);if(!C&&!_)for(;I--;I)k.unshift("..");!C||""===k[0]||k[0]&&"/"===k[0].charAt(0)||k.unshift(""),E&&"/"!==k.join("/").substr(-1)&&k.push("");var T,x=""===k[0]||k[0]&&"/"===k[0].charAt(0);return S&&(n.hostname=n.host=x?"":k.length?k.shift():"",(T=!!(n.host&&n.host.indexOf("@")>0)&&n.host.split("@"))&&(n.auth=T.shift(),n.host=n.hostname=T.shift())),(C=C||n.host&&k.length)&&!x&&k.unshift(""),k.length?n.pathname=k.join("/"):(n.pathname=null,n.path=null),o.isNull(n.pathname)&&o.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},s.prototype.parseHost=function(){var e=this.host,t=a.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":77,punycode:51,querystring:54}],77:[function(e,t,n){t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],78:[function(e,t,n){(function(e){(function(){function n(e,t){if(r("noDeprecation"))return e;var n=!1;function o(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}return o}function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var n=e.localStorage[t];return null!=n&&"true"===String(n).toLowerCase()}t.exports=n}).call(this)}).call(this,void 0!==Ce?Ce:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],79:[function(e,t,n){function r(e,t){if(e&&t)return r(e)(t);if("function"!=typeof e)throw new TypeError("need wrapper function");return Object.keys(e).forEach((function(t){n[t]=e[t]})),n;function n(){for(var t=new Array(arguments.length),n=0;n<t.length;n++)t[n]=arguments[n];var r=e.apply(this,t),o=t[t.length-1];return"function"==typeof r&&r!==o&&Object.keys(o).forEach((function(e){r[e]=o[e]})),r}}t.exports=r},{}],80:[function(e,t,n){t.exports=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}},{}],81:[function(e,t,n){t.exports=o;var r=Object.prototype.hasOwnProperty;function o(){for(var e={},t=0;t<arguments.length;t++){var n=arguments[t];for(var o in n)r.call(n,o)&&(e[o]=n[o])}return e}},{}],82:[function(e,t,n){t.exports=function(e){e.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}},{}],83:[function(e,t,n){function r(e){var t=this;if(t instanceof r||(t=new r),t.tail=null,t.head=null,t.length=0,e&&"function"==typeof e.forEach)e.forEach((function(e){t.push(e)}));else if(arguments.length>0)for(var n=0,o=arguments.length;n<o;n++)t.push(arguments[n]);return t}function o(e,t,n){var r=t===e.head?new a(n,null,t,e):new a(n,t,t.next,e);return null===r.next&&(e.tail=r),null===r.prev&&(e.head=r),e.length++,r}function s(e,t){e.tail=new a(t,e.tail,null,e),e.head||(e.head=e.tail),e.length++}function i(e,t){e.head=new a(t,null,e.head,e),e.tail||(e.tail=e.head),e.length++}function a(e,t,n,r){if(!(this instanceof a))return new a(e,t,n,r);this.list=r,this.value=e,t?(t.next=this,this.prev=t):this.prev=null,n?(n.prev=this,this.next=n):this.next=null}t.exports=r,r.Node=a,r.create=r,r.prototype.removeNode=function(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");var t=e.next,n=e.prev;return t&&(t.prev=n),n&&(n.next=t),e===this.head&&(this.head=t),e===this.tail&&(this.tail=n),e.list.length--,e.next=null,e.prev=null,e.list=null,t},r.prototype.unshiftNode=function(e){if(e!==this.head){e.list&&e.list.removeNode(e);var t=this.head;e.list=this,e.next=t,t&&(t.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}},r.prototype.pushNode=function(e){if(e!==this.tail){e.list&&e.list.removeNode(e);var t=this.tail;e.list=this,e.prev=t,t&&(t.next=e),this.tail=e,this.head||(this.head=e),this.length++}},r.prototype.push=function(){for(var e=0,t=arguments.length;e<t;e++)s(this,arguments[e]);return this.length},r.prototype.unshift=function(){for(var e=0,t=arguments.length;e<t;e++)i(this,arguments[e]);return this.length},r.prototype.pop=function(){if(this.tail){var e=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,e}},r.prototype.shift=function(){if(this.head){var e=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,e}},r.prototype.forEach=function(e,t){t=t||this;for(var n=this.head,r=0;null!==n;r++)e.call(t,n.value,r,this),n=n.next},r.prototype.forEachReverse=function(e,t){t=t||this;for(var n=this.tail,r=this.length-1;null!==n;r--)e.call(t,n.value,r,this),n=n.prev},r.prototype.get=function(e){for(var t=0,n=this.head;null!==n&&t<e;t++)n=n.next;if(t===e&&null!==n)return n.value},r.prototype.getReverse=function(e){for(var t=0,n=this.tail;null!==n&&t<e;t++)n=n.prev;if(t===e&&null!==n)return n.value},r.prototype.map=function(e,t){t=t||this;for(var n=new r,o=this.head;null!==o;)n.push(e.call(t,o.value,this)),o=o.next;return n},r.prototype.mapReverse=function(e,t){t=t||this;for(var n=new r,o=this.tail;null!==o;)n.push(e.call(t,o.value,this)),o=o.prev;return n},r.prototype.reduce=function(e,t){var n,r=this.head;if(arguments.length>1)n=t;else{if(!this.head)throw new TypeError("Reduce of empty list with no initial value");r=this.head.next,n=this.head.value}for(var o=0;null!==r;o++)n=e(n,r.value,o),r=r.next;return n},r.prototype.reduceReverse=function(e,t){var n,r=this.tail;if(arguments.length>1)n=t;else{if(!this.tail)throw new TypeError("Reduce of empty list with no initial value");r=this.tail.prev,n=this.tail.value}for(var o=this.length-1;null!==r;o--)n=e(n,r.value,o),r=r.prev;return n},r.prototype.toArray=function(){for(var e=new Array(this.length),t=0,n=this.head;null!==n;t++)e[t]=n.value,n=n.next;return e},r.prototype.toArrayReverse=function(){for(var e=new Array(this.length),t=0,n=this.tail;null!==n;t++)e[t]=n.value,n=n.prev;return e},r.prototype.slice=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=0,s=this.head;null!==s&&o<e;o++)s=s.next;for(;null!==s&&o<t;o++,s=s.next)n.push(s.value);return n},r.prototype.sliceReverse=function(e,t){(t=t||this.length)<0&&(t+=this.length),(e=e||0)<0&&(e+=this.length);var n=new r;if(t<e||t<0)return n;e<0&&(e=0),t>this.length&&(t=this.length);for(var o=this.length,s=this.tail;null!==s&&o>t;o--)s=s.prev;for(;null!==s&&o>e;o--,s=s.prev)n.push(s.value);return n},r.prototype.splice=function(e,t,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);for(var r=0,s=this.head;null!==s&&r<e;r++)s=s.next;var i=[];for(r=0;s&&r<t;r++)i.push(s.value),s=this.removeNode(s);for(null===s&&(s=this.tail),s!==this.head&&s!==this.tail&&(s=s.prev),r=0;r<n.length;r++)s=o(this,s,n[r]);return i},r.prototype.reverse=function(){for(var e=this.head,t=this.tail,n=e;null!==n;n=n.prev){var r=n.prev;n.prev=n.next,n.next=r}return this.head=t,this.tail=e,this};try{e("./iterator.js")(r)}catch(e){}},{"./iterator.js":82}]},{},[12])(12)}(qi);var $i=_e(qi.exports);const zi=1e3;var Hi;!function(e){e[e.IDENTIFIER_REJECTED=2]="IDENTIFIER_REJECTED",e[e.BAD_USERNAME_OR_PASSWORD=134]="BAD_USERNAME_OR_PASSWORD",e[e.NOT_AUTHORIZED=135]="NOT_AUTHORIZED"}(Hi||(Hi={}));const Vi=e=>{let t;return{connect:async function(n){return t&&(t.removeAllListeners(),t.end(!0)),t=$i.connect(e,function(e){return Object.assign({clean:!1,clientId:`mqttjs_ + ${Math.random().toString(16).substring(2,10)}`,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:zi,will:{topic:"WillMsg",payload:"Connection Closed abnormally..!",qos:0,retain:!1},resubscribe:!0},e)}({username:n.userId,password:n.accessToken})),t.on("connect",(()=>{t.options.reconnectPeriod=zi,(()=>{const e=[At(Ct()),At(_t()),At(kt()),At(St()),At(bt(rt()))]})()})),t.on("error",(e=>{switch(e.code){case 2:case 134:case 135:t.end()}})),t.on("reconnect",(()=>{t.options.reconnectPeriod=Math.min(2*(t.options.reconnectPeriod||zi),8e3)})),new Promise((e=>t.once("connect",(()=>e()))))},async disconnect(){if(this.connected)return new Promise((e=>null==t?void 0:t.end(!0,void 0,(()=>e()))))},get connected(){return!!(null==t?void 0:t.connected)},on(e,n){null==t||t.on(e,n)},once(e,n){null==t||t.once(e,n)},off(e,n){void 0!==n?null==t||t.off(e,n):null==t||t.removeAllListeners(e)},removeAllListeners(){null==t||t.removeAllListeners()},subscribe(e,n){const r=(t,r)=>{var o;if(t||128===(null===(o=r[0])||void 0===o?void 0:o.qos)){const r=t?new pe(t.message,8e5,"error"):new me(8e5,"error");console.warn(`Failed to subscribe to topic ${e}`,r),null==n||n(r)}else console.log(`Subscribed to topic ${e}`),null==n||n()};return t?t.subscribe(e,{qos:0},r):r(new Error("No connection to broker"),[]),()=>null==t?void 0:t.unsubscribe(e)},unsubscribe(e){null==t||t.unsubscribe(e)}}},Wi=async()=>{const e=be(),{data:t}=await e.http.get("/api/v3/network-settings/feed-setting");return Object.fromEntries(t.feedSettings.map((({feedType:e,contentSettings:t})=>[e,t])))},Ki=()=>`ascWebSdk#${Math.random().toString(16)}`,Qi=()=>{const e=(()=>{var e,t;return(null===(e=jt.versions)||void 0===e?void 0:e.node)?jt.versions.node:navigator?`${navigator.product.toLowerCase()}#${null!==(t=navigator.userAgent)&&void 0!==t?t:"unknown_agent"}`:"unknown_model"})();return{kind:"web",model:e,sdkVersion:d}},Ji={notLoggedIn:["establishing"],terminated:["establishing"],establishing:["notLoggedIn","established"],established:["notLoggedIn","terminated","tokenExpired","establishing"],tokenExpired:["establishing"]},Gi=e=>{const t=be();t.log("client/api/setSessionState",e);const{sessionState:n}=t;if(n===e)return!1;if(!((e,t)=>Ji[e].includes(t))(n,e))throw new pe(`Session state cannot change from ${n} to ${e}`,8e5,"error");return t.sessionState=e,t.emitter.emit("sessionStateChange",e),!0},Yi=async e=>{const t=be();Gi("establishing");const{accessToken:n,users:r,expiresAt:o,issuedAt:s,refreshToken:i}=await(async e=>{const t=be();t.log("client/api/getToken",e);const n=Qi(),{data:r}=await t.http.post("/api/v4/sessions",Object.assign(Object.assign({},e),{deviceInfo:n}),{headers:{"X-API-Key":t.apiKey}});return r})(e);return t.http.defaults.headers.common.Authorization=`Bearer ${n}`,t.http.defaults.metadata={tokenExpiry:o,isGlobalBanned:!1,isUserDeleted:!1},t.ws.io.opts.query={token:n},t.token={accessToken:n,issuedAt:s,expiresAt:o},Gi("established"),{accessToken:n,users:r,refreshToken:i}},Xi=(e={},t,n=!0)=>{Object.entries(e).forEach((([e,r])=>{const o=he[e];if(!o)return;const s=ce(o);s&&r.forEach((e=>{(n?Le:$e)([o,"get",s(e)],e,t)}))}))};function Zi(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}const ea=(e,t="userId",n="user")=>{var r;return null!==(r=null==e?void 0:e.map((e=>((e,t="userId",n="user")=>e[n]?e:Object.assign({get[n](){var n;if(!be().cache)return;return(null===(n=De(["user","get",e[t]]))||void 0===n?void 0:n.data)||void 0}},e))(e,t,n))))&&void 0!==r?r:e},ta=(e,t,n="userId",r="user")=>{const o=e,s=t,i=o[s],a=Zi(o,["symbol"==typeof s?s:s+""]),c=ea(i,n,r);return Object.assign(Object.assign({},a),{[t]:c})},na=(e,t)=>{var n,r,o;return(null==t?void 0:t.isDeleted)?0:null!==(o=null!==(n=null==t?void 0:t.unreadCount)&&void 0!==n?n:null===(r=(e=>{var t;const n={entityId:e,userId:rt()._id};return null===(t=De(["channelMarker","get",ce("channelMarker")(n)]))||void 0===t?void 0:t.data})(e.channelId))||void 0===r?void 0:r.unreadCount)&&void 0!==o?o:0},ra=(e,t)=>{var n;return null!==(n=null!=t?t:(e=>{var t,n;const r={creatorId:e.creatorId,feedId:null!==(t=e.messageFeedId)&&void 0!==t?t:e.subChannelId,contentId:e.messageId};return null===(n=De(["messageMarker","get",ce("messageMarker")(r)]))||void 0===n?void 0:n.data})(e))&&void 0!==n?n:{readCount:0,deliveredCount:0}};function oa(e,t,n){var r;if(n)return n.unreadCount;const o={entityId:e,feedId:t,userId:rt()._id},s=null===(r=De(["subChannelMarker","get",ce("subChannelMarker")(o)]))||void 0===r?void 0:r.data;return s?s.unreadCount:0}const sa=(e,t)=>{t.length&&ht(e,{userMarkers:t})},ia=(e,t)=>{t.length&&ht(e,{feedMarkers:t})},aa=(e,t)=>{if(!t.length)return;ht(e,{userEntityMarkers:t});const n=function(e){var t;const n=["channel","get",e.entityId],r=null===(t=De(n))||void 0===t?void 0:t.data;if(!r)return;const o=Object.assign(Object.assign({},r),{unreadCount:na(r,e),updatedAt:(new Date).toISOString()});return $e(n,o),o}(t[0]);return n&&ht("local.channel.updated",{channels:[n]}),n},ca=(e,t)=>{if(!t.length)return;ht(e,{userFeedMarkers:t});const n=function(e){var t;const n=["subChannel","get",e.feedId],r=null===(t=De(n))||void 0===t?void 0:t.data;if(!r)return;const o=Object.assign(Object.assign({},r),{unreadCount:oa(r.channelId,r.subChannelId,e),updatedAt:(new Date).toISOString()});return $e(n,o),o}(t[0]);return n&&ht("local.message-feed.updated",{messageFeeds:[n]}),n},la=(e,t)=>{if(!t.length)return;ht(e,{contentMarkers:t});const n=function(e){var t;const n=["message","get",e.contentId],r=null===(t=De(n))||void 0===t?void 0:t.data;if(!r)return;const{readCount:o,deliveredCount:s}=ra(r,e),i=Object.assign(Object.assign({},r),{readCount:o,deliveredCount:s,updatedAt:(new Date).toISOString()});return $e(n,i),i}(t[0]);return n&&ht("local.message.updated",{messages:[n]}),n},ua=async(e,t={limit:100})=>{const n=be();n.log("channel/getChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/channels",{params:{channelIds:e,options:{token:J(t,"skiplimit")}}}),{paging:o}=r,s=Zi(r,["paging"]),{userEntityMarkers:i,userMarkers:a}=s,c=n.cache&&Date.now();n.cache&&Xi(s,{cachedAt:c}),aa("local.channelMarker.fetched",i),sa("local.userMarker.fetched",a);const l=G(o.next);return{data:i,cachedAt:c,prevPage:G(o.previous),nextPage:l}},da=["broadcast","conversation","community"],ha=({type:e})=>da.includes(e);function fa(e,t){return Object.assign(Object.assign({},e),{defaultSubChannelId:e._id,isUnreadCountSupport:ha(e),unreadCount:na(e,t)})}const pa=async e=>{let t=[];const n=e.channels.filter(ha).map((({channelId:e})=>e));if(n.length>0){(e=>{Xi({channels:e.channels.map((e=>fa(e)))})})(e);try{({data:t}=await ua(n))}catch(e){}}const r=e.channels.map((e=>{const n=null==t?void 0:t.find((({entityId:t})=>t===e.channelId));return fa(e,n)})),o=ea(e.channelUsers);return Object.assign(Object.assign({},e),{channels:r,channelUsers:o})},ga=e=>{const t=be();return dt(t,"onChannelDeleted","channel.deleted",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])}))},ma=e=>{const t=be();return dt(t,"onChannelMemberBanned","channel.banned",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o.find((e=>"banned"===e.membership)))}))},ya=e=>{const t=be();return dt(t,"client/onSessionStateChange","sessionStateChange",e)},va=(e,t)=>{const n=setInterval(e,t);return()=>clearInterval(n)},ba=(e,t)=>{const{log:n,cache:r}=be(),o=[e,m,t];if(!r)return;n("cache/api/isInTombstone",o);const s=De(o),{lifeSpan:i}=oe("cache_then_server",18e4);if(s&&ne(s.data,i))throw new ge("Item not found!",400400,"error")},wa=(e,t)=>{const{log:n,cache:r}=be(),o=[e,m,t],s={cachedAt:Date.now()};r&&(n("cache/api/pushToTombstone",{cacheKey:o,data:s}),ze([e,"get",t],!0),Le(o,s))},Ca=async(e,t={limit:100})=>{const n=be();n.log("channel/getMessageMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/messages",{params:{messageIds:e,options:{token:J(t,"skiplimit")}}}),{paging:o}=r,s=Zi(r,["paging"]),{contentMarkers:i,feedMarkers:a,userMarkers:c}=s,l=n.cache&&Date.now();n.cache&&Xi(s,{cachedAt:l}),ia("local.feedMarker.fetched",a),la("local.messageMarker.fetched",i),sa("local.userMarker.fetched",c);const u=G(o.next);return{data:i,cachedAt:l,prevPage:G(o.previous),nextPage:u}},_a=async(e,t={limit:100})=>{const n=be();n.log("channel/getSubChannelMarkers",e,t);const{data:r}=await n.http.get("/api/v1/markers/message-feeds",{params:{messageFeedIds:e,options:{token:J(t,"skiplimit")}}}),{paging:o}=r,s=Zi(r,["paging"]),{userEntityMarkers:i,userFeedMarkers:a,userMarkers:c}=s,l=n.cache&&Date.now();n.cache&&Xi(s,{cachedAt:l}),aa("local.channelMarker.fetched",i),ca("local.subChannelMarker.fetched",a),sa("local.userMarker.fetched",c);const u=G(o.next);return{data:a,cachedAt:l,prevPage:G(o.previous),nextPage:u}},ka=async()=>{const e=be();e.log("channel/getUserMarker");const{data:t}=await e.http.get("/api/v1/markers/userMarker"),{userMarkers:n}=t,r=e.cache&&Date.now();return e.cache&&Xi(t,{cachedAt:r}),sa("local.userMarker.fetched",n),{data:n[0],cachedAt:r}},Sa=["broadcast","conversation","community"],Aa=({channelType:e})=>Sa.includes(e);function Ea(e,t){var{channelId:n,channelPublicId:r,channelType:o,childCount:s,creatorId:i,creatorPublicId:a,lastMessageId:c,lastMessageTimestamp:l,messageFeedId:u,name:d}=e,h=Zi(e,["channelId","channelPublicId","channelType","childCount","creatorId","creatorPublicId","lastMessageId","lastMessageTimestamp","messageFeedId","name"]);return Object.assign(Object.assign({},h),{channelId:r,creatorId:a,displayName:d,lastActivity:l,latestMessageId:c,messageCount:s,subChannelId:u,isUnreadCountSupport:Aa({channelType:o}),unreadCount:oa(n,u,t)})}const Ia=async e=>{let t=[];const n=e.messageFeeds.filter(Aa).map((({messageFeedId:e})=>e));if(n.length>0){(e=>{Xi({messageFeeds:e.messageFeeds.map((e=>Ea(e)))})})(e);try{({data:t}=await _a(n))}catch(e){}}const r=e.messageFeeds.map((e=>{const n=null==t?void 0:t.find((({feedId:t})=>t===e.messageFeedId));return Ea(e,n)}));return Object.assign(Object.assign({},e),{messageFeeds:r})};function Oa(e){var{excludeDefaultSubChannel:t}=e,n=Zi(e,["excludeDefaultSubChannel"]);const r=Object.assign({},n);return void 0!==t&&(r.excludeDefaultMessageFeed=t),r}const Ta=async e=>{const t=be();t.log("channel/getSubChannel",e),ba("subChannel",e);try{const n=await t.http.get(`/api/v5/message-feeds/${encodeURIComponent(e)}`),r=await Ia(n.data),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("local.message-feed.fetched",r),{data:r.messageFeeds[0],cachedAt:o}}catch(t){throw _(null==t?void 0:t.code)&&wa("subChannel",e),t}};Ta.locally=e=>{const t=be();if(t.log("channel/getSubChannel.locally",e),!t.cache)return;const n=De(["subChannel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const xa=async e=>{const t=be();t.log("subChannel/startReadingAPI",e);const{data:n}=await t.http.post("/api/v1/markers/message-feeds/reading",{messageFeedIds:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:a}),ia("local.feedMarker.fetched",s),aa("local.channelMarker.fetched",r),ca("local.subChannelMarker.fetched",o),sa("local.userMarker.fetched",i),!0},Ra=async e=>{const t=be();t.log("channel/stopReadingAPI",e);const{data:n}=await t.http.post(`/api/v1/markers/message-feeds/${e}/stop-reading`),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:a}),ia("local.feedMarker.fetched",s),aa("local.channelMarker.fetched",r),ca("local.subChannelMarker.fetched",o),sa("local.userMarker.fetched",i),!0};let Pa=null,Ma=[];const ja={},Fa=async()=>{const e=Object.entries(ja).filter((([,e])=>e)).map((([e])=>e));return 0!==e.length&&xa(e)},Ba=()=>{null==Pa||Pa(),Pa=null},Na=()=>(null===Pa&&(Pa=va(Fa,3e4)),ya((e=>{"notLoggedIn"===e&&Ba()})),()=>{Ba()}),Ua=()=>{Ma.push((()=>{const e=()=>{Fa()};return window.addEventListener("online",e),()=>window.removeEventListener("online",e)})())},Da=async e=>{const t=await(async e=>{const t=Ta.locally(e);if(t)return t.data.channelId;const{data:n}=await Ta(e);return n.channelId})(e),n=wt({channelId:t,subChannelId:e});Ma.push(At(n))},La=(e,t)=>{const n=be();return dt(n,e,e,(e=>{n.cache&&Xi(e),t(e.users[0])}))},qa=e=>La("user.deleted",e),$a=async()=>{const e=be();return e.log("client/api/disconnectClient"),await new Promise((t=>{e.ws.once("disconnect",t),e.ws.disconnect(),e.mqtt.disconnect()})),"established"===e.sessionState&&Gi("notLoggedIn"),e.emitter.all.clear(),e.ws.removeAllListeners(),e.mqtt.removeAllListeners(),e.userId=void 0,e.token=void 0,e.http.defaults.headers.common.Authorization="",e.ws.io.opts.query={token:""},"tokenExpired"!==e.sessionState&&e.cache&&(e.cache={data:{}}),!e.ws.connected},za=e=>{const t=be();Gi("terminated"),t.http.defaults.metadata&&("globalBan"===e&&(t.http.defaults.metadata.isGlobalBanned=!0),"userDeleted"===e&&(t.http.defaults.metadata.isUserDeleted=!0)),t.sessionHandler=void 0,$a()},Ha=["disconnected","error","connect_error","reconnect_error","reconnect_failed"],Va=e=>{const t=be(),n=Ha.map((n=>dt(t,`client/onConnectionError(${n})`,n,(t=>{const r=(null==t?void 0:t.code)?new pe(t.message,t.code,"fatal"):new ye(n);e(r)}))));return()=>{n.forEach((e=>e()))}},Wa=e=>{const t=be();return dt(t,"client/onConnectionError(user.didGlobalBan)","user.didGlobalBan",e)},Ka=e=>{const t=ce("channelMarker")({userId:rt()._id,entityId:e.channelId});ze(["channelMarker","get",t],!0)},Qa=[],Ja=async(e,t,n)=>{var r,o,s;const i=be();let a;i.log("client/api/connectClient",Object.assign({apiKey:i.apiKey,sessionState:i.sessionState},e)),i.userId&&i.userId!==e.userId&&(await $a(),Qa.forEach((e=>e()))),null!==(r=e.deviceId)&&void 0!==r||(e.deviceId=Ki());try{const{users:n}=await Yi(e);c=i.ws,l=i.emitter,ct.forEach((e=>{c.on(e,(t=>{l.emit(e,t)}))})),await new Promise((e=>{i.ws.once("connect",e),i.ws.open()})),i.userId=e.userId,i.sessionHandler=t,a=i.accessTokenExpiryWatcher(null===(o=i.token)||void 0===o?void 0:o.expiresAt,null===(s=i.token)||void 0===s?void 0:s.issuedAt,t),ot(n[0])}catch(e){throw Gi("notLoggedIn"),e}var c,l;return!0!==(null==n?void 0:n.disableRTE)&&await gt(),Qa.push(Wa((e=>{za("globalBan"),Qa.forEach((e=>e())),a()})),(e=>{const t=be();return dt(t,"client/onTokenTerminated","tokenTerminated",e)})((e=>{za(),Qa.forEach((e=>e())),a()})),qa((e=>{e.userId===i.userId&&(za("userDeleted"),Qa.forEach((e=>e())),a())})),(e=>{const t=be();return dt(t,"client/onTokenExpired","tokenExpired",e)})((e=>{Gi(e),$a(),Qa.forEach((e=>e()))})),ga(Ka),ma(Ka),Na()),i.ws.connected},Ga=()=>{let e,t=!1;const n=be();n.log("initiating access token renewal");const r=async r=>{const{userId:o,displayName:s}=rt(),i={userId:o,displayName:s,authToken:r,deviceId:Ki()};"tokenExpired"===n.sessionState?await Ja(i,n.sessionHandler):await Yi(i),t=!0,e&&clearTimeout(e)};return{renew:()=>{t?console.log("'renew' method can be called only once per renewal instance"):r()},renewWithAuthToken:e=>{t?console.log("'renewWithAuthToken' method can be called only once per renewal instance"):r(e)},unableToRetrieveAuthToken:()=>{e=setTimeout((()=>{var e;null===(e=n.sessionHandler)||void 0===e||e.sessionWillRenewAccessToken(Ga())}),g)}}},Ya=3e5,Xa=(e,t,n)=>{const r=setInterval((()=>{if((e=>Date.now()>Date.parse(e)-Ya)(e))return ht("tokenExpired","tokenExpired"),void at((()=>n.sessionWillRenewAccessToken(Ga())));(e=>{const{expiresAt:t,issuedAt:n}=e,r=Date.parse(t),o=Date.parse(n),s=Date.now();return s>o+.8*(r-o-Ya)&&s<r})({expiresAt:e,issuedAt:t})&&n.sessionWillRenewAccessToken(Ga())}),g);return()=>clearInterval(r)},Za=async e=>{const t=be();t.log("channel/markerSync");const{data:n}=await t.http.post("/api/v1/markers/sync",{deviceLastSyncAt:e}),{userEntityMarkers:r,userFeedMarkers:o,feedMarkers:s,userMarkers:i}=n,a=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:a}),ia("local.feedMarker.fetched",s),aa("local.channelMarker.fetched",r),ca("local.subChannelMarker.fetched",o),sa("local.userMarker.fetched",i),{data:n,hasMore:n.feedMarkers.length>0}},ec=e=>{const t=be();return dt(t,"feedMarker/onFeedMarkerUpdated","marker.feed-updated",(t=>{e(t.feedMarkers[0])}))},tc=e=>{const t=be();return dt(t,"userMarker/onUserMarkerFetched","local.userMarker.fetched",(t=>{e(t.userMarkers[0])}))};function nc(e,t){if(null==e||null==t)return e===t;if(e.constructor!==t.constructor)return!1;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>nc(e[n],t[n])))}const rc=(e,t,n,r,o,s)=>{const{forceDispatch:i,callbackDataSelector:a,callbackFilter:c}=Object.assign({forceDispatch:!1,callbackDataSelector:e=>e},s),{cache:l}=be();let u;l||console.log("For using Live Object feature you need to enable Cache!");let d=!1;const h=[],f=e=>{const{data:n}=e,r=Zi(e,["data"]);c&&!c(n,u)||t(Object.assign({data:a(n)},r)),u=n};return h.push(...o.map((t=>t((t=>((t,r=!1)=>{e===t[n]&&(u&&!r&&nc(u,t)||f({loading:!1,data:t,origin:"event"}))})(t,i)))))),(()=>{const t=re(r,e,!0);se(t,(({error:e,data:t,loading:n,origin:r,cachedAt:o})=>{-5===o?(f({data:t,origin:r,loading:!1,error:new ge("Observing unsynced object is not supported by Live Object.",800800,"error")}),d=!0,h.forEach((e=>e()))):d||f({loading:n,data:t,origin:r,error:e}),e&&h.forEach((e=>e()))}))})(),()=>{h.forEach((e=>e()))}},oc=async e=>{const t=be();t.log("channel/getChannelByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/channels/list",{params:{channelIds:n}})).data}catch(t){throw e.forEach((e=>{_(null==t?void 0:t.code)&&wa("channel",e)})),t}const o=await pa(r),s=t.cache&&Date.now();return t.cache&&Xi(o,{cachedAt:s}),{data:o.channels,cachedAt:s}};oc.locally=e=>{var t;const n=be();if(n.log("channel/getChannelByIds.locally",e),!n.cache)return;const r=e.map((e=>De(["channel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const sc=async e=>{const t=be();let n;t.log("channel/getChannel",e),ba("channel",e);try{const{data:r}=await t.http.get(`/api/v3/channels/${encodeURIComponent(e)}`);n=await pa(r)}catch(t){throw _(null==t?void 0:t.code)&&wa("channel",e),t}const r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{channels:o}=n;return{data:o.find((t=>t.channelId===e)),cachedAt:r}};sc.locally=e=>{const t=be();if(t.log("channel/getChannel.locally",e),!t.cache)return;const n=De(["channel","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const ic=e=>{const t=be();return dt(t,"onChannelCreated","channel.created",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])}))},ac=e=>{const t=be(),n=[dt(t,"onChannelUpdated","channel.updated",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])})),dt(t,"onChannelUpdated","local.channel.updated",(t=>e(t.channels[0])))];return()=>{n.forEach((e=>e()))}},cc=e=>{const t=be();return dt(t,"onChannelJoined","channel.joined",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o[0])}))},lc=e=>{const t=be();return dt(t,"onChannelLeft","channel.left",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o[0])}))},uc=e=>{const t=be();return dt(t,"onChannelMuted","channel.setMuted",(async t=>{const n=await pa(t);Xi(n),e(n.channels[0])}))},dc=e=>{const t=be();return dt(t,"onChannelMemberAdded","channel.membersAdded",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o.find((e=>"member"===e.membership)))}))},hc=e=>{const t=be();return dt(t,"onChannelMemberRemoved","channel.membersRemoved",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o[0])}))},fc=e=>{const t=be();return dt(t,"onChannelMemberUnbanned","channel.unbanned",(async t=>{const n=await pa(t),{channels:r,channelUsers:o}=n;Xi(n),e(r[0],o.find((e=>"none"===e.membership)))}))},pc=e=>!0===e&&void 0;function gc(e,t){const{channelPublicId:n,childCount:r,creatorPublicId:o,mentionedUsers:s,messageFeedId:i,myReactions:a,reactionCount:c,reactions:l,referenceId:u,segment:d,messageId:h}=e,f=Zi(e,["channelPublicId","childCount","creatorPublicId","mentionedUsers","messageFeedId","myReactions","reactionCount","reactions","referenceId","segment","messageId"]),{readCount:p,deliveredCount:g}=ra(e,t);let m;u&&(m=De(["message","get",u])),m||(m=De(["message","get",h]));const y=Object.assign(Object.assign({},f),{messageId:h,channelId:n,channelSegment:d,childrenNumber:r,creatorId:o,reactions:null!=l?l:{},reactionsCount:c,subChannelId:i,uniqueId:m?m.data.uniqueId:h,readCount:p,deliveredCount:g,referenceId:u});return s&&(y.mentionees=s.map((e=>"channel"===e.type?e:{type:"user",userIds:e.userPublicIds}))),a?y.myReactions=a:(e=>{const t=be(),n=De(["message","get",e.messageId]),r=(null==n?void 0:n.data.myReactions)||[];Object.assign(e,{myReactions:r});const o=null==e?void 0:e.latestReaction;o&&o.userId===t.userId&&("add"!==o.eventName||r.includes(o.reactionName)||Object.assign(e,{myReactions:[...r,o.reactionName]}),"remove"===o.eventName&&r.includes(o.reactionName)&&Object.assign(e,{myReactions:r.filter((e=>e!==o.reactionName))}))})(y),y}const mc=async e=>{let t=[];const n=e.messages.map((({messageId:e})=>e));if(n.length>0){Xi({messages:e.messages.map((e=>gc(e)))});try{({data:t}=await Ca(n))}catch(e){}}return Object.assign(Object.assign({},e),{messages:e.messages.map((e=>{const n=null==t?void 0:t.find((({contentId:t})=>t===e.messageId));return gc(e,n)}))})};function yc(e){var{subChannelId:t,mentionees:n}=e,r=Zi(e,["subChannelId","mentionees"]);return Object.assign({messageFeedId:t,mentionedUsers:n},r)}function vc(e){var{page:t,sortBy:n,subChannelId:r,tags:o,includeDeleted:s}=e,i=Zi(e,["page","sortBy","subChannelId","tags","includeDeleted"]);const a=Object.assign(Object.assign({},i),{messageFeedId:r,isDeleted:pc(s),options:{token:J(t||{limit:10},"afterbeforeraw")}});return void 0!==n&&(a.options.sortBy=n),o&&(a.includeTags=o),a}const bc=(e,t=!0)=>{const n=be(),r=[dt(n,"message/onMessageCreated","message.created",(async t=>{const n=await mc(t),r=n.messages[0];Xi(n),e(r)}))];return t&&dt(n,"message/onMessageCreated","local.message.created",(t=>e(t.messages[0]))),()=>{r.forEach((e=>e()))}},wc=e=>{const t=be(),n=[dt(t,"onMessageUpdated","message.updated",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])})),dt(t,"onMessageUpdated","local.message.updated",(t=>e(t.messages[0]))),dt(t,"onMessageUpdated","marker.marked-message",(async t=>{const n=function(e){var t,n,r;const o=["message","get"],s=null===(n=null===(t=Ue(["user","get"]))||void 0===t?void 0:t.filter((({data:t})=>t._id===e.creatorId)))||void 0===n?void 0:n[0].data;if(!s)return;const i=null===(r=Ue(o))||void 0===r?void 0:r.filter((({data:t})=>t.subChannelId===e.feedId&&t.creatorId===s.userId));return i?i.map((({data:t})=>{const{readCount:n,deliveredCount:r}=ra(t,e),s=Object.assign(Object.assign({},t),{readCount:n,deliveredCount:r,updatedAt:(new Date).toISOString()});return $e(o,s),s})):void 0}(t.contentMarkers[0]);n&&n.forEach((t=>e(t)))}))];return()=>{n.forEach((e=>e()))}},Cc=e=>{const t=be(),n=[dt(t,"message/onMessageDeleted","message.deleted",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])})),dt(t,"message/onMessageDeleted","local.message.deleted",(t=>e(t.messages[0])))];return()=>{n.forEach((e=>e()))}},_c=e=>{const t=be();return dt(t,"onMessageFlagged","message.flagged",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},kc=e=>{const t=be();return dt(t,"onMessageUnflagged","message.unflagged",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Sc=e=>{const t=be();return dt(t,"onMessageFlagCleared","message.flagCleared",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Ac=e=>{const t=be();return dt(t,"onMessageReactionAdded","message.reactionAdded",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Ec=e=>{const t=be();return dt(t,"onMessageReactionRemoved","message.reactionRemoved",(async t=>{const n=await mc(t);Xi(n),e(n.messages[0])}))},Ic=e=>{const t=be();return dt(t,"message/onMessageFetched","local.message.fetched",(t=>{Xi(t),e(t.messages[0])}))},Oc=async e=>{const t=be();t.log("channel/queryChannels",e);const n=null!=e?e:{},{page:r={limit:10},displayName:o,membership:s}=n,i=Zi(n,["page","displayName","membership"]),{data:a}=await t.http.get("/api/v3/channels",{params:Object.assign(Object.assign({},i),{keyword:o,filter:s,options:{token:J(r,"skiplimit")}})}),{paging:c}=a,l=Zi(a,["paging"]),u=await pa(l),{channels:d}=u,h=t.cache&&Date.now();if(t.cache){Xi(u,{cachedAt:h});const e=["channel","query",Object.assign(Object.assign({},i),{options:Object.assign({},r)})];Le(e,{channels:d.map(ce("channel")),paging:c})}const f=G(c.next);return{data:d,cachedAt:h,prevPage:G(c.previous),nextPage:f}},Tc=async e=>{const t=be();t.log("channel/queryChannelMembers",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get(`/api/v4/channels/${encodeURIComponent(o.channelId)}/users`,{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i}=s,a=Zi(s,["paging"]),c=await pa(a),{channelUsers:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c);const e=["channelUsers","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{channelUsers:l.map((({channelId:e,userId:t})=>ce("channelUsers")({channelId:e,userId:t}))),paging:i})}return{data:l,cachedAt:u,nextPage:G(i.next),prevPage:G(i.previous)}};Tc.locally=e=>{var t,n;const r=be();if(r.log("channel/queryChannelMembers.locally",e),!r.cache)return;const{page:o}=e,s=Zi(e,["page"]),i=["channelUsers","query",Object.assign(Object.assign({},s),{options:Object.assign({},o)})],{data:a,cachedAt:c}=null!==(t=De(i))&&void 0!==t?t:{};if(!(null==a?void 0:a.channelUsers.length))return;const l=a.channelUsers.map((e=>De(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),u=G(null==a?void 0:a.paging.previous),d=G(null==a?void 0:a.paging.next);return l.length===(null===(n=null==a?void 0:a.channelUsers)||void 0===n?void 0:n.length)?{data:l,cachedAt:c,prevPage:u,nextPage:d}:void 0};const xc=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["channelUsers","collection",{channelId:e.channelId}],g=t=>{let n=Ve(t,"roles",e.roles);e.memberships&&(n=n.filter((t=>!(!e.memberships.includes("muted")||!t.isMuted)||e.memberships.includes(t.membership)))),e.search&&(console.warn("`search` param will be deprecated in the next major release. If you want to search channel members by displayName, Please use `searchMembers()` instead."),n=Ge(n,e.search));const r=e.sortBy?e.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?et:Ze),n},m=(e,n=!1)=>{var r,o;const s=null!==(r=e.data.map((e=>De(["channelUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:v,data:n?g(s):s,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},y=t=>(t,n)=>{var r;if(e.channelId!==n.channelId)return;const o=null===(r=De(d))||void 0===r?void 0:r.data;if(!o)return;const s=ce("channelUsers")({channelId:e.channelId,userId:n.userId});"none"===n.membership?o.data=o.data.filter((e=>e!==s)):o.data.includes(s)||(o.data=[s,...o.data]),Le(d,o),m(o,!0)},v=(e=!1)=>{var t,n,r;const o=null===(t=De(d))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Tc,Object.assign(Object.assign({},a),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:c}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("channelUsers"))])]),Le(d,o),m(o)}),oe(l))};return u.push(cc(y()),lc(y()),dc(y()),hc(y()),ma(y()),fc(y())),v(!0),()=>{r(`getMembers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}};var Rc=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();n.log("channel/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users`,{channelId:e,userIds:t});t.forEach((e=>ht("channel.membersAdded",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await pa(r);n.cache&&Xi(o);const{channelUsers:s}=o;return!!s.find((t=>t.channelId===e&&"member"===t.membership))},removeMembers:async(e,t)=>{const n=be();n.log("channel/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users`,{data:{channelId:e,userIds:t}});t.forEach((e=>ht("channel.membersRemoved",Object.assign(Object.assign({},r),{channelUsers:r.channelUsers.filter((t=>t.userId===e))}))));const o=await pa(r);n.cache&&Xi(o);const{channelUsers:s}=o;return!!s.find((t=>t.channelId===e&&"member"!==t.membership))},getMembers:xc,searchMembers:(e,t,n)=>xc(e,t,n)});var Pc=Object.freeze({__proto__:null,addRole:async(e,t,n)=>{const r=be();r.log("channel/addRole",e,t,n);const{data:o}=await r.http.post(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{channelId:e,role:t,userIds:n}),s=await pa(o);r.cache&&Xi(s);const{channelUsers:i}=s;return!!i.find((n=>n.channelId===e&&n.roles.includes(t)))},removeRole:async(e,t,n)=>{const r=be();r.log("channel/removeRole",e,t,n);const{data:o}=await r.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/users/roles`,{data:{channelId:e,role:t,userIds:n}}),s=await pa(o);r.cache&&Xi(s);const{channelUsers:i}=s;return!!i.find((n=>n.channelId===e&&!n.roles.includes(t)))},banMembers:async(e,t)=>{const n=be();n.log("channel/banMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${e}/users/ban`,{userIds:t}),o=await pa(r),{channelUsers:s}=o,i=n.cache&&Date.now();return n.cache&&Xi(o,{cachedAt:i}),{data:null==s?void 0:s.filter((e=>"banned"===e.membership)),cachedAt:i}},unbanMembers:async(e,t)=>{const n=be();n.log("channel/unbanMembers",{userIds:t,channelId:e});const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}/users/unban`,{userIds:t}),o=await pa(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{channelUsers:i}=o;return{data:null==i?void 0:i.filter((e=>"member"===e.membership)),cachedAt:s}}}),Mc=Object.freeze({__proto__:null,Membership:Rc,Moderation:Pc,getChannelByIds:oc,createChannel:async e=>{const t=be();let n;t.log("user/createChannel",e),n="conversation"===(null==e?void 0:e.type)?await t.http.post("/api/v3/channels/conversation",Object.assign(Object.assign({},e),{isDistinct:!0})):await t.http.post("/api/v3/channels",e);const r=await pa(n.data),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{channels:s}=r;return{data:s[0],cachedAt:o}},updateChannel:async(e,t)=>{const n=be();n.log("channel/updateChannel",e,t);const{data:r}=await n.http.put(`/api/v3/channels/${encodeURIComponent(e)}`,t),o=await pa(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{channels:i}=o;return{data:i.find((t=>t.channelId===e)),cachedAt:s}},deleteChannel:async e=>{const t=be();t.log("channel/deleteChannel",e),await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}`);return(await sc(e)).data},joinChannel:async e=>{const t=be();t.log("channel/joinChannel",e);const{data:n}=await t.http.post(`/api/v3/channels/${encodeURIComponent(e)}/join`),r=await pa(n);t.cache&&Xi(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"===t.membership))},leaveChannel:async e=>{const t=be();t.log("channel/leaveChannel",e);const{data:n}=await t.http.delete(`/api/v3/channels/${encodeURIComponent(e)}/leave`),r=await pa(n);t.cache&&Xi(r);const{channelUsers:o}=r;return!!o.find((t=>t.channelId===e&&"member"!==t.membership))},muteChannel:async(e,t=-1)=>{const n=be();if(n.log("channel/muteChannel",e),-1!==t&&t<0)throw new pe("Mute Period can only be positive numbers or -1(mute forever)",800110,"error");const{data:r}=await n.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:t}),{success:o}=r;return o},unmuteChannel:async e=>{const t=be();t.log("channel/unmuteChannel",e);const{data:n}=await t.http.put(`/api/v2/channel/${encodeURIComponent(e)}/mute`,{mutePeriod:0}),{success:r}=n;return r},markAsRead:async e=>{const t=be();t.log("channel/markAsRead",e);const{data:n}=await t.http.put(`/api/v1/markers/channels/${e}/mark-read`),r=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:r}),!0},onChannelCreated:ic,onChannelUpdated:ac,onChannelDeleted:ga,onChannelJoined:cc,onChannelLeft:lc,onChannelMuted:uc,onChannelMemberAdded:dc,onChannelMemberRemoved:hc,onChannelMemberBanned:ma,onChannelMemberUnbanned:fc,observeChannel:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeChannel(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.channelId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}},s=[];return s.push(ac((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),ga((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),cc((e=>o({data:e,loading:!1,origin:"event"},"onJoin"))),lc((e=>o({data:e,loading:!1,origin:"event"},"onLeft"))),uc((e=>o({data:e,loading:!1,origin:"event"},"onMute"))),dc((e=>o({data:e,loading:!1,origin:"event"},"onMemberAdded"))),hc((e=>o({data:e,loading:!1,origin:"event"},"onMemberRemoved")))),se(re(sc,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeChannel(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},observeChannels:e=>{const{log:t}=be(),n=Date.now();t(`observeChannels(tmpid: ${n}) > listen`);const r=[],o=(t,n)=>{var r,o;if(e instanceof Function)return e(t);null===(r=e.onEvent)||void 0===r||r.call(e,n,t),null===(o=e[n])||void 0===o||o.call(e,t)};return r.push(ic((e=>o(e,"onCreate"))),ac((e=>o(e,"onUpdate"))),ga((e=>o(e,"onDelete"))),cc((e=>o(e,"onJoin"))),lc((e=>o(e,"onLeft"))),uc((e=>o(e,"onMute"))),dc((e=>o(e,"onMemberAdded"))),hc((e=>o(e,"onMemberRemoved")))),()=>{t(`observeChannels(tmpid: ${n}) > dispose`),r.forEach((e=>e()))}},getChannel:(e,t)=>rc(e,t,"channelId",sc,[ac,ga,cc,lc,dc,hc,ma,fc,uc,()=>bc((()=>null))]),getChannels:(e,t,n)=>{const{log:r,cache:o,userId:s}=be();o||console.log(p);const i=Date.now();r(`getChannels(tmpid: ${i}) > listen`);const{limit:a}=e,c=Zi(e,["limit"]),l=null!=a?a:h,{policy:u=f}=null!=n?n:{},d=[],g=["channel","collection",{}],m=n=>{var r,o;let i=null!==(r=n.data.map((e=>De(["channel","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];switch(i=He(i,"isDeleted",e.isDeleted),i=He(i,"displayName",e.displayName),e.types&&(i=i.filter((t=>{var n;return null===(n=e.types)||void 0===n?void 0:n.includes(t.type)}))),e.tags&&(i=i.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),e.excludeTags&&(i=i.filter((t=>{var n;return!(null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.excludeTags)||void 0===n?void 0:n.includes(t)})))}))),e.membership&&s&&(i=We(i,e.membership,s)),e.sortBy){case"firstCreated":i=i.sort(Ze);break;case"lastCreated":i=i.sort(et);break;case"displayName":i=i.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ye);break;default:i=i.sort(tt)}t({onNextPage:b,data:i,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},v=e=>e=>{var t;const n=null===(t=De(g))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.channelId,...n.data])],Le(g,n),m(n))},b=(e=!1)=>{var t,n,r;const o=null===(t=De(g))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Oc,Object.assign(Object.assign({},c),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:l}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("channel"))])]),Le(g,o),m(o)}),oe(u,y))};return d.push(ic(v()),ga(v()),ac(v()),uc(v()),cc(v()),lc(v()),dc(v()),hc(v()),bc((()=>null))),b(!0),ze(g),()=>{r(`getChannels(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},MARKER_INCLUDED_CHANNEL_TYPE:da,isUnreadCountSupport:ha,convertFromRaw:fa,prepareChannelPayload:pa});const jc=e=>{const t=be();return dt(t,"onSubChannelCreated","message-feed.created",(async t=>{const n=await Ia(t);Xi(n),e(n.messageFeeds[0])}))},Fc=e=>{const t=be(),n=[dt(t,"onSubChannelUpdated","message-feed.updated",(async t=>{const n=await Ia(t);Xi(n),e(n.messageFeeds[0])})),dt(t,"onSubChannelUpdated","local.message-feed.updated",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}},Bc=e=>{const t=be(),n=[dt(t,"onSubChannelDeleted","message-feed.deleted",(async t=>{const n=await Ia(t);Xi(n),e(n.messageFeeds[0])})),dt(t,"local.message-feed.deleted","local.message-feed.deleted",(t=>e(t.messageFeeds[0])))];return()=>{n.forEach((e=>e()))}};let Nc,Uc=[],Dc=!1,Lc=null;const qc=e=>{(!Lc||new Date(e).getTime()>new Date(Lc).getTime())&&(Lc=e)};let $c=[];const zc=e=>{$c=e},Hc=e=>$c.push(e),Vc=async()=>{if(Dc)return;if(0===$c.length)return;Dc=!0,$c=[];const e=await Za(null==Lc?(new Date).toISOString():Lc);qc(e.data.userMarkers[0].lastSyncAt),e.hasMore&&$c.push("has_more"),Dc=!1},Wc=()=>{Uc.push((()=>{const e=()=>$c.push("resume");return window.addEventListener("online",e),()=>window.removeEventListener("online",e)})(),bc((e=>{Aa(e)&&$c.push("new message")}),!1),ic((()=>$c.push("subchannel is created"))),ga((()=>$c.push("subchannel is deleted"))),cc((()=>$c.push("subchannel is joined"))),lc((()=>$c.push("subchannel is left"))),jc((()=>$c.push("subchannel is created"))),Bc((()=>$c.push("subchannel is deleted"))),ec((()=>$c.push("feed marker updated"))))},Kc=()=>{null==Nc||Nc(),Nc=void 0,zc([]),Uc.forEach((e=>e())),Uc=[]};var Qc=Object.freeze({__proto__:null,getActiveClient:be,getActiveUser:rt,setActiveUser:ot,createClient:(e,t=Bt.SG,{debugSession:n="amity",apiEndpoint:r}={})=>{var o,s;const i=(e=>{const t=`${null==e?void 0:e.trim()}`.length>0&&!Ft,n=Pt(e),r=(e,...r)=>{t&&n(e,r)};return r.__instance__=n,r})(n);i("client/api/createClient",{apiKey:e.replace(/.{5}$/g,"xxxxx"),apiRegion:t});const a=null!==(o=null==r?void 0:r.http)&&void 0!==o?o:Ut("http",t),c=null!==(s=null==r?void 0:r.mqtt)&&void 0!==s?s:Ut("mqtt",t),l=kr(a),u=(e=>{const t=Ui(e,{autoConnect:!1,reconnectionDelay:2e3,transports:["websocket"]});return t.on("disconnect",(e=>{"io server disconnect"===e&&t.connect()})),t})(a),h=Vi(c),f=ut(),p={version:`${d}`,apiKey:e,log:i,cache:{data:{}},http:l,ws:u,mqtt:h,emitter:f,sessionState:"notLoggedIn",accessTokenExpiryWatcher:Xa,sessionHandler:undefined,getFeedSettings:Wi,use:()=>we(p)};try{return be()}catch(e){we(p)}return p},login:Ja,logout:$a,isConnected:()=>{var e,t;const n=be();return n.log("client/api/isConnected",n),!!(n.userId&&(null===(t=String(null===(e=n.http.defaults.headers.common)||void 0===e?void 0:e.Authorization))||void 0===t?void 0:t.length)&&n.ws.connected)},getFeedSettings:Wi,renewal:Ga,markerSync:Za,onConnectionError:Va,onClientDisconnected:e=>Va((({code:t})=>{800211===t&&e()})),onClientBanned:Wa,onSessionStateChange:ya,getTotalUnreadCount:e=>{const{_id:t}=rt();if(!t)throw new pe("The _id has not been defined in ActiveUser",8e5,"error");return rc(t,e,"userId",ka,[tc],{callbackDataSelector:e=>{var t;return null!==(t=null==e?void 0:e.unreadCount)&&void 0!==t?t:0},callbackFilter:(e,t)=>(null==e?void 0:e.unreadCount)!==(null==t?void 0:t.unreadCount)})},getMarkerSyncEvents:()=>$c,setMarkerSyncEvents:zc,pushMarkerSyncEvent:Hc,markerSyncTrigger:Vc,startUnreadSync:async()=>{await(async()=>{const{data:e}=await ka();qc(e.lastSyncAt)})(),Hc("start syncing"),Nc||(Nc=va(Vc,2e3)),Wc()},stopUnreadSync:Kc,stopUnreadSyncing:()=>(console.warn("`stopUnreadSyncing` has been deprecated, please use `stopUnreadSync` instead"),Kc())});const Jc=async e=>{const t=be();let n={};if(e){const{token:t,limit:r}=e;n={limit:r,token:t}}t.log("user/queryBlockedUsers");const{data:r}=await t.http.get("/api/v4/me/user-blocks",{params:n}),{paging:o}=r,s=Zi(r,["paging"]),{users:i}=s,a=t.cache&&Date.now();if(t.cache){Xi(s,{cachedAt:a});Le(["blockedUsers","query",n],{users:i.map(ce("user")),paging:o})}const{next:c,previous:l,total:u}=o,d=Y(c);return{data:i,prevPage:Y(l),nextPage:d,total:u,cachedAt:a}};Jc.locally=(e={})=>{var t,n,r;const o=be();if(o.log("user/queryBlockedUsers.locally"),!o.cache)return;let s={};if(e){const{token:t,limit:n}=e;s={token:t,limit:n}}const i=["blockedUsers","query",s],{data:a,cachedAt:c}=null!==(t=De(i))&&void 0!==t?t:{},l=null!==(n=null==a?void 0:a.users.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[],u=Y(null==a?void 0:a.paging.next),d=Y(null==a?void 0:a.paging.previous);return l.length>0&&l.length===(null===(r=null==a?void 0:a.users)||void 0===r?void 0:r.length)?{data:l,nextPage:u,prevPage:d,total:null==a?void 0:a.paging.total,cachedAt:c}:void 0};const Gc=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getBlockedUsers(tmpid: ${s}) > listen`);const{limit:i,token:a}=e,c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["blockedUsers","collection",{}],g=(e=!1)=>{var n,r;const o=null===(n=De(d))||void 0===n?void 0:n.data,s=null!==(r=null==o?void 0:o.data)&&void 0!==r?r:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Jc,{limit:c,token:J(e||null==o?void 0:o.params.page,"afterbeforeraw")});se(i,(({data:e,loading:n,error:r,nextPage:o,total:i})=>{const a={loading:n,error:r,params:{page:o,total:i},data:s};e&&(a.data=[...new Set([...s,...e.map(ce("user"))])]),Le(d,a),(e=>{var n,r;const o=null!==(n=e.data.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];t({onNextPage:g,data:o,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})})(a)}),oe(l,y))};return u.push((()=>{})),g(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),u.forEach((e=>e())),ze(d)}},Yc=(e,t)=>{const n=be();return dt(n,e,e,(e=>{var r,o;if(n.cache){Xi(e);[...null!==(r=Ue(["followers","query"]))&&void 0!==r?r:[],...null!==(o=Ue(["followings","query"]))&&void 0!==o?o:[]].filter((({key:t})=>t[2].userId===e.follows[0].from||t[2].userId===e.follows[0].to)).forEach((({key:e,data:t})=>$e(e,t,{cachedAt:-1}))),t(e.follows[0])}else t(e.follows[0])}))},Xc=e=>Yc("follow.created",e),Zc=e=>Yc("follow.unfollowed",e),el=e=>Yc("follow.followerDeleted",e),tl=e=>Yc("follow.requested",e),nl=e=>Yc("follow.requestCanceled",e),rl=e=>Yc("follow.accepted",e),ol=e=>Yc("follow.requestDeclined",e),sl=async e=>{var t,n;const r=be();r.log("follow/getFollowInfo",e);const{data:o}=await r.http.get(r.userId===e?"/api/v4/me/followInfo":`/api/v5/users/${e}/followInfo`),s=r.cache&&Date.now(),i="follows"in o?Object.assign(Object.assign({},o.followCounts[0]),{status:null===(n=null===(t=o.follows)||void 0===t?void 0:t[0])||void 0===n?void 0:n.status}):o.followCounts[0];return r.cache&&Le(["followInfo","get",e],i,{cachedAt:s}),{data:i,cachedAt:s}};sl.locally=e=>{const t=be();if(t.log("follow/getFollowInfo.locally",e),!t.cache)return;const n=De(["followInfo","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const il=e=>{const t=async t=>{const[{data:n},{data:r}]=await Promise.all([sl(t.from),sl(t.to)]);e(n),e(r)},n=[Yc("follow.created",t),Yc("follow.requested",t),Yc("follow.accepted",t),Yc("follow.unfollowed",t),Yc("follow.requestCanceled",t),Yc("follow.requestDeclined",t),Yc("follow.followerDeleted",t)];return()=>{n.forEach((e=>e()))}},al=async(e,t)=>{const n=be();n.log(`follow/queryF${e.substring(1)}`,t);const{userId:r,page:o}=t,s=Zi(t,["userId","page"]),{data:i}=await n.http.get(n.userId===r?`/api/v4/me/${e}`:`/api/v4/users/${r}/${e}`,{params:Object.assign(Object.assign({},s),{token:J(o,"afterbeforeraw")})}),{paging:a}=i,c=Zi(i,["paging"]),{follows:l}=c,u=n.cache&&Date.now();if(n.cache){Xi(c,{cachedAt:u});const t=["follow","query",Object.assign(Object.assign({},s),{userId:r,options:Object.assign({},o),type:e})];Le(t,{follows:l.map(ce("follow")),paging:a})}const d=Y(a.next);return{data:l,cachedAt:u,prevPage:Y(a.previous),nextPage:d}};al.locally=(e,t)=>{var n,r;const o=be();if(o.log(`follow/queryF${e.substring(1)}.locally`,t),!o.cache)return;const{page:s}=t,i=Zi(t,["page"]),a=["follow","query",Object.assign(Object.assign({},i),{options:Object.assign({},s),type:e})],{data:c,cachedAt:l}=null!==(n=De(a))&&void 0!==n?n:{};if(!(null==c?void 0:c.follows.length))return;const u=c.follows.map((e=>De(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)),d=Y(null==c?void 0:c.paging.previous),h=Y(null==c?void 0:c.paging.next);return u.length===(null===(r=null==c?void 0:c.follows)||void 0===r?void 0:r.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};const cl=async e=>al("followers",e);cl.locally=e=>al.locally("followers",e);const ll=async e=>al("following",e);ll.locally=e=>al.locally("following",e);var ul=Object.freeze({__proto__:null,blockUser:async e=>{const t=be();t.log("user/blockUser",e);const{data:n}=await t.http.post(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:s}=n,i={follows:o};return t.cache&&(Xi(i,{cachedAt:r}),$e(["followInfo","get",e],s[0],{cachedAt:r})),ht("follow.unfollowed",i),n},unBlockUser:async e=>{const t=be();t.log("user/unBlockUser",e);const{data:n}=await t.http.delete(`/api/v4/me/user-blocks/${e}`),r=t.cache&&Date.now(),{follows:o,followCounts:s}=n,i={follows:o};return t.cache&&(Xi(i,{cachedAt:r}),$e(["followInfo","get",e],s[0],{cachedAt:r})),ht("follow.created",i),n},getBlockedUsers:(e,t,n)=>(console.log("Deprecation Notice: UserRepository.Relationship.getBlockedUsers will be deprecated on 9th June 2023, please use UserRepository.getBlockedUsers instead."),Gc(e,t,n)),follow:async e=>{const t=be();t.log("follow/follow",e);const{data:n}=await t.http.post(`/api/v4/me/following/${e}`),r=t.cache&&Date.now();return t.cache&&Xi(n,{cachedAt:r}),ht("accepted"===n.follows[0].status?"follow.created":"follow.requested",n),{data:n.follows[0],cachedAt:r}},unfollow:async e=>{const t=be();t.log("follow/unfollow",e);const{data:n}=await t.http.delete(`/api/v4/me/following/${e}`);return t.cache&&Xi(n),ht("follow.unfollowed",n),!0},acceptFollower:async e=>{const t=be();t.log("follow/acceptFollower",e);const{data:n}=await t.http.post(`/api/v4/me/followers/${e}`);return t.cache&&Xi(n),ht("follow.accepted",n),!0},declineFollower:async e=>{const t=be();t.log("follow/declineFollower",e);const{data:n}=await t.http.delete(`/api/v4/me/followers/${e}`);return t.cache&&Xi(n),ht("follow.requestDeclined",n),!0},onUserFollowed:Xc,onUserUnfollowed:Zc,onFollowerDeleted:el,onFollowerRequested:tl,onFollowRequestCanceled:nl,onFollowRequestAccepted:rl,onFollowRequestDeclined:ol,onFollowInfoUpdated:il,observeFollowInfo:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeFollowInfo(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=[];return i.push(il((t=>((t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.userId)===e&&s(t,n)})({data:t,loading:!1,origin:"event"},"onUpdate")))),se(re(sl,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observeFollowInfo(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},observeFollowers:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFollowers(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(n.from===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(tl((e=>s(e,"onRequested"))),rl((e=>s(e,"onAccepted"))),ol((e=>s(e,"onDeclined"))),nl((e=>s(e,"onCanceled"))),Xc((e=>s(e,"onFollowed"))),Zc((e=>s(e,"onUnfollowed"))),el((e=>s(e,"onDeleted")))),()=>{n(`observeFollowers(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeFollowings:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFollowings(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(n.to===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(tl((e=>s(e,"onRequested"))),rl((e=>s(e,"onAccepted"))),ol((e=>s(e,"onDeclined"))),nl((e=>s(e,"onCanceled"))),Xc((e=>s(e,"onFollowed"))),Zc((e=>s(e,"onUnfollowed"))),el((e=>s(e,"onDeleted")))),()=>{n(`observeFollowings(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},getFollowers:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["follow","collection",{userId:e.userId,type:"follower"}],p=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(s=He(s,"status",e.status)),t({onNextPage:m,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.userId===n.to&&o&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?o.data=o.data.filter((e=>e!==ce("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(o.data=[...new Set([ce("follow")(n),...o.data])]),Le(d,o),p(o))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(cl,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("follow"))])]),Le(d,o),p(o)}),oe(l))};return u.push(tl(g("onRequested")),rl(g("onAccepted")),ol(g("onDeclined")),nl(g("onCanceled")),Xc(g("onFollowed")),Zc(g("onUnfollowed")),el(g("onDeleted"))),m(!0),()=>{r(`getFollowers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},getFollowings:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getFollowings(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["follow","collection",{userId:e.userId,type:"following"}],p=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["follow","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.status&&"all"!==e.status&&(s=He(s,"status",e.status)),t({onNextPage:m,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.userId===n.from&&o&&(["onDeclined","onCanceled","onUnfollowed","onDeleted"].includes(t)?o.data=o.data.filter((e=>e!==ce("follow")(n))):["onRequested","onAccepted","onFollowed"].includes(t)&&(o.data=[...new Set([ce("follow")(n),...o.data])]),Le(d,o),p(o))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(ll,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("follow"))])]),Le(d,o),p(o)}),oe(l))};return u.push(tl(g("onRequested")),rl(g("onAccepted")),ol(g("onDeclined")),nl(g("onCanceled")),Xc(g("onFollowed")),Zc(g("onUnfollowed")),el(g("onDeleted"))),m(!0),()=>{r(`getFollowings(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},getFollowInfo:(e,t)=>rc(e,t,"userId",sl,[il],{forceDispatch:!0})});const dl=async e=>{const t=be();t.log("user/getUsers",e);const n=e.map((e=>encodeURIComponent(e))),{data:r}=await t.http.get("/api/v3/users/list",{params:{userIds:n}}),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("user.fetched",r),{data:r.users,cachedAt:o}};dl.locally=e=>{var t;const n=be();if(n.log("user/getUsers.locally",e),!n.cache)return;const r=e.map((e=>De(["user","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const hl=e=>La("user.updated",e),fl=e=>La("user.flagged",e),pl=e=>La("user.unflagged",e),gl=e=>La("user.flagCleared",e),ml=e=>La("user.fetched",e),yl=async e=>{const t=be();let n;t.log("user/getUser",e),ba("user",e);try{n=(await t.http.get(`/api/v3/users/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&wa("user",e),t}const r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{users:o}=n;return ht("user.fetched",n),{data:o.find((t=>t.userId===e)),cachedAt:r}};yl.locally=e=>{const t=be();return t.log("user/getUser.locally",e),t.cache&&De(["user","get",e])};const vl=async(e={})=>{const t=be();t.log("user/queryUsers",e);const{page:n={limit:10},displayName:r,filter:o="all",sortBy:s="displayName"}=e,i=Zi(e,["page","displayName","filter","sortBy"]),{data:a}=await t.http.get("/api/v3/users",{params:Object.assign(Object.assign({},i),{keyword:r,filter:o,sortBy:s,options:{token:J(n,"skiplimit")}})}),{paging:c}=a,l=Zi(a,["paging"]),{users:u}=l,d=t.cache&&Date.now();if(t.cache){Xi(l,{cachedAt:d});const t=["user","query",Object.assign(Object.assign({},e),{options:Object.assign({},n)})];Le(t,{users:u.map(ce("user")),paging:c})}ht("user.fetched",a);return{data:u,cachedAt:d,prevPage:G(c.previous),nextPage:G(c.next)}};vl.locally=(e={})=>{var t,n,r;const o=be();if(o.log("user/queryUsers.locally",e),!o.cache)return;const{page:s={limit:10}}=null!=e?e:{},i=["user","query",Object.assign(Object.assign({},e),{options:Object.assign({},s)})],{data:a,cachedAt:c}=null!==(t=De(i))&&void 0!==t?t:{},l=null!==(n=null==a?void 0:a.users.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[],u=G(null==a?void 0:a.paging.previous),d=G(null==a?void 0:a.paging.next);return l.length>0&&l.length===(null===(r=null==a?void 0:a.users)||void 0===r?void 0:r.length)?{data:l,cachedAt:c,prevPage:u,nextPage:d}:void 0};const bl=(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`liveUsers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["user","collection",{}],g=t=>{let n=He(t,"displayName",e.displayName);switch(e.sortBy){case"firstCreated":n=n.sort(Ze);break;case"lastCreated":n=n.sort(et);break;default:n=n.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ye)}return n},m=(e,n=!1)=>{var r,o;const s=null!==(r=e.data.map((e=>De(["user","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:v,data:n?g(s):s,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},y=e=>e=>{var t;const n=null===(t=De(d))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.userId,...n.data])],Le(d,n),m(n,!0))},v=(e=!1)=>{var t,n,r;const o=null===(t=De(d))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(vl,Object.assign(Object.assign({},a),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:c}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("user"))])]),Le(d,o),m(o)}),oe(l))};return u.push(hl(y()),qa(y()),fl(y()),pl(y()),gl(y())),v(!0),()=>{r(`liveUsers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}};var wl=Object.freeze({__proto__:null,Relationship:ul,getUserByIds:dl,updateUser:async(e,t)=>{const n=be();n.log("user/updateUser",e,t);const{data:r}=await n.http.put("/api/v3/users/",Object.assign(Object.assign({userId:e},t),{createNewUserWhenNotFound:!1})),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{users:s}=r;return ht("user.updated",r),{data:s.find((t=>t.userId===e)),cachedAt:o}},flagUser:async e=>{const t=be();t.log("user/flagUser",e);const{data:n}=await t.http.post(`api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Xi(n),ht("user.flagged",n),!!n},unflagUser:async e=>{const t=be();t.log("user/unflag",e);const{data:n}=await t.http.delete(`/api/v4/me/flags/${encodeURIComponent(e)}`);return t.cache&&Xi(n),ht("user.unflagged",n),!!n},isUserFlaggedByMe:async e=>{var t,n;const r=be();r.log("user/isUserFlaggedByMe",e);const{result:o,isFlagByMe:s}=null!==(t=await Di(r,"user.isFlagByMe",{userId:e}))&&void 0!==t?t:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n},onUserUpdated:hl,onUserDeleted:qa,onUserFlagged:fl,onUserUnflagged:pl,onUserFlagCleared:gl,getUser:(e,t)=>rc(e,t,"userId",yl,[ml,hl,qa,fl,pl,gl]),getUsers:bl,observeUser:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeUser(tmpid: ${r}) > listen`);const o=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.userId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}},s=[];return s.push(hl((e=>o({data:e,loading:!1,origin:"event"},"onUpdate"))),qa((e=>o({data:e,loading:!1,origin:"event"},"onDelete"))),fl((e=>o({data:e,loading:!1,origin:"event"},"onFlagged"))),pl((e=>o({data:e,loading:!1,origin:"event"},"onUnflagged"))),gl((e=>o({data:e,loading:!1,origin:"event"},"onFlagCleared")))),se(re(yl,e),(e=>e.data&&o(e,"onFetch"))),()=>{n(`observeUser(tmpid: ${r}) > dispose`),s.forEach((e=>e()))}},getBlockedUsers:Gc,searchUserByDisplayName:(e,t,n)=>bl(Object.assign(Object.assign({},e),{filter:"all"}),t,n)});const Cl=async e=>{const t=be();t.log("file/getFile",e);const{data:n}=await t.http.get(`/api/v3/files/${e}`),r=t.cache&&Date.now();return t.cache&&Xi({files:[n]},{cachedAt:r}),{data:n,cachedAt:r}};Cl.locally=e=>{const t=be();if(t.log("file/getFile.locally",e),!t.cache)return;const n=De(["file","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};var _l=Object.freeze({__proto__:null,getFile:Cl,uploadFile:async(e,t)=>{const n=be();if(n.log("file/uploadFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/files",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},deleteFile:async e=>{const t=be();return t.log("file/deleteFile",e),await t.http.delete(`/api/v3/files/${e}`),ze(["file","get",e],!0),{success:!0}},fileUrlWithSize:(e,t)=>`${e}?size=${t}`,uploadVideo:async(e,t,n)=>{const r=be();if(r.log("file/uploadVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),i=r.cache&&Date.now();return r.cache&&Xi({files:s},{cachedAt:i}),{data:s,cachedAt:i}},uploadImage:async(e,t)=>{const n=be();if(n.log("file/uploadImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/images",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},createImage:async(e,t)=>{const n=be();if(n.log("file/createImage",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/images",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},createFile:async(e,t)=>{const n=be();if(n.log("file/createFile",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");const r="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:o}=await n.http.post("/api/v4/files",e,{headers:r,onUploadProgress({loaded:e,total:n=100}){t&&t(Math.round(100*e/n))}}),s=n.cache&&Date.now();return n.cache&&Xi({files:o},{cachedAt:s}),{data:o,cachedAt:s}},createVideo:async(e,t,n)=>{const r=be();if(r.log("file/createVideo",e),!e.getAll("files").length)throw new Error("The formData object must have a `files` key.");t&&e.append("feedType",t);const o="getHeaders"in e?e.getHeaders():{"content-type":"multipart/form-data"},{data:s}=await r.http.post("/api/v4/videos",e,{headers:o,onUploadProgress({loaded:e,total:t=100}){n&&n(Math.round(100*e/t))}}),i=r.cache&&Date.now();return r.cache&&Xi({files:s},{cachedAt:i}),{data:s,cachedAt:i}},observeFile:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeFile(tmpid: ${r}) > listen`);return se(re(Cl,e),(n=>n.data&&((n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.fileId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}})(n,"onFetch"))),()=>{n(`observeFile(tmpid: ${r}) > dispose`)}}});const kl=async e=>{const t=be();t.log("role/queryRoles",e);const n=null!=e?e:{},{page:r={limit:10},displayName:o,sortBy:s}=n,i=Zi(n,["page","displayName","sortBy"]),{data:a}=await t.http.get("/api/v3/roles",{params:Object.assign(Object.assign({},i),{keyword:o,sortBy:s,options:{token:J(r,"skiplimit")}})}),{paging:c}=a,l=Zi(a,["paging"]),{roles:u}=l,d=t.cache&&Date.now();t.cache&&Xi(l,{cachedAt:d});const h=G(c.next);return{data:u,cachedAt:d,prevPage:G(c.previous),nextPage:h}};kl.locally=e=>{be().log("role/queryRoles.locally",e)};const Sl=async e=>{const t=be();t.log("role/getRole",e);const{data:n}=await t.http.get(`/api/v3/roles/${e}`),r=t.cache&&Date.now();return t.cache&&Xi({roles:n},{cachedAt:r}),{data:n.find((t=>t.roleId===e)),cachedAt:r}};Sl.locally=e=>{const t=be();if(t.log("role/getRole.locally",e),!t.cache)return;const n=De(["role","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Al=(e,t)=>{"message"===e?ht("local.message.updated",{messages:[t]}):"post"===e?ht("post.updated",{posts:[t]}):"comment"===e&&ht("comment.updated",{comments:[t]})},El=async(e,t=!1)=>{const n=be();let r;n.log("message/getMessage",e),t||console.log("getMessage will be deprecated on 15th November 2022, please use liveMessage instead."),ba("message",e);try{const{data:t}=await n.http.get(`/api/v5/messages/${encodeURIComponent(e)}`);r=await mc(t)}catch(t){throw _(null==t?void 0:t.code)&&wa("message",e),t}const o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{messages:s}=r;return ht("local.message.fetched",{messages:s}),{data:s.find((t=>t.messageId===e)),cachedAt:o}};El.locally=e=>{const t=be();if(t.log("message/getMessage.locally",e),!t.cache)return;const n=De(["message","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Il=async e=>{const t=be();let n;t.log("post/getPost",e),ba("post",e);try{n=(await t.http.get(`/api/v3/posts/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&wa("post",e),t}const r=ta(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{posts:s}=r;return{data:s.find((t=>t.postId===e)),cachedAt:o}};Il.locally=e=>{const t=be();if(t.log("post/getPost.locally",e),!t.cache)return;const n=De(["post","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Ol=async e=>{const t=be();let n;t.log("comment/getComment",e),ba("comment",e);try{n=(await t.http.get(`/api/v3/comments/${encodeURIComponent(e)}`)).data}catch(t){throw _(null==t?void 0:t.code)&&wa("comment",e),t}const r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{comments:o}=n;return{data:o.find((t=>t.commentId===e)),cachedAt:r}};Ol.locally=e=>{const t=be();if(t.log("comment/getComment.locally",e),!t.cache)return;const n=De(["comment","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const Tl=(e,t)=>{if(be().userId!==t.reactor.userId)return t;const n=e.split(".")[0],r=e.split(".")[1];let o;const s=((e,t)=>{var n,r;let o;if("post"===t)o=e.posts[0].postId;else{if("comment"!==t)throw new Error("Unknown event type");o=e.comments[0].commentId}return(null===(r=null===(n=De(["comment","get",o]))||void 0===n?void 0:n.data)||void 0===r?void 0:r.myReactions)||[]})(t,n);if("addReaction"===r)o=[...s,t.reactor.reactionName];else{if("removeReaction"!==r)throw new Error("Unknown event type");o=s.filter((e=>e!==t.reactor.reactionName))}return((e,t,n)=>{const[r]=e[t];return Object.assign(Object.assign({},e),{[t]:[Object.assign(Object.assign({},r),{myReactions:n})]})})(t,`${n}s`,o)},xl=async(e,t,n)=>{const r=be();if(r.log("reaction/createReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.post("/api/v2/reactions",{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}),r.cache){const n=De([e,"get",t]);(null==n?void 0:n.data)&&Le([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};xl.optimistically=(e,t,n)=>{var r,o,s,i,a;const c=be();if(c.log("reaction/createReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=De([e,"get",t]);if(!(null==l?void 0:l.data)||(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const u=Object.assign(Object.assign({},l.data),{reactionsCount:l.data.reactionsCount+1,myReactions:[...null!==(o=l.data.myReactions)&&void 0!==o?o:[],n],reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)+1})});return $e([e,"get",t],u,{cachedAt:-5}),Al(e,u),null!==(a=null===(i=null==u?void 0:u.myReactions)||void 0===i?void 0:i.includes(n))&&void 0!==a&&a};const Rl=async(e,t,n)=>{const r=be();if(r.log("reaction/removeReaction",{referenceId:t,referenceType:e,reactionName:n}),await r.http.delete("/api/v2/reactions",{data:{referenceId:t,referenceType:e,reactionName:n,referenceVersion:"message"===e?5:void 0}}),r.cache){const n=De([e,"get",t]);(null==n?void 0:n.data)&&Le([e,"get",t],n.data,{cachedAt:Date.now()})}return!0};Rl.optimistically=(e,t,n)=>{var r,o,s,i,a;const c=be();if(c.log("reaction/removeReaction.optimistically",{referenceId:t,referenceType:e,reactionName:n}),!c.cache)return;const l=De([e,"get",t]);if(!(null==l?void 0:l.data)||!(null===(r=l.data.myReactions)||void 0===r?void 0:r.includes(n)))return;const u=Object.assign(Object.assign({},l.data),{reactionsCount:Math.max(0,l.data.reactionsCount-1),myReactions:(null!==(o=l.data.myReactions)&&void 0!==o?o:[]).filter((e=>e!==n)),reactions:Object.assign(Object.assign({},l.data.reactions),{[n]:Math.max(0,(null!==(s=l.data.reactions[n])&&void 0!==s?s:0)-1)})});return $e([e,"get",t],u,{cachedAt:-5}),Al(e,u),null!==(a=!(null===(i=null==u?void 0:u.myReactions)||void 0===i?void 0:i.includes(n)))&&void 0!==a&&a};const Pl=(e,t)=>{const n=be();return dt(n,e,e,(r=>{var o;if(n.cache){const{communities:n}=r,s=Zi(r,["communities"]),i=ta(s,"communityUsers");Xi(i),(null==n?void 0:n[0])&&!["post.updated"].includes(e)&&ht("community.updated",{communities:n,categories:[],communityUsers:[],feeds:[],files:[],users:[]});const a=De(["post","get",r.posts[0].postId]);if(["post.created","post.approved","post.declined"].includes(e)){let t=null===(o=Ue(["post","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.targetId)===a.data.targetId}));"post.declined"===e&&(t=null==t?void 0:t.filter((({key:e})=>{var t;return"reviewing"===(null===(t=e[2])||void 0===t?void 0:t.feedType)}))),null==t||t.map((({key:e,data:t})=>$e(e,t,{cachedAt:-1})))}t(a.data)}else t(r.posts[0])}))},Ml=e=>Pl("post.created",e),jl=e=>Pl("post.updated",e),Fl=e=>Pl("post.deleted",e),Bl=e=>Pl("post.approved",e),Nl=e=>Pl("post.declined",e),Ul=e=>Pl("post.flagged",e),Dl=e=>Pl("post.unflagged",e),Ll=e=>{const t=be();return dt(t,"post.addReaction","post.addReaction",(n=>{if(t.cache){const t=Zi(Tl("post.addReaction",n),["reactor"]);Xi(t);const r=De(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},ql=e=>{const t=be();return dt(t,"post.removeReaction","post.removeReaction",(n=>{if(t.cache){const t=Zi(Tl("post.removeReaction",n),["reactor"]);Xi(t);const r=De(["post","get",n.posts[0].postId]);e(r.data)}else e(n.posts[0])}))},$l=(e,t)=>{const n=be();return dt(n,e,e,(r=>{var o;if(n.cache){Xi(r);const n=De(["comment","get",r.comments[0].commentId]);if(["comment.created"].includes(e)){const e=null===(o=Ue(["comment","query"]))||void 0===o?void 0:o.filter((({key:e})=>{var t;return(null===(t=e[2])||void 0===t?void 0:t.referenceId)===n.data.referenceId}));null==e||e.map((({key:e,data:t})=>$e(e,t,{cachedAt:-1})))}t(n.data)}else t(r.comments[0])}))},zl=e=>$l("comment.created",e),Hl=e=>$l("comment.updated",e),Vl=e=>$l("comment.deleted",e),Wl=e=>$l("comment.flagged",e),Kl=e=>$l("comment.unflagged",e),Ql=e=>{const t=be();return dt(t,"comment.addReaction","comment.addReaction",(n=>{if(t.cache){const t=Zi(Tl("comment.addReaction",n),["reactor"]);Xi(t);const r=De(["comment","get",n.comments[0].commentId]);e(r.data)}else e(n.comments[0])}))},Jl=e=>{const t=be();return dt(t,"comment.removeReaction","comment.removeReaction",(n=>{if(t.cache){const t=Zi(Tl("comment.removeReaction",n),["reactor"]);Xi(t);const r=De(["comment","get",n.comments[0].commentId]);e(r.data)}else e(n.comments[0])}))},Gl=(e,t,n)=>{const r=be(),o=(r,o,s)=>{r===e&&o===t&&n(s)};if("message"===e){const e=async e=>{const t=await mc(e);if(!t.messages[0].latestReaction)return;const n=t.messages[0].latestReaction,{eventName:r,referenceId:s,referenceType:i,userDisplayName:a}=n,c=Zi(n,["eventName","referenceId","referenceType","userDisplayName"]);"add"===r&&(Xi(t),Xi({reactions:[c]}),o("message",t.messages[0].messageId,c))};return dt(r,"reaction/onReactorAdded","message.updated",e)}if("post"===e){return dt(r,"post.addReaction","post.addReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("post",e.posts[0].postId,t)}))}return dt(r,"comment.addReaction","comment.addReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},Yl=(e,t,n)=>{const r=be(),o=(r,o,s)=>{r===e&&o===t&&n(s)};if("message"===e){const e=async e=>{const t=await mc(e);if(!t.messages[0].latestReaction)return;const n=t.messages[0].latestReaction,{eventName:r,referenceId:s,referenceType:i}=n,a=Zi(n,["eventName","referenceId","referenceType"]);"remove"===r&&(Xi(t),Xi({reactions:[a]}),o("message",t.messages[0].messageId,a))};return dt(r,"reaction/onReactorRemoved","message.updated",e)}if("post"===e){return dt(r,"post.removeReaction","post.removeReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("post",e.posts[0].postId,t)}))}return dt(r,"comment.removeReaction","comment.removeReaction",(e=>{const{reactor:t}=e,n=Zi(e,["reactor"]);Xi(n),Xi({reactions:[t]}),o("comment",e.comments[0].commentId,t)}))},Xl=async e=>{const t=be();t.log("reaction/queryReactions",e);const n=null!=e?e:{},{page:r={limit:10}}=n,o=Zi(n,["page"]),{data:s}=await t.http.get("/api/v3/reactions",{params:Object.assign(Object.assign({},o),{options:{token:J(r,"afterbeforeraw")}})}),{paging:i}=s,a=Zi(s,["paging"]),{reactions:c}=a;Xi(Object.assign(Object.assign({},a),{reactions:c[0].reactors}));const l=Y(i.next);return{data:c,prevPage:Y(i.previous),nextPage:l}};var Zl=Object.freeze({__proto__:null,addReaction:xl,removeReaction:Rl,onReactionAdded:(e,t,n)=>{const r=r=>{ce(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await mc(e),o=De(["message","get",n.messages[0].messageId]),s=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xi(n),s&&r(n.messages[0])};return dt(e,"reaction/onReactionAdded","message.updated",t)}return"post"===e?Ll(r):Ql(r)},onReactionRemoved:(e,t,n)=>{const r=r=>{ce(e)(r)===t&&n(r)};if("message"===e){const e=be(),t=async e=>{var t;const n=await mc(e),o=De(["message","get",n.messages[0].messageId]),s=(null===(t=null==o?void 0:o.data)||void 0===t?void 0:t.reactionsCount)!==n.messages[0].reactionsCount;Xi(n),s&&r(n.messages[0])};return dt(e,"reaction/onReactionRemoved","message.updated",t)}return"post"===e?ql(r):Jl(r)},onReactorAdded:Gl,onReactorRemoved:Yl,getReactions:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`liveReactions(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["reaction","collection",{referenceId:e.referenceId,referenceType:e.referenceType}],p=e=>{var n,r;const o=null!==(n=e.data.map((e=>De(["reaction","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==n?n:[];t({onNextPage:m,data:o,hasNextPage:!!(null===(r=e.params)||void 0===r?void 0:r.page),loading:e.loading,error:e.error})},g=e=>t=>{var n;const r=null===(n=De(d))||void 0===n?void 0:n.data;r&&("onAdded"===e?r.data=[...new Set([t.reactionId,...r.data])]:"onRemoved"===e&&(r.data=r.data.filter((e=>e!==t.reactionId))),Le(d,r),p(r))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(Xl,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e[0].reactors.map(ce("reaction"))])]),Le(d,o),p(o)}),oe(l))};return u.push(Gl(a.referenceType,a.referenceId,g("onAdded")),Yl(a.referenceType,a.referenceId,g("onRemoved"))),m(!0),()=>{r(`liveReactions(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}}),eu={post:{domainName:"posts",eventName:"v3/post.isflagbyme",primaryKey:"postId"},comment:{domainName:"comments",eventName:"v3/comment.isflagbyme",primaryKey:"commentId"},message:{domainName:"messages",eventName:"v3/message.isFlaggedByMe",primaryKey:"messageId"},user:{domainName:"users",eventName:"user.isFlagByMe",primaryKey:"userId"}};const tu=async e=>{const t=be();t.log("message/getMessages",e);const{data:n}=await t.http.get("/api/v5/messages/list",{params:{messageIds:e.map(encodeURIComponent)}}),r=await mc(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{messages:s}=r;return ht("local.message.fetched",{messages:s}),{data:s,cachedAt:o}};tu.locally=e=>{var t;const n=be();if(n.log("message/getMessages.locally",e),!n.cache)return;const r=e.map((e=>De(["message","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};var nu={},ru={},ou={};Object.defineProperty(ou,"__esModule",{value:!0}),ou.bytesToString=ou.stringToBytes=ou.NIL=ou.X500=ou.OID=ou.URL=ou.DNS=ou.hexToByte=ou.byteToHex=void 0;let su=[],iu={};for(var au=0;au<256;au++)su[au]=(au+256).toString(16).substr(1),iu[su[au]]=au;ou.byteToHex=su,ou.hexToByte=iu,ou.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ou.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",ou.OID="6ba7b812-9dad-11d1-80b4-00c04fd430c8",ou.X500="6ba7b814-9dad-11d1-80b4-00c04fd430c8",ou.NIL="00000000-0000-0000-0000-000000000000";ou.stringToBytes=e=>{e=unescape(encodeURIComponent(e));const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t};ou.bytesToString=e=>{const t=new Uint8Array(e,0,e.byteLength);return String.fromCharCode.apply(null,Array.from(t))},Object.defineProperty(ru,"__esModule",{value:!0}),ru.parse=void 0;const cu=ou;ru.parse=(e,t,n)=>{let r=t&&n||0,o=0;for(t=t||[],e.toLowerCase().replace(/[0-9a-f]{2}/g,(e=>(o<16&&t&&(t[r+o++]=cu.hexToByte[e]),"")));o<16;)t[r+o++]=0;return t};var lu={};Object.defineProperty(lu,"__esModule",{value:!0}),lu.unparse=void 0;const uu=ou;lu.unparse=(e,t)=>{let n=t||0,r=uu.byteToHex;return r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+"-"+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]+r[e[n++]]};var du={},hu={};Object.defineProperty(hu,"__esModule",{value:!0});hu.default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;var fu=Ce&&Ce.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(du,"__esModule",{value:!0}),du.validate=void 0;const pu=fu(hu);du.validate=e=>"string"==typeof e&&pu.default.test(e);var gu={};Object.defineProperty(gu,"__esModule",{value:!0}),gu.version=void 0;const mu=du;gu.version=e=>{if(!mu.validate(e))throw TypeError("Invalid UUID");return parseInt(e.substr(14,1),16)};var yu={},vu={};Object.defineProperty(vu,"__esModule",{value:!0}),vu.stringify=void 0;const bu=du,wu=[];for(let e=0;e<256;++e)wu.push((e+256).toString(16).substr(1));vu.stringify=(e,t=0)=>{const n=(wu[e[t+0]]+wu[e[t+1]]+wu[e[t+2]]+wu[e[t+3]]+"-"+wu[e[t+4]]+wu[e[t+5]]+"-"+wu[e[t+6]]+wu[e[t+7]]+"-"+wu[e[t+8]]+wu[e[t+9]]+"-"+wu[e[t+10]]+wu[e[t+11]]+wu[e[t+12]]+wu[e[t+13]]+wu[e[t+14]]+wu[e[t+15]]).toLowerCase();if(!bu.validate(n))throw TypeError("Stringified UUID is invalid");return n};var Cu={};Object.defineProperty(Cu,"__esModule",{value:!0}),Cu.rng=void 0;Cu.rng=()=>{let e=new Array(16);for(let t=0;t<16;t++)e[t]=255&256*Math.random()+0;return e},Object.defineProperty(yu,"__esModule",{value:!0}),yu.v1=void 0;const _u=vu,ku=Cu;let Su,Au,Eu=0,Iu=0;yu.v1=(e,t,n=0)=>{let r=t&&n||0;const o=t||new Uint8Array(16);let s=e&&e.node?e.node:Su,i=e&&e.clockseq?e.clockseq:Au;if(null==s||null==i){const t=e&&e.random?e.random:e&&e.rng?e.rng():ku.rng();null==s&&(s=Su=[1|t[0],t[1],t[2],t[3],t[4],t[5]]),null==i&&(i=Au=16383&(t[6]<<8|t[7]))}let a=e&&e.msecs?e.msecs:Date.now(),c=e&&e.nsecs?e.nsecs:Iu+1;const l=a-Eu+(c-Iu)/1e4;if(l<0&&e&&!e.clockseq&&(i=i+1&16383),(l<0||a>Eu)&&e&&!e.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Eu=a,Iu=c,Au=i,a+=122192928e5;const u=(1e4*(268435455&a)+c)%4294967296;o[r++]=u>>>24&255,o[r++]=u>>>16&255,o[r++]=u>>>8&255,o[r++]=255&u;const d=a/4294967296*1e4&268435455;o[r++]=d>>>8&255,o[r++]=255&d,o[r++]=d>>>24&15|16,o[r++]=d>>>16&255,o[r++]=i>>>8|128,o[r++]=255&i;for(let e=0;e<6;++e)o[r+e]=s[e];return t||_u.stringify(o)};var Ou={};Object.defineProperty(Ou,"__esModule",{value:!0}),Ou.v4=void 0;const Tu=lu,xu=Cu;Ou.v4=(e,t,n)=>{let r=t&&n||0,o=xu.rng();if(!e||e instanceof String||(e.random&&(o=e.random),e.rng&&(o=e.rng())),o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var s=0;s<16;s++)t[r+s]=o[s];return t||Tu.unparse(o)};var Ru={},Pu={};Object.defineProperty(Pu,"__esModule",{value:!0}),Pu.v35=void 0;const Mu=vu,ju=ru,Fu=ou;Pu.v35=(e,t,n)=>(e,r,o,s=0)=>{if("string"==typeof e&&(e=Fu.stringToBytes(e)),"string"==typeof r&&(r=ju.parse(r)),r&&16!==r.length)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let i=new Uint8Array(16+e.length);if(i.set(r),i.set(e,r.length),i=Fu.stringToBytes(n(Fu.bytesToString(i))),i[6]=15&i[6]|t,i[8]=63&i[8]|128,o)for(let e=0;e<16;++e)o[s+e]=i[e];return o||Mu.stringify(i)};var Bu={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.any_hmac_sha1=e.b64_hmac_sha1=e.hex_hmac_sha1=e.any_sha1=e.b64_sha1=e.hex_sha1=void 0;let t=0,n="";e.hex_sha1=e=>s(r(c(e))),e.default=e.hex_sha1;e.b64_sha1=e=>i(r(c(e)));e.any_sha1=(e,t)=>a(r(c(e)),t);e.hex_hmac_sha1=(e,t)=>s(o(c(e),c(t)));e.b64_hmac_sha1=(e,t)=>i(o(c(e),c(t)));e.any_hmac_sha1=(e,t,n)=>a(o(c(e),c(t)),n);const r=e=>u(d(l(e),8*e.length)),o=(e,t)=>{let n=l(e);n.length>16&&(n=d(n,8*e.length));let r=Array(16),o=Array(16);for(var s=0;s<16;s++)r[s]=909522486^n[s],o[s]=1549556828^n[s];var i=d(r.concat(l(t)),512+8*t.length);return u(d(o.concat(i),672))},s=e=>{for(var n,r=t?"0123456789ABCDEF":"0123456789abcdef",o="",s=0;s<e.length;s++)n=e.charCodeAt(s),o+=r.charAt(n>>>4&15)+r.charAt(15&n);return o},i=e=>{for(var t="",r=e.length,o=0;o<r;o+=3)for(var s=e.charCodeAt(o)<<16|(o+1<r?e.charCodeAt(o+1)<<8:0)|(o+2<r?e.charCodeAt(o+2):0),i=0;i<4;i++)8*o+6*i>8*e.length?t+=n:t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(s>>>6*(3-i)&63);return t},a=(e,t)=>{var n,r,o,s,i=t.length,a=[],c=Array(Math.ceil(e.length/2));for(n=0;n<c.length;n++)c[n]=e.charCodeAt(2*n)<<8|e.charCodeAt(2*n+1);for(;c.length>0;){for(s=[],o=0,n=0;n<c.length;n++)o=(o<<16)+c[n],o-=(r=Math.floor(o/i))*i,(s.length>0||r>0)&&(s[s.length]=r);a[a.length]=o,c=s}var l="";for(n=a.length-1;n>=0;n--)l+=t.charAt(a[n]);var u=Math.ceil(8*e.length/(Math.log(t.length)/Math.log(2)));for(n=l.length;n<u;n++)l=t[0]+l;return l},c=e=>{for(var t,n,r="",o=-1;++o<e.length;)t=e.charCodeAt(o),n=o+1<e.length?e.charCodeAt(o+1):0,t>=55296&&t<=56319&&n>=56320&&n<=57343&&(t=65536+((1023&t)<<10)+(1023&n),o++),t<=127?r+=String.fromCharCode(t):t<=2047?r+=String.fromCharCode(192|t>>>6&31,128|63&t):t<=65535?r+=String.fromCharCode(224|t>>>12&15,128|t>>>6&63,128|63&t):t<=2097151&&(r+=String.fromCharCode(240|t>>>18&7,128|t>>>12&63,128|t>>>6&63,128|63&t));return r},l=e=>{for(var t=Array(e.length>>2),n=0;n<t.length;n++)t[n]=0;for(n=0;n<8*e.length;n+=8)t[n>>5]|=(255&e.charCodeAt(n/8))<<24-n%32;return t},u=e=>{for(var t="",n=0;n<32*e.length;n+=8)t+=String.fromCharCode(e[n>>5]>>>24-n%32&255);return t},d=(e,t)=>{e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n=Array(80),r=1732584193,o=-271733879,s=-1732584194,i=271733878,a=-1009589776,c=0;c<e.length;c+=16){for(var l=r,u=o,d=s,m=i,y=a,v=0;v<80;v++){n[v]=v<16?e[c+v]:g(n[v-3]^n[v-8]^n[v-14]^n[v-16],1);let t=p(p(g(r,5),h(v,o,s,i)),p(p(a,n[v]),f(v)));a=i,i=s,s=g(o,30),o=r,r=t}r=p(r,l),o=p(o,u),s=p(s,d),i=p(i,m),a=p(a,y)}return[r,o,s,i,a]},h=(e,t,n,r)=>e<20?t&n|~t&r:e<40?t^n^r:e<60?t&n|t&r|n&r:t^n^r,f=e=>e<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514,p=(e,t)=>{var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n},g=(e,t)=>e<<t|e>>>32-t}(Bu);var Nu=Ce&&Ce.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ru,"__esModule",{value:!0}),Ru.v5=void 0;const Uu=Pu,Du=Nu(Bu);Ru.v5=Uu.v35("v5",80,Du.default),Object.defineProperty(nu,"__esModule",{value:!0});const Lu=ru,qu=lu,$u=du,zu=gu,Hu=yu,Vu=Ou,Wu=Ru,Ku=ou;var Qu=nu.default={parse:Lu.parse,unparse:qu.unparse,validate:$u.validate,version:zu.version,v1:Hu.v1,v4:Vu.v4,v5:Wu.v5,NIL:Ku.NIL,DNS:Ku.DNS,URL:Ku.URL,OID:Ku.OID,X500:Ku.X500};const Ju=()=>`LOCAL_${Qu.v4().toString()}`;let Gu;const Yu=async e=>{const t=be();t.log("message/createMessage",e);const n=e.referenceId||Gu||Ju();Gu=void 0;const{data:r}=await t.http.post("/api/v5/messages",Object.assign(Object.assign({},yc(e)),{referenceId:n})),o=await mc(r),{messages:s}=o,i=t.cache&&Date.now();return t.cache&&(ze(["message","get",n]),Xi(o,{cachedAt:i})),ht("local.message.created",{messages:s}),{data:s[0],cachedAt:i}};Yu.optimistically=e=>{var t,n,{referenceId:r}=e,o=Zi(e,["referenceId"]);const s=be();if(!s.cache)return;Gu=r||Ju();const i=Object.assign({messageId:Gu,uniqueId:Gu},o);s.log("message/createMessage.optimistically",i);const a=De(["subChannel","get",o.subChannelId]);if(a&&($e(["subChannel","get",o.subChannelId],Object.assign(Object.assign({},a.data),{messageCount:a.data.messageCount+1})),a.data.channelId===a.data.subChannelId)){const e=De(["channel","get",a.data.channelId]);(null==e?void 0:e.data)&&$e(["channel","get",a.data.channelId],Object.assign(Object.assign({},e.data),{messageCount:(null!==(t=e.data.messageCount)&&void 0!==t?t:0)+1}))}const c=(new Date).toISOString(),l=Object.assign({creatorId:s.userId,channelSegment:(null!==(n=null==a?void 0:a.data.messageCount)&&void 0!==n?n:0)+1,childrenNumber:0,createdAt:c,updatedAt:c},i);return Le(["message","get",l.messageId],l,{cachedAt:-5}),ht("local.message.created",{messages:[l]}),{cachedAt:-5,data:l}};const Xu=async(e,t)=>{const n=be();n.log("message/updateMessage",t),console.warn("MessageRepository.updateMessage will be replaced with MessageRepository.editMessage");const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,yc(t)),o=await mc(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{messages:i}=o;return ht("local.message.updated",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Xu.optimistically=(e,t)=>{const n=be();if(n.log("message/updateMessage.optimistically",t),!n.cache)return;const r=De(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return $e(["message","get",e],o,{cachedAt:-1}),ht("local.message.updated",{messages:[o]}),{data:o,cachedAt:-1}};const Zu=async(e,t)=>{const n=be();n.log("message/editMessage",t);const{data:r}=await n.http.put(`/api/v5/messages/${encodeURIComponent(e)}`,yc(t)),o=await mc(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{messages:i}=o;return ht("local.message.updated",{messages:i}),{data:i.find((t=>t.messageId===e)),cachedAt:s}};Zu.optimistically=(e,t)=>{const n=be();if(n.log("message/editMessage.optimistically",t),!n.cache)return;const r=De(["message","get",e]);if(!r)return;const o=Object.assign(Object.assign(Object.assign({},r.data),t),{updatedAt:(new Date).toISOString()});return $e(["message","get",e],o,{cachedAt:-1}),ht("local.message.updated",{messages:[o]}),{data:o,cachedAt:-1}};const ed=async e=>{const t=be();t.log("message/deleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await El(e);return ht("local.message.deleted",{messages:[n.data]}),n.data};ed.optimistically=e=>{be().log("message/deleteMessage.optimistically",e);const t=De(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return $e(["message","get",e],n,{cachedAt:-1}),ht("local.message.deleted",{messages:[n]}),{data:n,cachedAt:-1}};const td=async e=>{const t=be();t.log("message/softDeleteMessage",e),await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}`);const n=await El(e);return ht("local.message.deleted",{messages:[n.data]}),n.data};td.optimistically=e=>{be().log("message/softDeleteMessage.optimistically",e);const t=De(["message","get",e]);if(!t)return;const n=Object.assign(Object.assign({},t.data),{isDeleted:!0,updatedAt:(new Date).toISOString()});return $e(["message","get",e],n,{cachedAt:-1}),ht("local.message.deleted",{messages:[n]}),{data:n,cachedAt:-1}};const nd=async e=>{const t=be();t.log("user/getReadUsers",e);const{page:n,messageId:r}=e,o=Zi(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/read-users`,{params:Object.assign(Object.assign({},o),{options:{token:J(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:a}=s,c=Zi(s,["paging","publicUserIds"]),l=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:l});const e=["read-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];Le(e,{users:a,paging:i})}let u=[];a.length>0&&({data:u}=await dl(a));return{data:u,cachedAt:l,prevPage:G(i.previous),nextPage:G(i.next)}};nd.locally=e=>{var t;const n=be();if(n.log("user/getReadUsers.locally",e),!n.cache)return;const{page:r}=e,o=Zi(e,["page"]),s=["read-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=De(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:a,prevPage:G(null==i?void 0:i.paging.previous),nextPage:G(null==i?void 0:i.paging.next)}};const rd=async e=>{const t=be();t.log("user/getDeliveredUsers",e);const{page:n,messageId:r}=e,o=Zi(e,["page","messageId"]),{data:s}=await t.http.get(`/api/v1/markers/messages/${r}/delivered-users`,{params:Object.assign(Object.assign({},o),{options:{token:J(n,"afterbeforeraw")}})}),{paging:i,publicUserIds:a}=s,c=Zi(s,["paging","publicUserIds"]),l=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:l});const e=["delivered-user","query",Object.assign(Object.assign({messageId:r},o),{options:Object.assign({},n)})];Le(e,{users:a,paging:i})}let u=[];a.length>0&&({data:u}=await dl(a));return{data:u,cachedAt:l,prevPage:G(i.previous),nextPage:G(i.next)}};rd.locally=e=>{var t;const n=be();if(n.log("user/getDeliveredUsers.locally",e),!n.cache)return;const{page:r}=e,o=Zi(e,["page"]),s=["delivered-user","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{},c=null==i?void 0:i.users.map((e=>{var t;return null===(t=De(["user","get",e]))||void 0===t?void 0:t.data}));if(!c||c.some((e=>!e)))return;return{data:c,cachedAt:a,prevPage:G(null==i?void 0:i.paging.previous),nextPage:G(null==i?void 0:i.paging.next)}};const od=async e=>{const t=be();t.log("message/queryMessages",e);const n=vc(e),{data:r}=await t.http.get("/api/v5/messages",{params:n}),{paging:o}=r,s=Zi(r,["paging"]),i=await mc(s),{messages:a}=i,c=t.cache&&Date.now();if(t.cache){Xi(i,{cachedAt:c});Le(["message","query",n],{messages:a.map(ce("message")),paging:o})}ht("local.message.fetched",{messages:a});const l=Y(o.next);return{data:a,cachedAt:c,prevPage:Y(o.previous),nextPage:l}};var sd=Object.freeze({__proto__:null,getMessageByIds:tu,createMessage:Yu,updateMessage:Xu,editMessage:Zu,deleteMessage:ed,softDeleteMessage:td,markAsDelivered:async(e,t)=>{const n=be();n.log("message/markAsDelivered",e,t);const{data:r}=await n.http.put(`/api/v1/markers/message-feeds/${e}/mark-delivering`,{messageId:t}),o=n.cache&&Date.now();return n.cache&&Xi(r,{cachedAt:o}),!0},getReadUsers:nd,getDeliveredUsers:rd,flagMessage:async e=>{const t=be();t.log("message/flag",e);const{data:n}=await t.http.post(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await mc(n);Xi(e)}return ht("message.flagged",n),!!n},unflagMessage:async e=>{const t=be();t.log("message/unflag",e);const{data:n}=await t.http.delete(`/api/v5/messages/${encodeURIComponent(e)}/flags`);if(t.cache){const e=await mc(n);Xi(e)}return ht("message.unflagged",n),!!n},isMessageFlaggedByMe:async e=>{const t=be();t.log("message/isMessageFlaggedByMe",e);const{data:n}=await t.http.get(`/api/v5/messages/${encodeURIComponent(e)}/flags`);return n.result},onMessageCreated:bc,onMessageUpdated:wc,onMessageDeleted:Cc,onMessageFlagged:_c,onMessageUnflagged:kc,onMessageFlagCleared:Sc,onMessageReactionAdded:Ac,onMessageReactionRemoved:Ec,onMessageFetched:Ic,getMessage:(e,t)=>rc(e,t,"messageId",El,[Ic,wc,Cc,_c,kc,Sc,Ac,Ec]),getMessages:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getMessages(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["message","collection",e],g=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["message","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.includeDeleted||(s=He(s,"isDeleted",!1)),t({onNextPage:v,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},m=t=>t=>{var n;const r=null===(n=De(d))||void 0===n?void 0:n.data;e.subChannelId===(null==t?void 0:t.subChannelId)&&r&&(r.data=[...new Set([t.messageId,...r.data])],Le(d,r),g(r))},v=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(od,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("message"))])]),Le(d,o),g(o)}),oe(l,y))};return u.push(Ic(m()),bc(m()),wc(m()),Cc(m()),_c(m()),kc(m()),Sc(m()),Ac(m()),Ec(m())),v(!0),u.push((()=>ze(d))),()=>{r(`getMessages(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},observeMessage:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeMessage(tmpid: ${o}) > listen`),console.log("observeMessage will be deprecated on 15th November 2022, please use liveMessage instead.");const s=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.messageId)===e){if(t instanceof Function)return t(n);"onFetch"!==r&&(null===(s=t.onEvent)||void 0===s||s.call(t,r,n)),null===(i=t[r])||void 0===i||i.call(t,n)}},i=[];return i.push(wc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Cc((e=>s({data:e,loading:!1,origin:"event"},"onDelete")))),"no_fetch"!==n&&se(re(El,e),(e=>e.data&&s(e,"onFetch")),oe(n)),()=>{r(`observeMessages(tmpid: ${o}) > dispose`),i.forEach((e=>e()))}},observeMessages:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeMessages(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s,i;if((null===(o=n.data)||void 0===o?void 0:o.subChannelId)===e){if(t instanceof Function)return t(n);null===(s=t.onEvent)||void 0===s||s.call(t,r,n),null===(i=t[r])||void 0===i||i.call(t,n)}};return o.push(bc((e=>s({data:e,loading:!1,origin:"event"},"onCreate"))),wc((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),Cc((e=>s({data:e,loading:!1,origin:"event"},"onDelete")))),()=>{n(`observeMessages(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},convertFromRaw:gc,prepareMessagePayload:mc,convertParams:yc,convertQueryParams:vc});const id=async e=>{const t=be();t.log("channel/getSubChannels",e);const n=await t.http.get("/api/v5/message-feeds/list",{params:{messageFeedIds:e.map(encodeURIComponent)}}),r=await Ia(n.data),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("local.message-feed.fetched",r),{data:r.messageFeeds,cachedAt:o}};id.locally=e=>{var t;const n=be();if(n.log("channel/getSubChannels.locally",e),!n.cache)return;const r=e.map((e=>De(["subChannel","get",e]))).filter(Boolean);if((null==r?void 0:r.length)<e.length)return;return{data:r.map((({data:e})=>e)),cachedAt:(null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0]).cachedAt}};const ad=async(e,t=!1)=>{const n=be(),r=await Ta(e);await n.http.delete(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{params:{permanent:t}});const o=Object.assign(Object.assign({},r.data),{isDeleted:!0,updatedAt:fe(r.data.updatedAt)});return t?setTimeout((()=>{wa("subChannel",e)}),0):$e(["subChannel","get",e],o),ht("local.message-feed.deleted",{messageFeeds:[o]}),o},cd=e=>dt(be(),"onSubChannelFetched","local.message-feed.fetched",(t=>e(t.messageFeeds[0])));function ld(e,t){const n=[...e,...t];if(0===n.length)return[];const r=de(n[0]),o=new Map;return n.forEach((e=>o.set(e[r],e))),Array.from(o.values())}const ud=async e=>{const t=be();t.log("channel/querySubChannels",e);const n=Oa(e),{page:r={limit:10},channelId:o,includeDeleted:s}=n,i=Zi(n,["page","channelId","includeDeleted"]),a=(await t.http.get(`/api/v5/message-feeds/channel/${o}`,{params:Object.assign(Object.assign({},i),{isDeleted:pc(s),options:{token:J(r,"skiplimit")}})})).data,{paging:c}=a,l=Zi(a,["paging"]),u=await Ia(l),d=u.messageFeeds,h=t.cache&&Date.now();if(t.cache){Xi(u,{cachedAt:h});const e=["subChannel","query",Object.assign(Object.assign({channelId:o},i),{options:Object.assign({},r)})];Le(e,{subChannels:d.map(ce("subChannel")),paging:c})}ht("local.message-feed.fetched",u);const f=G(c.next);return{data:d,cachedAt:h,prevPage:G(c.previous),nextPage:f}};ud.locally=e=>{var t,n,r;be().log("channel/querySubChannels.locally",e);const o=null!==(t=Oa(e))&&void 0!==t?t:{},{page:s={limit:10},channelId:i}=o,a=Zi(o,["page","channelId"]),c=["subChannel","query",Object.assign(Object.assign({channelId:i},a),{options:Object.assign({},s)})],{data:l,cachedAt:u}=null!==(n=De(c))&&void 0!==n?n:{};if(!(null==l?void 0:l.subChannels.length))return;const d=l.subChannels.map((e=>De(["subChannel","get",e]))).filter(Boolean).map((({data:e})=>e)),h=G(null==l?void 0:l.paging.previous),f=G(null==l?void 0:l.paging.next);return d.length===(null===(r=null==l?void 0:l.subChannels)||void 0===r?void 0:r.length)?{data:d,cachedAt:u,prevPage:h,nextPage:f}:void 0};var dd=Object.freeze({__proto__:null,getSubChannelByIds:id,createSubChannel:async e=>{const t=be();t.log("user/createSubChannel",e);const n=await t.http.post("/api/v5/message-feeds",{channelId:e.channelId,name:e.displayName}),r=await Ia(n.data),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),ht("message-feed.created",n.data),{data:r.messageFeeds[0],cachedAt:o}},updateSubChannel:async(e,t)=>{const n=be();n.log("channel/updateSubChannel",e,t);const r=await n.http.put(`/api/v5/message-feeds/${encodeURIComponent(e)}`,{name:t.displayName}),o=await Ia(r.data),s=n.cache&&Date.now();return n.cache&&Xi(o,{cachedAt:s}),ht("message-feed.updated",r.data),{data:o.messageFeeds[0],cachedAt:s}},deleteSubChannel:ad,hardDeleteSubChannel:async e=>{be().log("channel/hardDeleteSubChannel",e);return await ad(e,!0)},softDeleteSubChannel:async e=>{be().log("channel/softDeleteSubChannel",e);return await ad(e,!1)},startReadingAPI:xa,stopReadingAPI:Ra,onSubChannelCreated:jc,onSubChannelUpdated:Fc,onSubChannelDeleted:Bc,getSubChannel:(e,t)=>rc(e,t,"subChannelId",Ta,[cd,Fc,Bc]),getSubChannels:(e,t,n)=>{const{log:r,cache:o}=be(),s=Date.now();r(`getSubChannels(tmpid: ${s}) > listen`),o||console.log(p);const{limit:i=h}=e,a=Zi(e,["limit"]),{policy:c=f}=null!=n?n:{};let l;const u=[],d=n=>{var r;let o=n.data;e.includeDeleted||(o=He(o,"isDeleted",!1)),o.sort(tt),t({onNextPage:m,data:o,hasNextPage:!!(null===(r=n.params)||void 0===r?void 0:r.page),loading:n.loading,error:n.error})},g=t=>n=>{e.channelId===n.channelId&&l&&function(e,t,n){const r=de(t),o=e.find((e=>e[r]===t[r]));return o?!nc(o,t):"onCreate"===n}(l.data,n,t)&&(l.data="onCreate"===t?[n,...l.data]:l.data.map((e=>e.subChannelId===n.subChannelId?n:e)),d(l))},m=()=>{var e;const t=l?l.data:[];if(t.length>0&&!(null==l?void 0:l.params.page))return;const n=re(ud,Object.assign(Object.assign({},a),{page:null!==(e=null==l?void 0:l.params.page)&&void 0!==e?e:{limit:i}}));se(n,(({data:e,error:n,loading:r,nextPage:o})=>{l={loading:r,error:n,params:{page:o},data:e?ld(t,e):t},d(l)}),oe(c,y))};return u.push(jc(g("onCreate")),Bc(g("onDelete")),cd(g("onFetch")),Fc(g("onUpdate"))),m(),()=>{r(`getSubChannels(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},markReadEngineOnLoginHandler:Na,startReading:async e=>{ja[e]=!0,0===Ma.length&&(Ua(),Da(e));try{return await Fa()}catch(t){return ja[e]=!1,!1}},stopReading:e=>(ja[e]=!1,Ma.forEach((e=>e())),Ma=[],Ra(e))});const hd=e=>{var t;return null!==(t=Object.keys(n).find((t=>e.needApprovalOnPostCreation===n[t].needApprovalOnPostCreation&&e.onlyAdminCanPost===n[t].onlyAdminCanPost)))&&void 0!==t?t:r},fd=e=>{const t=e.communities.map((e=>{var{needApprovalOnPostCreation:t,onlyAdminCanPost:n}=e,r=Zi(e,["needApprovalOnPostCreation","onlyAdminCanPost"]);return Object.assign({postSetting:hd({needApprovalOnPostCreation:t,onlyAdminCanPost:n})},r)})),n=ea(e.communityUsers);return Object.assign(Object.assign({},e),{communities:t,communityUsers:n})},pd=e=>{const{postSetting:t}=e,r=Zi(e,["postSetting"]);return Object.assign(Object.assign({},r),t?n[t]:void 0)},gd=async e=>{const t=be();t.log("community/getCommunities",e);const{data:n}=await t.http.get("/api/v3/communities/list",{params:{communityIds:e}}),r=fd(n),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:r.communities,cachedAt:o}};gd.locally=e=>{var t;const n=be();if(n.log("community/getCommunities.locally",e),!n.cache)return;const r=e.map((e=>De(["community","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const md=async e=>{const t=be();t.log("community/getCommunity",e);const{data:n}=await t.http.get(`/api/v3/communities/${e}`),r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communities:s}=r;return{data:s.find((t=>t.communityId===e)),cachedAt:o}};md.locally=e=>{const t=be();if(t.log("community/getCommunity.locally",e),!t.cache)return;const n=De(["community","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const yd=async e=>{const t=be();t.log("channel/getTopTrendingCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/top-trending",{params:{options:{limit:n}}}),o=fd(r),{communities:s}=o,i=t.cache&&Date.now();if(t.cache){Xi(o,{cachedAt:i});Le(["community","top-trending",{params:{options:{limit:n}}}],{communities:s.map(ce("community"))})}return{data:s,cachedAt:i}};yd.locally=e=>{var t,n;const r=be();if(r.log("community/getTopTrendingCommunities.locally",e),!r.cache)return;const{limit:o=5}=null!=e?e:{},s=["community","top-trending",{params:{options:{limit:o}}}],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{};if(!(null==i?void 0:i.communities.length))return;const c=i.communities.map((e=>De(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return c.length===(null===(n=null==i?void 0:i.communities)||void 0===n?void 0:n.length)?{data:c,cachedAt:a}:void 0};const vd=async e=>{const t=be();t.log("channel/getRecommendedCommunities",e);const{limit:n=5}=null!=e?e:{},{data:r}=await t.http.get("/api/v3/communities/recommended",{params:{options:{limit:n}}}),o=fd(r),{communities:s}=o,i=t.cache&&Date.now();if(t.cache){Xi(o,{cachedAt:i});Le(["community","recommended",{params:{options:{limit:n}}}],{communities:s.map(ce("community"))})}return{data:s,cachedAt:i}};vd.locally=e=>{var t,n;const r=be();if(r.log("community/getRecommendedCommunities.locally",e),!r.cache)return;const{limit:o=5}=null!=e?e:{},s=["community","recommended",{params:{options:{limit:o}}}],{data:i,cachedAt:a}=null!==(t=De(s))&&void 0!==t?t:{};if(!(null==i?void 0:i.communities.length))return;const c=i.communities.map((e=>De(["community","get",e]))).filter(Boolean).map((({data:e})=>e));return c.length===(null===(n=null==i?void 0:i.communities)||void 0===n?void 0:n.length)?{data:c,cachedAt:a}:void 0};const bd=(e,t)=>{const n=be();return dt(n,e,e,(e=>{const r=fd(e);if(n.cache){Xi(r);const e=De(["community","get",r.communities[0].communityId]);t(e.data)}else t(r.communities[0])}))},wd=e=>bd("community.created",e),Cd=e=>bd("community.updated",e),_d=e=>bd("community.deleted",e);function kd(e,t){return e.map((e=>{const n=t.some((t=>function(e,t){const{userId:n}=rt();return e.communityId===t.communityId&&t.userId===n}(e,t)&&"none"!==t.communityMembership));return Object.assign(Object.assign({},e),{isJoined:n})}))}function Sd(e,t,n){return!!e.permissions.some((e=>e===n))||t.users.find((t=>t.userId===e.userId)).permissions.some((e=>e===n))}function Ad(e,t){return"community.joined"===e||"community.left"===e?t.communityUsers[0]:"community.userRemoved"===e?t.communityUsers.filter((e=>"none"===e.communityMembership))[0]:"community.userBanned"===e?t.communityUsers.filter((e=>"banned"===e.communityMembership))[0]:"community.userUnbanned"===e?t.communityUsers.filter((e=>!Sd(e,t,"BAN_COMMUNITY_USER")))[0]:t.communityUsers.filter((e=>!Sd(e,t,"ADD_COMMUNITY_USER")))[0]}const Ed=(e,t)=>{const n=be();return dt(n,e,e,(r=>{const o=fd(r),{communities:s,communityUsers:i}=o,a=kd(s,i);if(o.communities=a,n.cache){Xi(o);const n=De(["community","get",o.communities[0].communityId]),r=De(["communityUsers","get",ce("communityUsers")(Ad(e,o))]);t(n.data,r.data)}else t(o.communities[0],Ad(e,o))}))},Id=e=>Ed("community.userAdded",e),Od=e=>Ed("community.userRemoved",e),Td=e=>Ed("community.userBanned",e),xd=e=>Ed("community.userChanged",e),Rd=e=>Ed("community.userUnbanned",e),Pd=e=>Ed("community.roleAdded",e),Md=e=>Ed("community.roleRemoved",e),jd=e=>Ed("community.joined",e),Fd=e=>Ed("community.left",e),Bd=async e=>{const t=be();t.log("channel/queryCommunities",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),s=null!=o?o:{},{displayName:i,membership:a,includeDeleted:c}=s,l=Zi(s,["displayName","membership","includeDeleted"]),{data:u}=await t.http.get("/api/v3/communities",{params:Object.assign(Object.assign({},l),{isDeleted:pc(c),keyword:i,filter:a,options:{token:J(r,"skiplimit")}})}),{paging:d}=u,h=Zi(u,["paging"]),f=fd(h),{communities:p}=f,g=t.cache&&Date.now();if(t.cache){Xi(f,{cachedAt:g});const e=["community","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{communities:p.map(ce("community")),paging:d})}const m=G(d.next);return{data:p,cachedAt:g,prevPage:G(d.previous),nextPage:m}};var Nd=Object.freeze({__proto__:null,addRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/addRoles",e,t,n);const{data:o}=await r.http.post(`/api/v4/communities/${e}/users/roles`,{communityId:e,roles:t,userIds:n}),s=ta(o,"communityUsers");r.cache&&Xi(s);const{communityUsers:i}=s;return!!i.find((n=>n.communityId===e&&t.some((e=>n.roles.includes(e)))))},removeRoles:async(e,t,n)=>{const r=be();r.log("community/moderation/removeRoles",e,t,n);const{data:o}=await r.http.delete(`/api/v4/communities/${e}/users/roles`,{data:{communityId:e,roles:t,userIds:n}}),s=ta(o,"communityUsers");r.cache&&Xi(s);const{communityUsers:i}=s;return!!i.find((n=>n.communityId===e&&!t.some((e=>n.roles.includes(e)))))},banMembers:async(e,t)=>{const n=be();n.log("community/banMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/ban`,{userIds:t}),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{communityUsers:i}=o;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:s}},unbanMembers:async(e,t)=>{const n=be();n.log("community/unbanMembers",{userIds:t,communityId:e});const{data:r}=await n.http.put(`/api/v3/communities/${e}/users/unban`,{userIds:t}),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{communityUsers:i}=o;return{data:i.filter((e=>t.includes(e.userId))),cachedAt:s}}});const Ud=async e=>{const t=be();t.log("community/queryCommunityMembers",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get(`/api/v3/communities/${o.communityId}/users`,{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i}=s,a=Zi(s,["paging"]),c=ta(a,"communityUsers"),{communityUsers:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:u});const e=["communityUsers","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{communityUsers:l.map((({communityId:e,userId:t})=>ce("communityUsers")({communityId:e,userId:t}))),paging:i})}return{data:l,cachedAt:u,nextPage:G(i.next),prevPage:G(i.previous)}};Ud.locally=e=>{var t,n;const r=be();if(r.log("community/queryCommunityMembers",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,i=Zi(o,["page"]),a=["communityUsers","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.communityUsers.length))return;const u=c.communityUsers.map((e=>De(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.communityUsers)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};var Dd=Object.freeze({__proto__:null,addMembers:async(e,t)=>{const n=be();n.log("community/moderation/addMembers",e,t);const{data:r}=await n.http.post(`/api/v3/communities/${e}/users`,{communityId:e,userIds:t});ht("community.userAdded",r);const o=ta(r,"communityUsers");n.cache&&Xi(o);const{communityUsers:s}=o;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},removeMembers:async(e,t)=>{const n=be();n.log("community/moderation/removeMembers",e,t);const{data:r}=await n.http.delete(`/api/v3/communities/${e}/users`,{data:{communityId:e,userIds:t}});ht("community.userRemoved",r);const o=ta(r,"communityUsers");n.cache&&Xi(o);const{communityUsers:s}=o;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getMembers:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getMembers(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["communityUsers","collection",{communityId:e.communityId}],g=t=>{let n=Ve(t,"roles",e.roles);e.membership&&(n=n.filter((({communityMembership:t})=>e.membership.includes(t)))),e.search&&(n=Ge(n,e.search));const r=e.sortBy?e.sortBy:"lastCreated";return n=n.sort("lastCreated"===r?et:Ze),n},m=(e,n=!1)=>{var r,o;const s=null!==(r=e.data.map((e=>De(["communityUsers","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];t({onNextPage:v,data:n?g(s):s,hasNextPage:!!(null===(o=e.params)||void 0===o?void 0:o.page),loading:e.loading,error:e.error})},y=t=>(t,n)=>{var r;if(e.communityId!==n.communityId)return;const o=null===(r=De(d))||void 0===r?void 0:r.data;if(!o)return;const s=ce("communityUsers")({communityId:e.communityId,userId:n.userId});o.data=[...new Set([s,...o.data])],Le(d,o),m(o,!0)},v=(e=!1)=>{var t,n,r;const o=null===(t=De(d))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Ud,Object.assign(Object.assign({},a),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:c}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("communityUsers"))])]),Le(d,o),m(o)}),oe(l))};return u.push(Fd(y()),jd(y()),Td(y()),Rd(y()),xd(y()),Pd(y()),Md(y())),v(!0),()=>{r(`getMembers(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}},onCommunityUserAdded:Id,onCommunityUserRemoved:Od,onCommunityUserBanned:Td,onCommunityUserChanged:xd,onCommunityUserUnbanned:Rd,onCommunityUserRoleAdded:Pd,onCommunityUserRoleRemoved:Md,onCommunityJoined:jd,onCommunityLeft:Fd}),Ld=Object.freeze({__proto__:null,Moderation:Nd,Membership:Dd,getCommunityByIds:gd,createCommunity:async e=>{const t=be();t.log("user/createCommunity",e);const{data:n}=await t.http.post("/api/v3/communities/",pd(e));ht("community.created",n);const r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communities:s}=r;return{data:s[0],cachedAt:o}},updateCommunity:async(e,t)=>{const n=be();n.log("community/updateCommunity",e,t);const{data:r}=await n.http.put(`/api/v3/communities/${e}`,pd(t));ht("community.updated",r);const o=fd(r),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s});const{communities:i}=o;return{data:i.find((t=>t.communityId===e)),cachedAt:s}},deleteCommunity:async e=>{const t=be();t.log("community/deleteCommunity",e),await t.http.delete(`/api/v3/communities/${e}`);const n=await md(e);return ht("community.deleted",{communities:[n.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]}),n.data},joinCommunity:async e=>{const t=be();t.log("community/joinCommunity",e);const{data:n}=await t.http.post(`/api/v3/communities/${e}/join`);ht("community.joined",n);const r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"===t.communityMembership))},leaveCommunity:async e=>{const t=be();t.log("community/leaveCommunity",e);const{data:n}=await t.http.delete(`/api/v3/communities/${e}/leave`);ht("community.left",n);const r=fd(n),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{communityUsers:s}=r;return!!s.find((t=>t.communityId===e&&"member"!==t.communityMembership))},getTopTrendingCommunities:yd,getRecommendedCommunities:vd,onCommunityCreated:wd,onCommunityUpdated:Cd,onCommunityDeleted:_d,observeCommunity:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeCommunity(tmpid: ${r}) > listen`);const o=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},s=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.communityId)===e&&o(t,n)},i=[];return i.push(Cd((e=>s({data:e,loading:!1,origin:"event"},"onUpdate"))),_d((e=>s({data:e,loading:!1,origin:"event"},"onDelete"))),jd((e=>s({data:e,loading:!1,origin:"event"},"onJoin"))),Fd((e=>s({data:e,loading:!1,origin:"event"},"onLeft"))),Id((e=>s({data:e,loading:!1,origin:"event"},"onUserAdded"))),Od((e=>s({data:e,loading:!1,origin:"event"},"onUserRemoved"))),Td((e=>s({data:e,loading:!1,origin:"event"},"onUserBanned"))),Rd((e=>s({data:e,loading:!1,origin:"event"},"onUserUnbanned")))),se(re(md,e),(e=>(e.data||e.error)&&o(e,"onFetch"))),()=>{n(`observeCommunity(tmpid: ${r}) > dispose`),i.forEach((e=>e()))}},getCommunities:(e,t,n)=>{const{log:r,cache:o,userId:s}=be();o||console.log(p);const i=Date.now();r(`getCommunities(tmpid: ${i}) > listen`);const{limit:a}=e,c=Zi(e,["limit"]),l=null!=a?a:h,{policy:u=f}=null!=n?n:{},d=[],g=["community","collection",{}],m=n=>{var r,o;let i=null!==(r=n.data.map((e=>De(["community","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];i=He(i,"displayName",e.displayName),e.includeDeleted||(i=He(i,"isDeleted",!1)),e.categoryId&&(i=i.filter((t=>{var n;return null===(n=t.categoryIds)||void 0===n?void 0:n.includes(e.categoryId)}))),e.tags&&(i=i.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),e.membership&&s&&(i=Qe(i,e.membership,s));const a=e.sortBy||"lastCreated";"lastCreated"!==a&&"firstCreated"!==a||(i=i.sort("lastCreated"===a?et:Ze)),"displayName"===a&&(i=i.map((e=>e.displayName?e:Object.assign(Object.assign({},e),{displayName:""}))).sort(Ye)),t({onNextPage:b,data:i,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},v=e=>e=>{var t;const n=null===(t=De(g))||void 0===t?void 0:t.data;n&&(n.data=[...new Set([e.communityId,...n.data])],Le(g,n),m(n))},b=(e=!1)=>{var t,n,r;const o=null===(t=De(g))||void 0===t?void 0:t.data,s=null!==(n=null==o?void 0:o.data)&&void 0!==n?n:[];if(!e&&s.length>0&&!(null==o?void 0:o.params.page))return;const i=re(Bd,Object.assign(Object.assign({},c),{page:null!==(r=e||null==o?void 0:o.params.page)&&void 0!==r?r:{limit:l}}));se(i,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:s};e&&(o.data=[...new Set([...s,...e.map(ce("community"))])]),Le(g,o),m(o)}),oe(u,y))};return d.push(wd(v()),_d(v()),Cd(v()),jd(v()),Fd(v()),xd(v())),b(!0),d.push((()=>ze(g))),()=>{r(`getCommunities(tmpid: ${i}) > dispose`),d.forEach((e=>e()))}},getCommunity:(e,t)=>rc(e,t,"communityId",md,[Cd,_d,jd,Fd,Td,Rd,xd])});const qd=async e=>{const t=be();t.log("category/getCategory",e);const{data:n}=await t.http.get(`/api/v3/community-categories/${encodeURIComponent(e)}`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{categories:o}=n;return{data:o.find((t=>t.categoryId===e)),cachedAt:r}};qd.locally=e=>{const t=be();if(t.log("category/getCategory.locally",e),!t.cache)return;const n=De(["category","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const $d=async e=>{const t=be();t.log("category/queryCategories",e);const n=null!=e?e:{},{page:r={limit:10},includeDeleted:o}=n,s=Zi(n,["page","includeDeleted"]),{data:i}=await t.http.get("/api/v3/community-categories",{params:Object.assign(Object.assign({},s),{isDeleted:pc(o),options:{token:J(r,"skiplimit")}})}),{paging:a}=i,c=Zi(i,["paging"]),{categories:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:u});const e=["category","query",Object.assign(Object.assign({},s),{options:Object.assign({},r)})];Le(e,{categories:l.map(ce("category")),paging:a})}const d=G(a.next);return{data:l,cachedAt:u,prevPage:G(a.previous),nextPage:d}};$d.locally=e=>{var t,n;const r=be();if(r.log("category/queryCategories.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s={limit:10}}=o,i=Zi(o,["page"]),a=["category","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.categories.length))return;const u=c.categories.map((e=>De(["category","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.categories)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};var zd=Object.freeze({__proto__:null,getCategory:qd,getCategories:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getCategories(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["category","collection",{}],g=(n=!1)=>{var r,o,s;const i=null===(r=De(d))||void 0===r?void 0:r.data,u=null!==(o=null==i?void 0:i.data)&&void 0!==o?o:[];if(!n&&u.length>0&&!(null==i?void 0:i.params.page))return;const h=re($d,Object.assign(Object.assign({},a),{page:null!==(s=n||null==i?void 0:i.params.page)&&void 0!==s?s:{limit:c}}));se(h,(({data:n,error:r,loading:o,nextPage:s})=>{const i={loading:o,error:r,params:{page:s},data:u};n&&(i.data=[...new Set([...u,...n.map(ce("category"))])]),Le(d,i),(n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["category","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];switch(e.includeDeleted||(s=He(s,"isDeleted",!1)),e.sortBy){case"firstCreated":s=s.sort(Ze);break;case"lastCreated":s=s.sort(et);break;default:s=s.sort(Xe)}t({onNextPage:g,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})})(i)}),oe(l))};return u.push((()=>{})),g(!0),()=>{r(`getCategories(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}});const Hd=async e=>{const t=be();t.log("feed/queryGlobalFeed",e);const n=null!=e?e:{},{useCustomRanking:r,page:o}=n,s=Zi(n,["useCustomRanking","page"]);r&&console.warn('The param "useCustomRanking" has been deprecated. To get custom ranking feed use FeedRepository.getCustomRankingGlobalFeed instead');const{data:i}=await t.http.get("/api/v4/me/global-feeds",{params:Object.assign(Object.assign({},s),{options:{token:J(o,"skiplimit")}})}),{paging:a}=i,c=Zi(i,["paging"]),l=ta(c,"communityUsers"),{posts:u}=l,d=t.cache&&Date.now();if(t.cache){Xi(l);const e=["globalFeed","query",Object.assign(Object.assign({},s),{options:Object.assign({},o)})];Le(e,{posts:u.map(ce("post")),paging:a})}const h=G(a.next);return{data:u,cachedAt:d,prevPage:G(a.previous),nextPage:h}};Hd.locally=e=>{var t,n;const r=be();if(r.log("post/queryGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,i=Zi(o,["page"]),a=["globalFeed","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const u=c.posts.map((e=>De(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};const Vd=async e=>{const t=be();t.log("feed/getCustomRankingGlobalFeed",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get("/api/v5/me/global-feeds",{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i}=s,a=Zi(s,["paging"]),c=ta(a,"communityUsers"),{posts:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c);const e=["customGlobalFeed","query",Object.assign(Object.assign({},o),{options:Object.assign({},r)})];Le(e,{posts:l.map(ce("post")),paging:i})}const d=G(i.next);return{data:l,cachedAt:u,prevPage:G(i.previous),nextPage:d}};Vd.locally=e=>{var t,n;const r=be();if(r.log("post/getCustomRankingGlobalFeed.locally",e),!r.cache)return;const o=null!=e?e:{},{page:s}=o,i=Zi(o,["page"]),a=["customGlobalFeed","query",Object.assign(Object.assign({},i),{options:Object.assign({},s)})],{data:c,cachedAt:l}=null!==(t=De(a))&&void 0!==t?t:{};if(!(null==c?void 0:c.posts.length))return;const u=c.posts.map((e=>De(["post","get",e]))).filter(Boolean).map((({data:e})=>e)),d=G(null==c?void 0:c.paging.previous),h=G(null==c?void 0:c.paging.next);return u.length===(null===(n=null==c?void 0:c.posts)||void 0===n?void 0:n.length)?{data:u,cachedAt:l,prevPage:d,nextPage:h}:void 0};var Wd=Object.freeze({__proto__:null,queryGlobalFeed:Hd,getCustomRankingGlobalFeed:Vd});const Kd=async e=>{const t=be();t.log("post/getPostByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/posts/list",{params:{postIds:n}})).data}catch(t){throw e.forEach((e=>{_(null==t?void 0:t.code)&&wa("post",e)})),t}const o=ta(r,"communityUsers"),s=t.cache&&Date.now();return t.cache&&Xi(o,{cachedAt:s}),{data:o.posts,cachedAt:s}};Kd.locally=e=>{var t;const n=be();if(n.log("post/getPostByIds.locally",e),!n.cache)return;const r=e.map((e=>De(["post","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const Qd=async(e,t=!1)=>{const n=be(),r=await Il(e);if(await n.http.delete(`/api/v4/posts/${encodeURIComponent(e)}`,{params:{postId:e,permanent:t}}),"community"===r.data.targetType){const e=await md(r.data.targetId);ht("community.updated",{communities:[e.data],categories:[],communityUsers:[],feeds:[],files:[],users:[]})}const o=Object.assign(Object.assign({},r.data),{isDeleted:!0});return ht("post.deleted",{posts:[o],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),t?setTimeout((()=>{wa("post",e)}),0):$e(["post","get",e],{isDeleted:!0}),o},Jd=async e=>{const t=be();t.log("post/queryPosts",e);const{page:n={limit:10},includeDeleted:r}=e,o=Zi(e,["page","includeDeleted"]),{dataTypes:s,matchingOnlyParentPost:i}=o,{data:a}=await t.http.get("/api/v4/posts",{params:Object.assign(Object.assign({},o),{isDeleted:pc(r),matchingOnlyParentPost:null!=i?i:!(null==s?void 0:s.length),options:{token:J(n,"afterbeforeraw")}})}),{paging:c}=a,l=Zi(a,["paging"]),u=ta(l,"communityUsers"),{posts:d}=l,h=t.cache&&Date.now();if(t.cache){Xi(u,{cachedAt:h});const e=["post","query",Object.assign(Object.assign({},o),{options:Object.assign({},n)})];Le(e,{posts:d.map(ce("post")),paging:c})}const f=Y(c.next);return{data:d,cachedAt:h,prevPage:Y(c.previous),nextPage:f}};var Gd=Object.freeze({__proto__:null,getPostByIds:Kd,createPost:async e=>{const t=be();t.log("post/createPost",e),e.dataType&&!["text","image","file","video"].includes(e.dataType)||delete e.dataType;const{data:n}=await t.http.post("/api/v4/posts",e);ht("post.created",n);const r=ta(n,"communityUsers"),o=t.cache&&Date.now();t.cache&&Xi(r,{cachedAt:o});const{posts:s}=r;return{data:s[0],cachedAt:o}},updatePost:async(e,t)=>{const n=be();n.log("user/updatePost",t),console.warn("Deprecation: updatePost has been renamed to editPost. Update post API will be deprecated soon.");const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s}),ht("post.updated",o);const{posts:i}=o;return{data:i.find((t=>t.postId===e)),cachedAt:s}},editPost:async(e,t)=>{const n=be();n.log("user/editPost",t);const{data:r}=await n.http.put(`/api/v4/posts/${encodeURIComponent(e)}`,t),o=ta(r,"communityUsers"),s=n.cache&&Date.now();n.cache&&Xi(o,{cachedAt:s}),ht("post.updated",o);const{posts:i}=o;return{data:i.find((t=>t.postId===e)),cachedAt:s}},deletePost:Qd,softDeletePost:async e=>{be().log("post/softDeletePost",e);return await Qd(e,!1)},hardDeletePost:async e=>{be().log("post/hardDeletePost",e);return await Qd(e,!0)},approvePost:async e=>{const t=be();t.log("post/approvePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/approve`);ht("post.approved",n),"community"===n.posts[0].targetType&&ht("community.updated",n);const r=ta(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:r.posts.find((t=>t.postId===e)),cachedAt:o}},declinePost:async e=>{const t=be();t.log("post/declinePost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/decline`);"community"===n.posts[0].targetType&&ht("community.updated",n),ht("post.declined",n);const r=ta(n,"communityUsers"),o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:n.posts.find((t=>t.postId===e)),cachedAt:o}},flagPost:async e=>{const t=be();t.log("post/flagPost",e);const{data:n}=await t.http.post(`/api/v3/posts/${encodeURIComponent(e)}/flag`);return t.cache&&Xi(ta(n,"communityUsers")),ht("post.flagged",n),!!n},unflagPost:async e=>{const t=be();t.log("post/unflagPost",e);const{data:n}=await t.http.delete(`/api/v3/posts/${encodeURIComponent(e)}/unflag`);return t.cache&&Xi(ta(n,"communityUsers")),ht("post.unflagged",n),!!n},isPostFlaggedByMe:async e=>{var t,n;const r=be();r.log("post/isPostFlaggedByMe",e);const{result:o,isFlagByMe:s}=null!==(t=await Di(r,"v3/post.isflagbyme",{postId:e}))&&void 0!==t?t:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n},onPostCreated:Ml,onPostUpdated:jl,onPostDeleted:Fl,onPostApproved:Bl,onPostDeclined:Nl,onPostFlagged:Ul,onPostUnflagged:Dl,onPostReactionAdded:Ll,onPostReactionRemoved:ql,observePosts:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observePosts(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(e.targetId===n.targetId&&e.targetType===n.targetType){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(Ml((e=>s(e,"onCreate"))),jl((e=>s(e,"onUpdate"))),Fl((e=>s(e,"onDelete"))),Bl((e=>s(e,"onApproved"))),Nl((e=>s(e,"onDeclined"))),Ul((e=>s(e,"onFlagged"))),Dl((e=>s(e,"onUnflagged"))),Ll((e=>s(e,"onReactionAdded"))),ql((e=>s(e,"onReactionRemoved")))),()=>{n(`observePosts(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observePost:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observePost(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.postId)===e&&s(t,n)},a=[];return a.push(jl((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Fl((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Bl((e=>i({data:e,loading:!1,origin:"event"},"onApproved"))),Nl((e=>i({data:e,loading:!1,origin:"event"},"onDeclined"))),Ul((e=>i({data:e,loading:!1,origin:"event"},"onFlagged"))),Dl((e=>i({data:e,loading:!1,origin:"event"},"onUnflagged"))),Ll((e=>i({data:e,loading:!1,origin:"event"},"onReactionAdded"))),ql((e=>i({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),se(re(Il,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observePosts(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getPost:(e,t)=>rc(e,t,"postId",Il,[Bl,Nl,Fl,Ul,Ll,ql,Dl,jl]),getPosts:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log(p);const s=Date.now();r(`getPosts(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["post","collection",{targetId:e.targetId,targetType:e.targetType}],g=n=>{var r,o,s;let i=null!==(r=n.data.map((e=>De(["post","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];const a=e.sortBy?e.sortBy:"lastCreated";i=i.sort("lastCreated"===a?et:Ze),e.includeDeleted||(i=He(i,"isDeleted",!1)),e.tags&&(i=i.filter((t=>{var n;return null===(n=t.tags)||void 0===n?void 0:n.some((t=>{var n;return null===(n=e.tags)||void 0===n?void 0:n.includes(t)}))}))),"community"===e.targetType&&e.feedType&&(i=Ke(i,e.feedType)),(null===(o=e.dataTypes)||void 0===o?void 0:o.length)&&(i=Je(i,e.dataTypes)),t({onNextPage:v,data:i,hasNextPage:!!(null===(s=n.params)||void 0===s?void 0:s.page),loading:n.loading,error:n.error})},m=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.targetId===n.targetId&&e.targetType===n.targetType&&o&&(o.data="onDeclined"===t?o.data.filter((e=>e!==n.postId)):[...new Set([n.postId,...o.data])],Le(d,o),g(o))},v=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(Jd,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,nextPage:r})=>{const o={loading:n,error:t,params:{page:r},data:i};e&&(o.data=[...new Set([...i,...e.map(ce("post"))])]),Le(d,o),g(o)}),oe(l,y))};return u.push(Ml(m("onCreate")),Bl(m("onApproved")),Nl(m("onDeclined")),Fl(m("onDelete")),jl(m("onUpdate")),Ul(m("onFlagged")),Dl(m("onUnflagged")),Ll(m("onReactionAdded")),ql(m("onReactionRemoved"))),v(!0),u.push((()=>ze(d))),()=>{r(`getPosts(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}});const Yd=async e=>{const t=be();t.log("comment/getCommentByIds",e);const n=e.map((e=>encodeURIComponent(e)));let r;try{r=(await t.http.get("/api/v3/comments/list",{params:{commentIds:n}})).data}catch(t){throw e.forEach((e=>{_(null==t?void 0:t.code)&&wa("comment",e)})),t}const o=t.cache&&Date.now();return t.cache&&Xi(r,{cachedAt:o}),{data:r.comments,cachedAt:o}};Yd.locally=e=>{var t;const n=be();if(n.log("comment/getCommentByIds.locally",e),!n.cache)return;const r=e.map((e=>De(["comment","get",e]))).filter(Boolean),o=r.map((({data:e})=>e)),s=null===(t=r.sort(((e,t)=>e.cachedAt<t.cachedAt?-1:1)))||void 0===t?void 0:t[0];return(null==r?void 0:r.length)<e.length?void 0:{data:o,cachedAt:s.cachedAt}};const Xd=async(e,t=!1)=>{const n=be(),r=await Ol(e);await n.http.delete(`/api/v4/comments/${encodeURIComponent(e)}`,{params:{commentId:e,permanent:t}});const o=Object.assign(Object.assign({},r.data),{isDeleted:!0}),s=await Il(r.data.referenceId);return ht("post.updated",{posts:[s.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),ht("comment.deleted",{comments:[o],commentChildren:[],files:[],users:[]}),t?at((()=>wa("comment",e))):$e(["comment","get",e],{isDeleted:!0}),o},Zd=async e=>{const t=be();t.log("comment/queryComments",e);const{page:n={limit:10},includeDeleted:r}=e,o=Zi(e,["page","includeDeleted"]),s={type:o.sortBy?"pagination":void 0,token:J(n,o.sortBy?"skiplimit":"afterbefore")},{data:i}=await t.http.get("/api/v3/comments",{params:Object.assign(Object.assign({},o),{isDeleted:pc(r),options:s})}),{paging:a}=i,c=Zi(i,["paging"]),{comments:l}=c,u=t.cache&&Date.now();if(t.cache){Xi(c,{cachedAt:u});const e=["comment","query",Object.assign(Object.assign({},o),{options:Object.assign({},n)})];Le(e,{comments:l.map(ce("comment")),paging:a})}const d=G(a.next);return{data:l,cachedAt:u,prevPage:G(a.previous),nextPage:d}};var eh=Object.freeze({__proto__:null,getCommentByIds:Yd,createComment:async e=>{const t=be();t.log("comment/createComment",e);const{data:n}=await t.http.post("/api/v3/comments",e),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const o=await Il(e.referenceId);ht("post.updated",{posts:[o.data],categories:[],comments:[],communities:[],communityUsers:[],feeds:[],files:[],postChildren:[],users:[]}),ht("comment.created",n);const{comments:s}=n;return{data:s[0],cachedAt:r}},updateComment:async(e,t)=>{const n=be();n.log("user/updateComment",t);const{data:r}=await n.http.put(`/api/v3/comments/${encodeURIComponent(e)}`,t),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o}),ht("comment.updated",r);const{comments:s}=r;return{data:s.find((t=>t.commentId===e)),cachedAt:o}},deleteComment:Xd,softDeleteComment:async e=>{be().log("comment/softDeleteComment",e);return Xd(e)},hardDeleteComment:async e=>{be().log("comment/hardDeleteComment",e);return Xd(e,!0)},flagComment:async e=>{const t=be();t.log("comment/flagComment",e);const{data:n}=await t.http.post(`/api/v3/comments/${encodeURIComponent(e)}/flag`);return t.cache&&Xi(n),ht("comment.flagged",n),!!n},unflagComment:async e=>{const t=be();t.log("comment/unflagComment",e);const{data:n}=await t.http.delete(`/api/v3/comments/${encodeURIComponent(e)}/unflag`);return t.cache&&Xi(n),ht("comment.unflagged",n),!!n},isCommentFlaggedByMe:async e=>{var t,n;const r=be();r.log("comment/isCommentFlaggedByMe",e);const{result:o,isFlagByMe:s}=null!==(t=await Di(r,"v3/comment.isflagbyme",{commentId:e}))&&void 0!==t?t:{};return null!==(n=null!=o?o:s)&&void 0!==n&&n},onCommentCreated:zl,onCommentUpdated:Hl,onCommentDeleted:Vl,onCommentFlagged:Wl,onCommentUnflagged:Kl,onCommentReactionAdded:Ql,onCommentReactionRemoved:Jl,observeComments:(e,t)=>{const{log:n}=be(),r=Date.now();n(`observeComments(tmpid: ${r}) > listen`);const o=[],s=(n,r)=>{var o,s;if(n.referenceId===e){if(t instanceof Function)return t(n);null===(o=t.onEvent)||void 0===o||o.call(t,r,n),null===(s=t[r])||void 0===s||s.call(t,n)}};return o.push(zl((e=>s(e,"onCreate"))),Hl((e=>s(e,"onUpdate"))),Vl((e=>s(e,"onDelete"))),Wl((e=>s(e,"onFlagged"))),Kl((e=>s(e,"onUnflagged"))),Ql((e=>s(e,"onReactionAdded"))),Jl((e=>s(e,"onReactionRemoved")))),()=>{n(`observeComments(tmpid: ${r}) > dispose`),o.forEach((e=>e()))}},observeComment:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observeComment(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.commentId)===e&&s(t,n)},a=[];return a.push(Hl((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),Vl((e=>i({data:e,loading:!1,origin:"event"},"onDelete"))),Wl((e=>i({data:e,loading:!1,origin:"event"},"onFlagged"))),Kl((e=>i({data:e,loading:!1,origin:"event"},"onUnflagged"))),Ql((e=>i({data:e,loading:!1,origin:"event"},"onReactionAdded"))),Jl((e=>i({data:e,loading:!1,origin:"event"},"onReactionRemoved")))),se(re(Ol,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observeComment(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}},getComment:(e,t)=>rc(e,t,"commentId",Ol,[Vl,Wl,Ql,Jl,Kl,Hl]),getComments:(e,t,n)=>{const{log:r,cache:o}=be();o||console.log("For using Live Collection feature you need to enable Cache!");const s=Date.now();r(`getComments(tmpid: ${s}) > listen`);const{limit:i}=e,a=Zi(e,["limit"]),c=null!=i?i:h,{policy:l=f}=null!=n?n:{},u=[],d=["comment","collection",{referenceId:e.referenceType,referenceType:e.referenceId}],p=n=>{var r,o;let s=null!==(r=n.data.map((e=>De(["comment","get",e]))).filter(Boolean).map((({data:e})=>e)))&&void 0!==r?r:[];e.includeDeleted||(s=He(s,"isDeleted",!1));const i=e.sortBy?e.sortBy:"lastCreated";s=s.sort("lastCreated"===i?et:Ze),t({onNextPage:m,data:s,hasNextPage:!!(null===(o=n.params)||void 0===o?void 0:o.page),loading:n.loading,error:n.error})},g=t=>n=>{var r;const o=null===(r=De(d))||void 0===r?void 0:r.data;e.referenceId===n.referenceId&&e.referenceType===n.referenceType&&o&&("onCreate"===t?o.data=[...new Set([n.commentId,...o.data])]:"onDelete"===t&&(o.data=o.data.filter((e=>e!==n.commentId))),Le(d,o),p(o))},m=(e=!1)=>{var t,n,r,o;const s=null===(t=De(d))||void 0===t?void 0:t.data,i=null!==(n=null==s?void 0:s.data)&&void 0!==n?n:[];if(!e&&i.length>0&&!(null===(r=null==s?void 0:s.params)||void 0===r?void 0:r.page))return;const u=re(Zd,Object.assign(Object.assign({},a),{page:null!==(o=e||null==s?void 0:s.params.page)&&void 0!==o?o:{limit:c}}));se(u,(({data:e,error:t,loading:n,prevPage:r,nextPage:o})=>{const s={loading:n,error:t,params:{page:a.sortBy?o:r},data:i};e&&(s.data=[...new Set([...i,...e.map(ce("comment"))])]),Le(d,s),p(s)}),oe(l,y))};return u.push(zl(g("onCreate")),Hl(g("onUpdate")),Vl(g("onDelete")),Wl(g("onFlagged")),Kl(g("onUnflagged")),Ql(g("onReactionAdded")),Jl(g("onReactionRemoved"))),m(!0),u.push((()=>ze(d))),()=>{r(`getComments(tmpid: ${s}) > dispose`),u.forEach((e=>e()))}}});const th=async e=>{const t=be();t.log("stream/getStream",e);const{data:n}=await t.http.get(`/api/v3/video-streaming/${e}`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}};th.locally=e=>{const t=be();if(t.log("stream/getStream",e),!t.cache)return;const n=De(["stream","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const nh=async e=>{const t=be();t.log("stream/getStreams",e);const n=null!=e?e:{},{page:r}=n,o=Zi(n,["page"]),{data:s}=await t.http.get("/api/v3/video-streaming",{params:Object.assign(Object.assign({},o),{options:{token:J(r,"skiplimit")}})}),{paging:i,results:a}=s,{videoStreamings:c}=a,l=t.cache&&Date.now();t.cache&&Xi(a,{cachedAt:l});const u=G(i.next);return{data:c,cachedAt:l,prevPage:G(i.previous),nextPage:u}};nh.locally=e=>{be().log("stream/getStreams.locally",e)};var rh=Object.freeze({__proto__:null,getStream:th,getStreams:nh,createStream:async e=>{const t=be();t.log("stream/createStream",e);const{data:n}=await t.http.post("/api/v3/video-streaming",e),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o[0],cachedAt:r}},updateStream:async(e,t)=>{const n=be();n.log("stream/updateStream",e,t);const{data:r}=await n.http.put(`/api/v3/video-streaming/${e}`,t),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{videoStreamings:s}=r;return{data:s.find((t=>t.streamId===e)),cachedAt:o}},deleteStream:async e=>{const t=be();t.log("stream/deleteStream",e);const n=await th(e),{data:r}=await t.http.delete(`/api/v3/video-streaming/${e}`),{success:o}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return $e(["stream","get",e],s),o},disposeStream:async e=>{const t=be();t.log("stream/disposeStream",e);const{data:n}=await t.http.delete(`/api/v3/video-streaming/${e}/streaming-url`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{videoStreamings:o}=n;return{data:o.find((t=>t.streamId===e)),cachedAt:r}},onStreamStarted:e=>{const t=be();return dt(t,"stream/onStreamStarted","video-streaming.didStart",(t=>{Xi(t),e(t.videoStreamings[0])}))},onStreamStopped:e=>{const t=be();return dt(t,"stream/onStreamStarted","video-streaming.didStop",(t=>{Xi(t),e(t.videoStreamings[0])}))},onStreamRecorded:e=>{const t=be();return dt(t,"stream/onStreamRecorded","video-streaming.didRecord",(t=>{Xi(t),e(t.videoStreamings[0])}))}});const oh=async e=>{const t=be();t.log("poll/getPoll",e);const{data:n}=await t.http.get(`/api/v3/polls/${e}`),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}};oh.locally=e=>{const t=be();if(t.log("poll/getPoll",e),!t.cache)return;const n=De(["poll","get",e]);return n?{data:n.data,cachedAt:n.cachedAt}:void 0};const sh=e=>{const t=be();return dt(t,"poll/onPollUpdated","poll.updated",(n=>{t.cache&&Xi(n),e(n.polls[0])}))},ih=e=>{const t=be();return dt(t,"poll/onPollDeleted","poll.deleted",(n=>{t.cache&&Xi(n),e(n.polls[0])}))};var ah=Object.freeze({__proto__:null,getPoll:oh,createPoll:async e=>{const t=be();t.log("post/createPoll",e);const{data:n}=await t.http.post("/api/v3/polls",e),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r});const{polls:o}=n;return{data:o[0],cachedAt:r}},closePoll:async e=>{const t=be();t.log("user/closePoll",e);const{data:n}=await t.http.put(`/api/v3/polls/${encodeURIComponent(e)}`,{status:"closed"}),r=t.cache&&Date.now();t.cache&&Xi(n,{cachedAt:r}),ht("poll.updated",n);const{polls:o}=n;return{data:o.find((t=>t.pollId===e)),cachedAt:r}},deletePoll:async e=>{const t=be();t.log("poll/deletePoll",e);const n=await oh(e),{data:r}=await t.http.delete(`/api/v3/polls/${e}`),{success:o}=r,s=Object.assign(Object.assign({},n.data),{isDeleted:!0});return $e(["poll","get",e],s),ht("poll.deleted",{polls:[s],users:[]}),o},votePoll:async(e,t)=>{const n=be();n.log("user/votePoll",e);const{data:r}=await n.http.post(`/api/v3/polls/${encodeURIComponent(e)}/votes`,{pollId:e,answerIds:t}),o=n.cache&&Date.now();n.cache&&Xi(r,{cachedAt:o});const{polls:s}=r;return ht("poll.updated",r),{data:s.find((t=>t.pollId===e)),cachedAt:o}},onPollUpdated:sh,onPollDeleted:ih,observePoll:(e,t,n="cache_then_server")=>{const{log:r}=be(),o=Date.now();r(`observePoll(tmpid: ${o}) > listen`);const s=(e,n)=>{var r,o;if(t instanceof Function)return t(e);"onFetch"!==n&&(null===(r=t.onEvent)||void 0===r||r.call(t,n,e)),null===(o=t[n])||void 0===o||o.call(t,e)},i=(t,n)=>{var r;(null===(r=t.data)||void 0===r?void 0:r.pollId)===e&&s(t,n)},a=[];return a.push(sh((e=>i({data:e,loading:!1,origin:"event"},"onUpdate"))),ih((e=>i({data:e,loading:!1,origin:"event"},"onDelete")))),se(re(oh,e),(e=>(e.data||e.error)&&s(e,"onFetch")),oe(n)),()=>{r(`observePoll(tmpid: ${o}) > dispose`),a.forEach((e=>e()))}}});return e.API_REGIONS=Bt,e.CategoryRepository=zd,e.ChannelRepository=Mc,e.Client=Qc,e.CommentRepository=eh,e.CommunityPostSettingMaps=n,e.CommunityPostSettings=t,e.CommunityRepository=Ld,e.ContentFeedType=o,e.DefaultCommunityPostSetting=r,e.FeedRepository=Wd,e.FileRepository=_l,e.FileType=s,e.MessageContentType=l,e.MessageRepository=sd,e.PollRepository=ah,e.PostContentType=u,e.PostRepository=Gd,e.ReactionRepository=Zl,e.StreamRepository=rh,e.SubChannelRepository=dd,e.UserRepository=wl,e.VERSION=d,e.VideoResolution=i,e.VideoSize=c,e.VideoTranscodingStatus=a,e.backupCache=async(e="amitySdk",t=(e=>e.offline))=>{const{log:n,cache:r,userId:o}=be();if(!r)return!1;n("cache/api/backupCache",{storageKey:e});const s=Object.fromEntries(Object.entries(r.data).filter((([e,n])=>t(n))));return!!Object.keys(s).length&&(await Ne.setItem(`${e}#${o}`,JSON.stringify(s)),!0)},e.createQuery=re,e.createReport=async(e,t)=>{const n=be();n.log("report/createReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.post((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=eu[e];return`/api/v3/${n}/${encodeURIComponent(t)}/flag`})());if(n.cache)if("message"===e){const e=await mc(r);Xi(e)}else Xi("post"===e?ta(r,"communityUsers"):r);return ht(`${e}.flagged`,r),!!r},e.createUserToken=async(e,t,n)=>{const r=Ki(),o=Qi(),s=kr(Ut("http",t)),{data:i}=await s.post("/api/v4/sessions",Object.assign(Object.assign({},n),{deviceId:r,deviceInfo:Object.assign(Object.assign({},o),{model:"token management API on TS-SDK"})}),{headers:{"X-API-Key":e}});return{accessToken:i.accessToken}},e.deleteReport=async(e,t)=>{const n=be();n.log("report/deleteReport",{referenceType:e,referenceId:t});const{data:r}=await n.http.delete((()=>{if("user"===e)return`/api/v4/me/flags/${encodeURIComponent(t)}`;if("message"===e)return`/api/v5/messages/${encodeURIComponent(t)}/flags`;const{domainName:n}=eu[e];return`/api/v3/${n}/${encodeURIComponent(t)}/unflag`})());if(n.cache)if("message"===e){const e=await mc(r);Xi(e)}else Xi("post"===e?ta(r,"communityUsers"):r);return ht(`${e}.unflagged`,r),!!r},e.disableCache=()=>{const e=be();e.cache&&(e.log("cache/api/disableCache"),delete e.cache)},e.dropFromCache=ze,e.enableCache=(e={},t)=>{const n=be();n.cache||(n.log("cache/api/enableCache"),n.cache={data:e,persistIf:t})},e.filterByChannelMembership=We,e.filterByCommunityMembership=Qe,e.filterByFeedType=Ke,e.filterByPostDataTypes=Je,e.filterByPropEquality=He,e.filterByPropInclusion=(e,t,n)=>void 0!==n?e.filter((e=>n.includes(e[t]))):e,e.filterByPropIntersection=Ve,e.filterBySearchTerm=Ge,e.getChannelMarkers=ua,e.getChannelTopic=e=>`${e.path}/#`,e.getCommentTopic=({path:e})=>e,e.getCommunityTopic=({path:t},n=e.SubscriptionLevels.COMMUNITY)=>yt(t,n),e.getMarkedMessageTopic=wt,e.getMessageMarkers=Ca,e.getMessageTopic=e=>e.path,e.getMyFollowersTopic=()=>{const e=rt();return`${vt(e)}/membership/${e._id}/+/+`},e.getMyFollowingsTopic=()=>{const e=rt();return`${vt(e)}/membership/+/${e._id}/+`},e.getNetworkTopic=Ct,e.getPostTopic=({path:t},n=e.SubscriptionLevels.POST)=>"comment"===n?`${t}/comment/+`:t,e.getRole=Sl,e.getSmartFeedChannelTopic=_t,e.getSmartFeedMessageTopic=St,e.getSmartFeedSubChannelTopic=kt,e.getSubChannelMarkers=_a,e.getSubChannelTopic=e=>`${e.path}/#`,e.getUserMarker=ka,e.getUserTopic=bt,e.isAfterBefore=W,e.isAfterBeforeRaw=K,e.isCachable=te,e.isFetcher=X,e.isFresh=ne,e.isLocal=e=>te(e)&&-1===(null==e?void 0:e.cachedAt),e.isMutator=Z,e.isOffline=ee,e.isPaged=Q,e.isReportedByMe=async(e,t)=>{var n,r;const o=be();o.log("report/isReportedByMe",{referenceType:e,referenceId:t});const{eventName:s,primaryKey:i}=eu[e];if("message"===e){const{data:e}=await o.http.get(`/api/v5/messages/${encodeURIComponent(t)}/flags`);return e.result}const{result:a,isFlagByMe:c}=null!==(n=await Di(o,s,{[i]:t}))&&void 0!==n?n:{};return null!==(r=null!=a?a:c)&&void 0!==r&&r},e.isSkip=V,e.mergeInCache=qe,e.onChannelMarkerFetched=e=>{const t=be();return dt(t,"channelMarker/onChannelMarkerFetched","local.channelMarker.fetched",(t=>{e(t.userEntityMarkers[0])}))},e.onFeedMarkerFetched=e=>{const t=be();return dt(t,"feedMarker/onFeedMarkerFetched","local.feedMarker.fetched",(t=>{e(t.feedMarkers[0])}))},e.onFeedMarkerUpdated=ec,e.onMessageMarked=e=>{const t=be();return dt(t,"messageMarker/onMessageMarked","marker.marked-message",(t=>{e(t.contentMarkers[0])}))},e.onMessageMarkerFetched=e=>{const t=be();return dt(t,"messageMarker/onMessageMarkerFetched","local.messageMarker.fetched",(t=>{e(t.contentMarkers[0])}))},e.onSubChannelMarkerFetched=e=>{const t=be();return dt(t,"subChannelMarker/onSubChannelMarkerFetched","local.subChannelMarker.fetched",(t=>{e(t.userFeedMarkers[0])}))},e.onSubChannelMarkerUpdated=e=>{const t=be();return dt(t,"subChannelMarker/onSubChannelMarkerUpdated","local.subChannelMarker.updated",(t=>{e(t.userFeedMarkers[0])}))},e.onUserMarkerFetched=tc,e.pullFromCache=De,e.pushToCache=Le,e.queryCache=Ue,e.queryOptions=oe,e.queryRoles=kl,e.restoreCache=async(e="amitySdk")=>{var t;const n=be();if(!n.cache)return!1;n.log("cache/api/restoreCache",{storageKey:e});const r=null!==(t=await Ne.getItem(`${e}#${n.userId}`))&&void 0!==t?t:"{}";let o={};try{o=JSON.parse(r)}catch(e){}return n.cache.data=Object.assign(Object.assign({},o),n.cache.data),!0},e.runQuery=se,e.sortByChannelSegment=({channelSegment:e},{channelSegment:t})=>e-t,e.sortByDisplayName=Ye,e.sortByFirstCreated=Ze,e.sortByLastActivity=tt,e.sortByLastCreated=et,e.sortByName=Xe,e.sortBySegmentNumber=({segmentNumber:e},{segmentNumber:t})=>e-t,e.subscribeTopic=At,e.toPage=G,e.toPageRaw=Y,e.toToken=J,e.upsertInCache=$e,e.wipeCache=async(e="amitySdk")=>{const{log:t,cache:n,userId:r}=be();return!!n&&(t("cache/api/wipeCache",{storageKey:e}),n.data={},await Ne.setItem(`${e}#${r}`,"{}"),!0)},Object.defineProperty(e,"__esModule",{value:!0}),e}({});