@twilio/conversations 3.0.1-rc.1 → 3.0.1-rc.103
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/builds/browser.js +9543 -4302
- package/builds/browser.js.map +1 -1
- package/builds/lib.d.ts +256 -61
- package/builds/lib.js +9543 -4302
- package/builds/lib.js.map +1 -1
- package/builds/twilio-conversations.js +44686 -27540
- package/builds/twilio-conversations.min.js +1 -200
- package/dist/channel-metadata-client.js +1 -1
- package/dist/channel-metadata-client.js.map +1 -1
- package/dist/client.js +153 -43
- package/dist/client.js.map +1 -1
- package/dist/command-executor.js +31 -50
- package/dist/command-executor.js.map +1 -1
- package/dist/configuration.js +8 -4
- package/dist/configuration.js.map +1 -1
- package/dist/content-template.js +1 -1
- package/dist/content-template.js.map +1 -1
- package/dist/conversation.js +12 -46
- package/dist/conversation.js.map +1 -1
- package/dist/data/conversations.js +2 -18
- package/dist/data/conversations.js.map +1 -1
- package/dist/data/messages.js +13 -3
- package/dist/data/messages.js.map +1 -1
- package/dist/data/participants.js +2 -4
- package/dist/data/participants.js.map +1 -1
- package/dist/data/users.js +2 -2
- package/dist/data/users.js.map +1 -1
- package/dist/index.js +5 -6
- package/dist/index.js.map +1 -1
- package/dist/media.js.map +1 -1
- package/dist/message-builder.js.map +1 -1
- package/dist/message-recipients-client.js +237 -0
- package/dist/message-recipients-client.js.map +1 -0
- package/dist/message.js +57 -0
- package/dist/message.js.map +1 -1
- package/dist/node_modules/quick-lru/index.js.map +1 -1
- package/dist/node_modules/tslib/tslib.es6.js.map +1 -1
- package/dist/packages/conversations/package.json.js +1 -1
- package/dist/participant.js +34 -34
- package/dist/participant.js.map +1 -1
- package/dist/push-notification.js.map +1 -1
- package/dist/rest-paginator.js +11 -11
- package/dist/rest-paginator.js.map +1 -1
- package/dist/services/network.js +11 -101
- package/dist/services/network.js.map +1 -1
- package/dist/services/typing-indicator.js +5 -13
- package/dist/services/typing-indicator.js.map +1 -1
- package/dist/unsent-message.js.map +1 -1
- package/dist/user.js.map +1 -1
- package/dist/util/index.js.map +1 -1
- package/docs/assets/css/main.css +2660 -0
- package/docs/assets/images/icons.png +0 -0
- package/docs/assets/images/icons@2x.png +0 -0
- package/docs/assets/images/widgets.png +0 -0
- package/docs/assets/images/widgets@2x.png +0 -0
- package/docs/assets/js/main.js +248 -0
- package/docs/assets/js/search.js +1 -0
- package/docs/classes/AggregatedDeliveryReceipt.html +3182 -144
- package/docs/classes/CancellablePromise.html +3209 -224
- package/docs/classes/ChannelMetadata.html +3049 -66
- package/docs/classes/Client.html +4276 -701
- package/docs/classes/ContentTemplate.html +3115 -96
- package/docs/classes/ContentTemplateVariable.html +3114 -88
- package/docs/classes/Conversation.html +4380 -768
- package/docs/classes/DetailedDeliveryReceipt.html +3162 -116
- package/docs/classes/EmailRecipientDescriptor.html +3098 -0
- package/docs/classes/Media.html +3165 -119
- package/docs/classes/Message.html +3824 -417
- package/docs/classes/MessageBuilder.html +3315 -208
- package/docs/classes/Participant.html +3442 -258
- package/docs/classes/PushNotification.html +3129 -101
- package/docs/classes/RestPaginator.html +3158 -120
- package/docs/classes/UnknownRecipientDescriptor.html +3067 -0
- package/docs/classes/UnsentMessage.html +3040 -63
- package/docs/classes/User.html +3347 -209
- package/docs/index.html +4366 -146
- package/docs/interfaces/ClientOptions.html +3065 -66
- package/docs/interfaces/ConversationBindings.html +3000 -109
- package/docs/interfaces/ConversationEmailBinding.html +3000 -109
- package/docs/interfaces/ConversationLimits.html +3097 -87
- package/docs/interfaces/ConversationState.html +3049 -66
- package/docs/interfaces/ConversationUpdatedEventArgs.html +3000 -109
- package/docs/interfaces/CreateConversationOptions.html +3065 -73
- package/docs/interfaces/LastMessage.html +3049 -66
- package/docs/interfaces/Paginator.html +3139 -110
- package/docs/interfaces/ParticipantBindings.html +3000 -109
- package/docs/interfaces/ParticipantEmailBinding.html +3000 -109
- package/docs/interfaces/PushNotificationData.html +3113 -94
- package/docs/interfaces/SendEmailOptions.html +3033 -59
- package/docs/interfaces/SendMediaOptions.html +3067 -75
- package/docs/modules.html +4373 -180
- package/package.json +13 -14
- package/docs/.nojekyll +0 -1
- package/docs/assets/highlight.css +0 -113
- package/docs/assets/main.js +0 -58
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1279
- package/docs/classes/CancellationError.html +0 -112
- package/docs/interfaces/ParticipantBindingOptions.html +0 -110
- package/docs/types/ChannelType.html +0 -106
- package/docs/types/ConnectionState.html +0 -115
- package/docs/types/ContentData.html +0 -106
- package/docs/types/ContentDataAction.html +0 -107
- package/docs/types/ContentDataActionOther.html +0 -121
- package/docs/types/ContentDataActionPhone.html +0 -128
- package/docs/types/ContentDataActionReply.html +0 -133
- package/docs/types/ContentDataActionUrl.html +0 -128
- package/docs/types/ContentDataCallToAction.html +0 -131
- package/docs/types/ContentDataCard.html +0 -137
- package/docs/types/ContentDataListItem.html +0 -121
- package/docs/types/ContentDataListPicker.html +0 -134
- package/docs/types/ContentDataLocation.html +0 -134
- package/docs/types/ContentDataMedia.html +0 -129
- package/docs/types/ContentDataOther.html +0 -121
- package/docs/types/ContentDataQuickReply.html +0 -131
- package/docs/types/ContentDataReply.html +0 -119
- package/docs/types/ContentDataText.html +0 -125
- package/docs/types/ConversationStatus.html +0 -107
- package/docs/types/ConversationUpdateReason.html +0 -106
- package/docs/types/DeliveryAmount.html +0 -106
- package/docs/types/DeliveryStatus.html +0 -106
- package/docs/types/JSONArray.html +0 -106
- package/docs/types/JSONObject.html +0 -111
- package/docs/types/JSONValue.html +0 -106
- package/docs/types/LogLevel.html +0 -106
- package/docs/types/MediaCategory.html +0 -106
- package/docs/types/MessageType.html +0 -106
- package/docs/types/MessageUpdateReason.html +0 -106
- package/docs/types/NotificationLevel.html +0 -109
- package/docs/types/NotificationsChannelType.html +0 -110
- package/docs/types/ParticipantEmailLevel.html +0 -108
- package/docs/types/ParticipantType.html +0 -107
- package/docs/types/ParticipantUpdateReason.html +0 -106
- package/docs/types/PushNotificationType.html +0 -106
- package/docs/types/State.html +0 -110
- package/docs/types/UserUpdateReason.html +0 -106
@@ -126,203 +126,4 @@ This software includes platform.js under the following license.
|
|
126
126
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
127
127
|
|
128
128
|
*/
|
129
|
-
this.Twilio=this.Twilio||{},this.Twilio.Conversations=function(e){"use strict";var t=void 0!==t?t:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function n(e,t,n,i){var r,s=arguments.length,a=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,n,a):r(t,n))||a);return s>3&&a&&Object.defineProperty(t,n,a),a}function i(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{};function s(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})})),t}var a,o,c,u={exports:{}};function l(e,t){return[`${(new Date).toISOString()} Conversations ${e}:`].concat(Array.from(t))}o=r,c=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"];function r(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function a(t,n){for(var r=0;r<i.length;r++){var s=i[r];this[s]=r<t?e:this.methodFactory(s,t,n)}this.log=this.debug}function o(e,n,i){return function(){typeof console!==t&&(a.call(this,n,i),this[e].apply(this,arguments))}}function c(i,a,c){return function(i){return"debug"===i&&(i="log"),typeof console!==t&&("trace"===i&&n?s:void 0!==console[i]?r(console,i):void 0!==console.log?r(console,"log"):e)}(i)||o.apply(this,arguments)}function u(e,n,r){var s,o=this;n=null==n?"WARN":n;var u="loglevel";function l(){var e;if(typeof window!==t&&u){try{e=window.localStorage[u]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,i=n.indexOf(encodeURIComponent(u)+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i))[1])}catch(e){}return void 0===o.levels[e]&&(e=void 0),e}}"string"==typeof e?u+=":"+e:"symbol"==typeof e&&(u=void 0),o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=r||c,o.getLevel=function(){return s},o.setLevel=function(n,r){if("string"==typeof n&&void 0!==o.levels[n.toUpperCase()]&&(n=o.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=o.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(s=n,!1!==r&&function(e){var n=(i[e]||"silent").toUpperCase();if(typeof window!==t&&u){try{return void(window.localStorage[u]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"="+n+";"}catch(e){}}}(n),a.call(o,n,e),typeof console===t&&n<o.levels.SILENT)return"No console available for logging"},o.setDefaultLevel=function(e){n=e,l()||o.setLevel(e,!1)},o.resetLevel=function(){o.setLevel(n,!1),function(){if(typeof window!==t&&u){try{return void window.localStorage.removeItem(u)}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)};var d=l();null==d&&(d=n),o.setLevel(d,!1)}var l=new u,d={};l.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=d[e];return t||(t=d[e]=new u(e,l.getLevel(),l.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return l.noConflict=function(){return typeof window!==t&&window.log===l&&(window.log=h),l},l.getLoggers=function(){return d},l.default=l,l},(a=u).exports?a.exports=c():o.log=c();const d=u.exports.getLogger("twilio-conversations");class h{prefix="";constructor(e){this.prefix=null!=e&&e.length>0?e+" ":""}static scope(e){return new h(e)}setLevel(e){d.setLevel(e)}static setLevel(e){d.setLevel(e)}trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.trace.apply(null,l(this.prefix+"T",t))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.debug.apply(null,l(this.prefix+"D",t))}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.info.apply(null,l(this.prefix+"I",t))}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.warn.apply(null,l(this.prefix+"W",t))}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.error.apply(null,l(this.prefix+"E",t))}static trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.trace.apply(null,l("T",t))}static debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.debug.apply(null,l("D",t))}static info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.info.apply(null,l("I",t))}static warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.warn.apply(null,l("W",t))}static error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];d.error.apply(null,l("E",t))}}var p,f,m={};Object.defineProperty(m,"__esModule",{value:!0});var g="\\d+(?:[\\.,]\\d+)?",y="P(?:"+("("+g+"W)")+"|"+("("+g+"Y)?("+g+"M)?("+g+"D)?")+"(?:"+("T("+g+"H)?("+g+"M)?("+g+"S)?")+")?)",v=["weeks","years","months","days","hours","minutes","seconds"],b=m.pattern=new RegExp(y),_=f=m.parse=function(e){return e.match(b).slice(1).reduce((function(e,t,n){return e[v[n]]=parseFloat(t)||0,e}),{})},w=m.end=function(e,t){var n=t?t.getTime():Date.now(),i=new Date(n);return i.setFullYear(i.getFullYear()+e.years),i.setMonth(i.getMonth()+e.months),i.setDate(i.getDate()+e.days),i.setHours(i.getHours()+e.hours),i.setMinutes(i.getMinutes()+e.minutes),i.setMilliseconds(i.getMilliseconds()+1e3*e.seconds),i.setDate(i.getDate()+7*e.weeks),i},x=p=m.toSeconds=function(e,t){var n=t?t.getTime():Date.now(),i=new Date(n);return(w(e,i).getTime()-i.getTime())/1e3};m.default={end:w,toSeconds:x,pattern:b,parse:_};const S="PT5S",k="PT5S";class E{links;limits;productId;typingIndicatorTimeoutOverride;typingIndicatorTimeoutDefault=5e3;backoffConfiguration;retryWhenThrottled;consumptionReportInterval;userInfosToSubscribe;httpCacheInterval;reachabilityEnabled;userIdentity;userInfo;myConversations;channelMetadataCacheCapacity;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;const i=e.Chat||e.IPMessaging||e||{};this.productId=i.productId,this.links={myConversations:t.links.my_conversations,conversations:t.links.conversations,users:t.links.users,currentUser:t.links.current_user,typing:t.links.typing,mediaService:t.links.media_service,mediaSetService:t.links.media_set_service,messagesReceipts:t.links.messages_receipts},this.limits={mediaAttachmentsCountLimit:t.options.media_attachments_count_limit,mediaAttachmentSizeLimitInMb:t.options.media_attachment_size_limit_in_mb,mediaAttachmentsTotalSizeLimitInMb:t.options.media_attachments_total_size_limit_in_mb,emailHistoriesAllowedContentTypes:t.options.email_histories_allowed_mime_types,emailBodiesAllowedContentTypes:t.options.email_bodies_allowed_mime_types},this.typingIndicatorTimeoutOverride=i.typingIndicatorTimeoutOverride,this.backoffConfiguration={min:1e3,max:4e3,maxAttemptsCount:3,...i.backoffConfigOverride},this.retryWhenThrottled=void 0===i.retryWhenThrottledOverride||i.retryWhenThrottledOverride,this.userInfosToSubscribe=i.userInfosToSubscribeOverride??t.options.user_infos_to_subscribe??100,this.reachabilityEnabled=t.options.reachability_enabled,this.userIdentity=t.identity,this.userInfo=t.sync_objects.my_user_info,this.myConversations=t.sync_objects.my_conversations;const r=i.httpCacheIntervalOverride??t.options.http_cache_interval??S;try{this.httpCacheInterval=p(f(r))}catch{n.error(`Failed to parse http cache interval ${r}, using default value ${S}`),this.httpCacheInterval=p(f(S))}const s=i.consumptionReportIntervalOverride??t.options.consumption_report_interval??k;try{this.consumptionReportInterval=p(f(s))}catch{n.error(`Failed to parse consumption report interval ${s}, using default value ${k}`),this.consumptionReportInterval=p(f(k))}this.channelMetadataCacheCapacity=e.channelMetadataCacheCapacity??100}}function T(e){return void 0===e||isNaN(Number(e))?null:Number(e)}function I(e){try{return new Date(e)}catch(e){return null}}function C(e,t,n){let i={};if(e)try{i=JSON.parse(e)}catch(e){n.warn(t,e)}return i}class R{base;args;paths;constructor(e){this.base=e.replace(/\/$/,""),this.args=[],this.paths=[]}arg(e,t){return void 0!==t&&this.args.push(encodeURIComponent(e)+"="+encodeURIComponent(t)),this}path(e){return this.paths.push(encodeURIComponent(e)),this}build(){let e=this.base;return this.paths.length&&(e+="/"+this.paths.join("/")),this.args.length&&(e+="?"+this.args.join("&")),e}}var P={};
|
130
|
-
/*
|
131
|
-
@license
|
132
|
-
Copyright (c) 2021 Twilio Inc.
|
133
|
-
|
134
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
135
|
-
|
136
|
-
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
137
|
-
|
138
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
139
|
-
|
140
|
-
|
141
|
-
*/Object.defineProperty(P,"__esModule",{value:!0});const M=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return{checks:t}},O=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return M((e=>{let n=!1;const i=[];for(const r of t)"string"!=typeof r?(n=n||e instanceof r,i.push(`an instance of ${r.name}`)):(n=n||typeof e===r,i.push(`of type ${r}`));return[n,i]}))},A=(e,t)=>{if(t.length>e.length)throw new Error(`Expected at most ${e.length} argument(s), but got ${t.length}`);for(;t.length<e.length;)t.push(void 0);for(const[n,i]of t.entries()){const[t,r,s,a]=U(e[n],i);if(t)continue;throw new Error(`Argument ${n+1} is expected to be ${s}${a} but got ${r}`)}},j=e=>{let t;return["undefined","boolean","number","bigint","string"].includes(typeof e)&&(t="string"==typeof e?`"${e}"`:`${e}`),"object"==typeof e&&"Object"!==e?.constructor?.name&&(t=null===e?"null":`instance of ${e?.constructor?.name}`),t||(t=typeof e),t},$=e=>{const t=[];for(const n of e)t.push(N(n));return t},N=e=>{const t=[],n=Array.isArray(e)?e:[e];for(const e of n)"string"!=typeof e&&"function"!=typeof e?t.push(e):t.push(O(e));return t},U=(e,t)=>{let n,i=[],r=!1;for(const s of e)for(const e of s.checks){const[s,a,o]=e(t);r=r||s,!n&&o&&(n=o),a&&(i="string"==typeof a?[...i,a]:[...i,...a])}if(r)return[!0];const s=n||j(t),a=i.length-1;return[!1,s,a>0?`${i.slice(0,a).join(", ")} or ${i[a]}`:i.join(", "),a>1?";":","]},L=M((e=>["string"==typeof e&&e.length>0,"a non-empty string"])),F=M((e=>["number"==typeof e&&Number.isInteger(e)&&e>=0,"a non-negative integer"])),q=M((e=>["object"==typeof e&&null!==e&&!Array.isArray(e),"a pure object (non-null and non-array)"]));var D=P.array=(e,t)=>M((n=>{if(!Array.isArray(n))return[!1,`an array of ${e}`];for(const[i,r]of n.entries()){const[n,s,a]=U(N(t),r);if(!n)return[!1,`a valid array of ${e} (index ${i} should be ${a})`,`malformed array of ${e} (index ${i} is ${s})`]}return[!0]})),B=P.custom=M,z=P.literal=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return M((e=>{let n=!1;const i=[];for(const r of t)n=n||e===r,i.push("string"==typeof r?`"${r}"`:`${r}`);return[n,i]}))},W=P.nonEmptyArray=(e,t)=>M((n=>{if(!Array.isArray(n)||n.length<1)return[!1,`a non-empty array of ${e}`];for(const[i,r]of n.entries()){const[n,s,a]=U(N(t),r);if(!n)return[!1,`a valid non-empty array of ${e} (index ${i} should be ${a})`,`malformed array of ${e} (index ${i} is ${s})`]}return[!0]})),K=P.nonEmptyString=L,H=P.nonNegativeInteger=F,V=P.objectSchema=(e,t)=>M((n=>{if("object"!=typeof n||null===n||Array.isArray(n))return[!1,`valid ${e} (should be a pure object)`];for(const[i,r]of Object.entries(t)){const[t,s,a]=U(N(r),n[i]);if(!t)return[!1,`valid ${e} (key "${i}" should be ${a})`,`malformed ${e} (key "${i}" is ${s})`]}return[!0]})),J=P.pureObject=q;P.runtimeTypeValidation=A,P.stringifyReceivedType=j,P.type=O;var G=P.validateConstructorTypes=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=$(t);return e=>class extends e{constructor(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];A(i,t),super(...t)}}},Q=P.validateTypes=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=$(t);return(e,t,n)=>{if("function"!=typeof n.value)throw new Error("The validateTypes decorator can only be applied to methods");const r=n.value;n.value=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return A(i,t),r.apply(this,t)}}},X=P.validateTypesAsync=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=$(t);return(e,t,n)=>{if("function"!=typeof n.value)throw new Error("The validateTypesAsync decorator can only be applied to methods");const r=n.value;n.value=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];try{A(i,t)}catch(e){return Promise.reject(e)}return r.apply(this,t)}}};const Z=B((e=>[["string","number","boolean","object"].includes(typeof e),"a JSON type"])),Y=B((e=>[["undefined","string","number","boolean","object"].includes(typeof e),"an optional JSON type"])),ee=V("send media options",{contentType:[z(null),"string"],filename:["string","undefined"],media:[z("null"),"string",..."function"==typeof Buffer?[Buffer]:[],..."function"==typeof Blob?[Blob]:[]]});var te={};
|
142
|
-
/*
|
143
|
-
@license
|
144
|
-
Copyright (c) 2021 Twilio Inc.
|
145
|
-
|
146
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
147
|
-
|
148
|
-
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
149
|
-
|
150
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
151
|
-
|
152
|
-
*/function ne(){}function ie(){ie.init.call(this)}function re(e){return void 0===e._maxListeners?ie.defaultMaxListeners:e._maxListeners}function se(e,t,n,i){var r,s,a;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),a=s[t]):(s=e._events=new ne,e._eventsCount=0),a){if("function"==typeof a?a=s[t]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),!a.warned&&(r=re(e))&&r>0&&a.length>r){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=a.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(o)}}else a=s[t]=n,++e._eventsCount;return e}function ae(e,t,n){var i=!1;function r(){e.removeListener(t,r),i||(i=!0,n.apply(e,arguments))}return r.listener=n,r}function oe(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function ce(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(te,"__esModule",{value:!0}),ne.prototype=Object.create(null),ie.EventEmitter=ie,ie.usingDomains=!1,ie.prototype.domain=void 0,ie.prototype._events=void 0,ie.prototype._maxListeners=void 0,ie.defaultMaxListeners=10,ie.init=function(){this.domain=null,ie.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new ne,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},ie.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},ie.prototype.getMaxListeners=function(){return re(this)},ie.prototype.emit=function(e){var t,n,i,r,s,a,o,c="error"===e;if(a=this._events)c=c&&null==a.error;else if(!c)return!1;if(o=this.domain,c){if(t=arguments[1],!o){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=a[e]))return!1;var l="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,r=ce(e,i),s=0;s<i;++s)r[s].call(n)}(n,l,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var r=e.length,s=ce(e,r),a=0;a<r;++a)s[a].call(n,i)}(n,l,this,arguments[1]);break;case 3:!function(e,t,n,i,r){if(t)e.call(n,i,r);else for(var s=e.length,a=ce(e,s),o=0;o<s;++o)a[o].call(n,i,r)}(n,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,r,s){if(t)e.call(n,i,r,s);else for(var a=e.length,o=ce(e,a),c=0;c<a;++c)o[c].call(n,i,r,s)}(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(r=new Array(i-1),s=1;s<i;s++)r[s-1]=arguments[s];!function(e,t,n,i){if(t)e.apply(n,i);else for(var r=e.length,s=ce(e,r),a=0;a<r;++a)s[a].apply(n,i)}(n,l,this,r)}return!0},ie.prototype.addListener=function(e,t){return se(this,e,t,!1)},ie.prototype.on=ie.prototype.addListener,ie.prototype.prependListener=function(e,t){return se(this,e,t,!0)},ie.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,ae(this,e,t)),this},ie.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,ae(this,e,t)),this},ie.prototype.removeListener=function(e,t){var n,i,r,s,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(n=i[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new ne:(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,s=n.length;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){a=n[s].listener,r=s;break}if(r<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new ne,this;delete i[e]}else!function(e,t){for(var n=t,i=n+1,r=e.length;i<r;n+=1,i+=1)e[n]=e[i];e.pop()}(n,r);i.removeListener&&this.emit("removeListener",e,a||t)}return this},ie.prototype.off=function(e,t){return this.removeListener(e,t)},ie.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new ne,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new ne:delete n[e]),this;if(0===arguments.length){for(var i,r=Object.keys(n),s=0;s<r.length;++s)"removeListener"!==(i=r[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new ne,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},ie.prototype.listeners=function(e){var t,n,i=this._events;return n=i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},ie.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):oe.call(e,t)},ie.prototype.listenerCount=oe,ie.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var ue=te.ReplayEventEmitter=class extends ie{#e=new Map;constructor(){super()}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}off(e,t){return super.off(e,t)}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return this.#e.set(e,n),super.emit(e,...n)}emitNextTick(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];Promise.resolve().then((()=>{this.#e.set(e,n),super.emit(e,...n)}))}addListener(e,t){return super.addListener(e,t)}removeListener(e,t){return super.removeListener(e,t)}addListenerWithReplay(e,t){const n=this.#e.get(e);return void 0!==n&&t(...n),this.addListener(e,t)}onWithReplay(e,t){return this.addListenerWithReplay(e,t)}onceWithReplay(e,t){const n=this.#e.get(e);return void 0!==n?(t(...n),this):super.once(e,t)}};te.ReplayEventSubject=class{#t;_=null;constructor(e){this.#t=e}on(e,t){return this.#t.on(e,t),this.#n(e,t)}addListener(e,t){return this.#t.addListener(e,t),this.#n(e,t)}onWithReplay(e,t){return this.#t.onWithReplay(e,t),this.#n(e,t)}addListenerWithReplay(e,t){return this.#t.addListenerWithReplay(e,t),this.#n(e,t)}once(e,t){return this.#t.once(e,t),this.#n(e,t)}onceWithReplay(e,t){return this.#t.onceWithReplay(e,t),this.#n(e,t)}#n(e,t){return()=>{this.#t.off(e,t)}}};var le={exports:{}};!function(e,t){var n="__lodash_hash_undefined__",i=1,s=2,a=9007199254740991,o="[object Arguments]",c="[object Array]",u="[object AsyncFunction]",l="[object Boolean]",d="[object Date]",h="[object Error]",p="[object Function]",f="[object GeneratorFunction]",m="[object Map]",g="[object Number]",y="[object Null]",v="[object Object]",b="[object Promise]",_="[object Proxy]",w="[object RegExp]",x="[object Set]",S="[object String]",k="[object Symbol]",E="[object Undefined]",T="[object WeakMap]",I="[object ArrayBuffer]",C="[object DataView]",R=/^\[object .+?Constructor\]$/,P=/^(?:0|[1-9]\d*)$/,M={};M["[object Float32Array]"]=M["[object Float64Array]"]=M["[object Int8Array]"]=M["[object Int16Array]"]=M["[object Int32Array]"]=M["[object Uint8Array]"]=M["[object Uint8ClampedArray]"]=M["[object Uint16Array]"]=M["[object Uint32Array]"]=!0,M[o]=M[c]=M[I]=M[l]=M[C]=M[d]=M[h]=M[p]=M[m]=M[g]=M[v]=M[w]=M[x]=M[S]=M[T]=!1;var O="object"==typeof r&&r&&r.Object===Object&&r,A="object"==typeof self&&self&&self.Object===Object&&self,j=O||A||Function("return this")(),$=t&&!t.nodeType&&t,N=$&&e&&!e.nodeType&&e,U=N&&N.exports===$,L=U&&O.process,F=function(){try{return L&&L.binding&&L.binding("util")}catch(e){}}(),q=F&&F.isTypedArray;function D(e,t){for(var n=-1,i=null==e?0:e.length;++n<i;)if(t(e[n],n,e))return!0;return!1}function B(e){var t=-1,n=Array(e.size);return e.forEach((function(e,i){n[++t]=[i,e]})),n}function z(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}var W,K,H,V=Array.prototype,J=Function.prototype,G=Object.prototype,Q=j["__core-js_shared__"],X=J.toString,Z=G.hasOwnProperty,Y=(W=/[^.]+$/.exec(Q&&Q.keys&&Q.keys.IE_PROTO||""))?"Symbol(src)_1."+W:"",ee=G.toString,te=RegExp("^"+X.call(Z).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ne=U?j.Buffer:void 0,ie=j.Symbol,re=j.Uint8Array,se=G.propertyIsEnumerable,ae=V.splice,oe=ie?ie.toStringTag:void 0,ce=Object.getOwnPropertySymbols,ue=ne?ne.isBuffer:void 0,le=(K=Object.keys,H=Object,function(e){return K(H(e))}),de=Fe(j,"DataView"),he=Fe(j,"Map"),pe=Fe(j,"Promise"),fe=Fe(j,"Set"),me=Fe(j,"WeakMap"),ge=Fe(Object,"create"),ye=ze(de),ve=ze(he),be=ze(pe),_e=ze(fe),we=ze(me),xe=ie?ie.prototype:void 0,Se=xe?xe.valueOf:void 0;function ke(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Ee(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Te(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Ie(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new Te;++t<n;)this.add(e[t])}function Ce(e){var t=this.__data__=new Ee(e);this.size=t.size}function Re(e,t){var n=He(e),i=!n&&Ke(e),r=!n&&!i&&Ve(e),s=!n&&!i&&!r&&Ze(e),a=n||i||r||s,o=a?function(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}(e.length,String):[],c=o.length;for(var u in e)!t&&!Z.call(e,u)||a&&("length"==u||r&&("offset"==u||"parent"==u)||s&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||Be(u,c))||o.push(u);return o}function Pe(e,t){for(var n=e.length;n--;)if(We(e[n][0],t))return n;return-1}function Me(e){return null==e?void 0===e?E:y:oe&&oe in Object(e)?function(e){var t=Z.call(e,oe),n=e[oe];try{e[oe]=void 0;var i=!0}catch(e){}var r=ee.call(e);i&&(t?e[oe]=n:delete e[oe]);return r}(e):function(e){return ee.call(e)}(e)}function Oe(e){return Xe(e)&&Me(e)==o}function Ae(e,t,n,r,a){return e===t||(null==e||null==t||!Xe(e)&&!Xe(t)?e!=e&&t!=t:function(e,t,n,r,a,u){var p=He(e),f=He(t),y=p?c:De(e),b=f?c:De(t),_=(y=y==o?v:y)==v,E=(b=b==o?v:b)==v,T=y==b;if(T&&Ve(e)){if(!Ve(t))return!1;p=!0,_=!1}if(T&&!_)return u||(u=new Ce),p||Ze(e)?Ne(e,t,n,r,a,u):function(e,t,n,r,a,o,c){switch(n){case C:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case I:return!(e.byteLength!=t.byteLength||!o(new re(e),new re(t)));case l:case d:case g:return We(+e,+t);case h:return e.name==t.name&&e.message==t.message;case w:case S:return e==t+"";case m:var u=B;case x:var p=r&i;if(u||(u=z),e.size!=t.size&&!p)return!1;var f=c.get(e);if(f)return f==t;r|=s,c.set(e,t);var y=Ne(u(e),u(t),r,a,o,c);return c.delete(e),y;case k:if(Se)return Se.call(e)==Se.call(t)}return!1}(e,t,y,n,r,a,u);if(!(n&i)){var R=_&&Z.call(e,"__wrapped__"),P=E&&Z.call(t,"__wrapped__");if(R||P){var M=R?e.value():e,O=P?t.value():t;return u||(u=new Ce),a(M,O,n,r,u)}}if(!T)return!1;return u||(u=new Ce),function(e,t,n,r,s,a){var o=n&i,c=Ue(e),u=c.length,l=Ue(t),d=l.length;if(u!=d&&!o)return!1;var h=u;for(;h--;){var p=c[h];if(!(o?p in t:Z.call(t,p)))return!1}var f=a.get(e);if(f&&a.get(t))return f==t;var m=!0;a.set(e,t),a.set(t,e);var g=o;for(;++h<u;){var y=e[p=c[h]],v=t[p];if(r)var b=o?r(v,y,p,t,e,a):r(y,v,p,e,t,a);if(!(void 0===b?y===v||s(y,v,n,r,a):b)){m=!1;break}g||(g="constructor"==p)}if(m&&!g){var _=e.constructor,w=t.constructor;_==w||!("constructor"in e)||!("constructor"in t)||"function"==typeof _&&_ instanceof _&&"function"==typeof w&&w instanceof w||(m=!1)}return a.delete(e),a.delete(t),m}(e,t,n,r,a,u)}(e,t,n,r,Ae,a))}function je(e){return!(!Qe(e)||function(e){return!!Y&&Y in e}(e))&&(Je(e)?te:R).test(ze(e))}function $e(e){if(n=(t=e)&&t.constructor,i="function"==typeof n&&n.prototype||G,t!==i)return le(e);var t,n,i,r=[];for(var s in Object(e))Z.call(e,s)&&"constructor"!=s&&r.push(s);return r}function Ne(e,t,n,r,a,o){var c=n&i,u=e.length,l=t.length;if(u!=l&&!(c&&l>u))return!1;var d=o.get(e);if(d&&o.get(t))return d==t;var h=-1,p=!0,f=n&s?new Ie:void 0;for(o.set(e,t),o.set(t,e);++h<u;){var m=e[h],g=t[h];if(r)var y=c?r(g,m,h,t,e,o):r(m,g,h,e,t,o);if(void 0!==y){if(y)continue;p=!1;break}if(f){if(!D(t,(function(e,t){if(i=t,!f.has(i)&&(m===e||a(m,e,n,r,o)))return f.push(t);var i}))){p=!1;break}}else if(m!==g&&!a(m,g,n,r,o)){p=!1;break}}return o.delete(e),o.delete(t),p}function Ue(e){return function(e,t,n){var i=t(e);return He(e)?i:function(e,t){for(var n=-1,i=t.length,r=e.length;++n<i;)e[r+n]=t[n];return e}(i,n(e))}(e,Ye,qe)}function Le(e,t){var n=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?n["string"==typeof t?"string":"hash"]:n.map}function Fe(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return je(n)?n:void 0}ke.prototype.clear=function(){this.__data__=ge?ge(null):{},this.size=0},ke.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},ke.prototype.get=function(e){var t=this.__data__;if(ge){var i=t[e];return i===n?void 0:i}return Z.call(t,e)?t[e]:void 0},ke.prototype.has=function(e){var t=this.__data__;return ge?void 0!==t[e]:Z.call(t,e)},ke.prototype.set=function(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=ge&&void 0===t?n:t,this},Ee.prototype.clear=function(){this.__data__=[],this.size=0},Ee.prototype.delete=function(e){var t=this.__data__,n=Pe(t,e);return!(n<0)&&(n==t.length-1?t.pop():ae.call(t,n,1),--this.size,!0)},Ee.prototype.get=function(e){var t=this.__data__,n=Pe(t,e);return n<0?void 0:t[n][1]},Ee.prototype.has=function(e){return Pe(this.__data__,e)>-1},Ee.prototype.set=function(e,t){var n=this.__data__,i=Pe(n,e);return i<0?(++this.size,n.push([e,t])):n[i][1]=t,this},Te.prototype.clear=function(){this.size=0,this.__data__={hash:new ke,map:new(he||Ee),string:new ke}},Te.prototype.delete=function(e){var t=Le(this,e).delete(e);return this.size-=t?1:0,t},Te.prototype.get=function(e){return Le(this,e).get(e)},Te.prototype.has=function(e){return Le(this,e).has(e)},Te.prototype.set=function(e,t){var n=Le(this,e),i=n.size;return n.set(e,t),this.size+=n.size==i?0:1,this},Ie.prototype.add=Ie.prototype.push=function(e){return this.__data__.set(e,n),this},Ie.prototype.has=function(e){return this.__data__.has(e)},Ce.prototype.clear=function(){this.__data__=new Ee,this.size=0},Ce.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},Ce.prototype.get=function(e){return this.__data__.get(e)},Ce.prototype.has=function(e){return this.__data__.has(e)},Ce.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Ee){var i=n.__data__;if(!he||i.length<199)return i.push([e,t]),this.size=++n.size,this;n=this.__data__=new Te(i)}return n.set(e,t),this.size=n.size,this};var qe=ce?function(e){return null==e?[]:(e=Object(e),function(e,t){for(var n=-1,i=null==e?0:e.length,r=0,s=[];++n<i;){var a=e[n];t(a,n,e)&&(s[r++]=a)}return s}(ce(e),(function(t){return se.call(e,t)})))}:function(){return[]},De=Me;function Be(e,t){return!!(t=null==t?a:t)&&("number"==typeof e||P.test(e))&&e>-1&&e%1==0&&e<t}function ze(e){if(null!=e){try{return X.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function We(e,t){return e===t||e!=e&&t!=t}(de&&De(new de(new ArrayBuffer(1)))!=C||he&&De(new he)!=m||pe&&De(pe.resolve())!=b||fe&&De(new fe)!=x||me&&De(new me)!=T)&&(De=function(e){var t=Me(e),n=t==v?e.constructor:void 0,i=n?ze(n):"";if(i)switch(i){case ye:return C;case ve:return m;case be:return b;case _e:return x;case we:return T}return t});var Ke=Oe(function(){return arguments}())?Oe:function(e){return Xe(e)&&Z.call(e,"callee")&&!se.call(e,"callee")},He=Array.isArray;var Ve=ue||function(){return!1};function Je(e){if(!Qe(e))return!1;var t=Me(e);return t==p||t==f||t==u||t==_}function Ge(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=a}function Qe(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function Xe(e){return null!=e&&"object"==typeof e}var Ze=q?function(e){return function(t){return e(t)}}(q):function(e){return Xe(e)&&Ge(e.length)&&!!M[Me(e)]};function Ye(e){return null!=(t=e)&&Ge(t.length)&&!Je(t)?Re(e):$e(e);var t}e.exports=function(e,t){return Ae(e,t)}}(le,le.exports);var de=le.exports;const he=h.scope("User");class User extends ue{links;configuration;services;entity;state;promiseToFetch=null;subscribed;_initializationPromise;_resolveInitializationPromise;constructor(e,t,n,i){super(),this.services=i,this.subscribed="initializing",this.setMaxListeners(0),this.state={identity:e,entityName:t,friendlyName:null,attributes:{},online:null,notifiable:null},this._initializationPromise=new Promise((e=>{this._resolveInitializationPromise=e})),null!==n&&this._resolveInitialization(n,e,t,!1)}updated="updated";userSubscribed="userSubscribed";userUnsubscribed="userUnsubscribed";get identity(){return this.state.identity}set identity(e){this.state.identity=e}set entityName(e){this.state.entityName=e}get attributes(){return this.state.attributes}get friendlyName(){return this.state.friendlyName}get isOnline(){return this.state.online}get isNotifiable(){return this.state.notifiable}get isSubscribed(){return"subscribed"==this.subscribed}async _update(e,t){await this._initializationPromise;const n=[];switch(he.debug("User for",this.state.identity,"updated:",e,t),e){case"friendlyName":this.state.friendlyName!==t.value&&(n.push("friendlyName"),this.state.friendlyName=t.value);break;case"attributes":const e=C(t.value,`Retrieved malformed attributes from the server for user: ${this.state.identity}`,he);de(this.state.attributes,e)||(this.state.attributes=e,n.push("attributes"));break;case"reachability":this.state.online!==t.online&&(this.state.online=t.online,n.push("reachabilityOnline")),this.state.notifiable!==t.notifiable&&(this.state.notifiable=t.notifiable,n.push("reachabilityNotifiable"));break;default:return}n.length>0&&this.emit("updated",{user:this,updateReasons:n})}async _updateReachabilityInfo(e,t){return await this._initializationPromise,this.configuration.reachabilityEnabled?e.get("reachability").then(t).catch((e=>{he.warn("Failed to get reachability info for ",this.state.identity,e)})):Promise.resolve()}async _fetch(){return await this._initializationPromise,this.state.entityName?(this.promiseToFetch=this.services.syncClient.map({id:this.state.entityName,mode:"open_existing",includeItems:!0}).then((e=>(this.entity=e,e.on("itemUpdated",(e=>(he.debug(this.state.entityName+" ("+this.state.identity+") itemUpdated: "+e.item.key),this._update(e.item.key,e.item.data)))),e.on("itemAdded",(e=>(he.debug(this.state.entityName+" ("+this.state.identity+") itemAdded: "+e.item.key),this._update(e.item.key,e.item.data)))),Promise.all([e.get("friendlyName").then((e=>this._update(e.key,e.data))),e.get("attributes").then((e=>this._update(e.key,e.data))),this._updateReachabilityInfo(e,(e=>this._update(e.key,e.data)))])))).then((()=>(he.debug("Fetched for",this.identity),this.subscribed="subscribed",this.emit("userSubscribed",this),this))).catch((e=>{throw this.promiseToFetch=null,e})),this.promiseToFetch):this}async _ensureFetched(){return await this._initializationPromise,this.promiseToFetch||this._fetch()}async updateAttributes(e){if(await this._initializationPromise,"unsubscribed"==this.subscribed)throw new Error("Can't modify unsubscribed object");return await this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(e)}),this}async updateFriendlyName(e){if(await this._initializationPromise,"unsubscribed"==this.subscribed)throw new Error("Can't modify unsubscribed object");return await this.services.commandExecutor.mutateResource("post",this.links.self,{friendly_name:e}),this}async unsubscribe(){await this._initializationPromise,this.promiseToFetch&&(await this.promiseToFetch,this.entity.close(),this.promiseToFetch=null,this.subscribed="unsubscribed",this.emit("userUnsubscribed",this))}_resolveInitialization(e,t,n,i){this.configuration=e,this.identity=t,this.entityName=n,this.links={self:`${this.configuration.links.users}/${encodeURIComponent(this.identity)}`},this._resolveInitializationPromise(),i&&this.emit("updated",{user:this,updateReasons:["friendlyName","attributes","reachabilityOnline","reachabilityNotifiable"]})}}n([X(Z),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],User.prototype,"updateAttributes",null),n([X(["string"]),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],User.prototype,"updateFriendlyName",null);var pe={};
|
153
|
-
/*
|
154
|
-
@license
|
155
|
-
Copyright (c) 2016, Twilio, Inc.
|
156
|
-
|
157
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
158
|
-
purpose with or without fee is hereby granted, provided that the above
|
159
|
-
copyright notice and this permission notice appear in all copies.
|
160
|
-
|
161
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
162
|
-
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
163
|
-
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
164
|
-
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
165
|
-
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
166
|
-
OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
167
|
-
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
168
|
-
|
169
|
-
*/function fe(){}function me(){me.init.call(this)}function ge(e){return void 0===e._maxListeners?me.defaultMaxListeners:e._maxListeners}function ye(e,t,n,i){var r,s,a;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),a=s[t]):(s=e._events=new fe,e._eventsCount=0),a){if("function"==typeof a?a=s[t]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),!a.warned&&(r=ge(e))&&r>0&&a.length>r){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=a.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(o)}}else a=s[t]=n,++e._eventsCount;return e}function ve(e,t,n){var i=!1;function r(){e.removeListener(t,r),i||(i=!0,n.apply(e,arguments))}return r.listener=n,r}function be(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function _e(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}Object.defineProperty(pe,"__esModule",{value:!0}),fe.prototype=Object.create(null),me.EventEmitter=me,me.usingDomains=!1,me.prototype.domain=void 0,me.prototype._events=void 0,me.prototype._maxListeners=void 0,me.defaultMaxListeners=10,me.init=function(){this.domain=null,me.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new fe,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},me.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},me.prototype.getMaxListeners=function(){return ge(this)},me.prototype.emit=function(e){var t,n,i,r,s,a,o,c="error"===e;if(a=this._events)c=c&&null==a.error;else if(!c)return!1;if(o=this.domain,c){if(t=arguments[1],!o){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=a[e]))return!1;var l="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,r=_e(e,i),s=0;s<i;++s)r[s].call(n)}(n,l,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var r=e.length,s=_e(e,r),a=0;a<r;++a)s[a].call(n,i)}(n,l,this,arguments[1]);break;case 3:!function(e,t,n,i,r){if(t)e.call(n,i,r);else for(var s=e.length,a=_e(e,s),o=0;o<s;++o)a[o].call(n,i,r)}(n,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,r,s){if(t)e.call(n,i,r,s);else for(var a=e.length,o=_e(e,a),c=0;c<a;++c)o[c].call(n,i,r,s)}(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(r=new Array(i-1),s=1;s<i;s++)r[s-1]=arguments[s];!function(e,t,n,i){if(t)e.apply(n,i);else for(var r=e.length,s=_e(e,r),a=0;a<r;++a)s[a].apply(n,i)}(n,l,this,r)}return!0},me.prototype.addListener=function(e,t){return ye(this,e,t,!1)},me.prototype.on=me.prototype.addListener,me.prototype.prependListener=function(e,t){return ye(this,e,t,!0)},me.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,ve(this,e,t)),this},me.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,ve(this,e,t)),this},me.prototype.removeListener=function(e,t){var n,i,r,s,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(n=i[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new fe:(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,s=n.length;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){a=n[s].listener,r=s;break}if(r<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new fe,this;delete i[e]}else!function(e,t){for(var n=t,i=n+1,r=e.length;i<r;n+=1,i+=1)e[n]=e[i];e.pop()}(n,r);i.removeListener&&this.emit("removeListener",e,a||t)}return this},me.prototype.off=function(e,t){return this.removeListener(e,t)},me.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new fe,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new fe:delete n[e]),this;if(0===arguments.length){for(var i,r=Object.keys(n),s=0;s<r.length;++s)"removeListener"!==(i=r[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new fe,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},me.prototype.listeners=function(e){var t,n,i=this._events;return n=i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},me.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):be.call(e,t)},me.prototype.listenerCount=be,me.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class we extends me{minDelay;maxDelay;initialDelay;maxAttemptsCount;maxAttemptsTime;randomness;prevDelay;currDelay;timeout=null;inProgress;attemptNum;startTimestamp=-1;constructor(e){super(),this.minDelay=e.min,this.maxDelay=e.max,this.initialDelay=e.initial||0,this.maxAttemptsCount=e.maxAttemptsCount||0,this.maxAttemptsTime=e.maxAttemptsTime||0,this.randomness=e.randomness||0,this.inProgress=!1,this.attemptNum=0,this.prevDelay=0,this.currDelay=0}attempt(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.attemptNum++,this.emit("attempt",this)}nextDelay(e){if("number"==typeof e)return this.prevDelay=0,this.currDelay=e,e;if(0==this.attemptNum)return this.initialDelay;if(1==this.attemptNum)return this.currDelay=this.minDelay,this.currDelay;this.prevDelay=this.currDelay;let t=this.currDelay+this.prevDelay;return this.maxDelay&&t>this.maxDelay&&(this.currDelay=this.maxDelay,t=this.maxDelay),this.currDelay=t,t}randomize(e){const t=e*this.randomness,n=Math.round(Math.random()*t*2-t);return Math.max(0,e+n)}scheduleAttempt(e){if(this.maxAttemptsCount&&this.attemptNum>=this.maxAttemptsCount)return this.cleanup(),void this.emit("failed",new Error("Maximum attempt count limit reached"));let t=this.nextDelay(e);if(t=this.randomize(t),this.maxAttemptsTime&&this.startTimestamp+this.maxAttemptsTime<Date.now()+t)return this.cleanup(),void this.emit("failed",new Error("Maximum attempt time limit reached"));this.timeout=setTimeout((()=>this.attempt()),t)}cleanup(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.inProgress=!1,this.attemptNum=0,this.prevDelay=0,this.currDelay=0}start(){if(this.inProgress)throw new Error("Retrier is already in progress");this.inProgress=!0,this.startTimestamp=Date.now(),this.scheduleAttempt(this.initialDelay)}cancel(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null,this.inProgress=!1,this.emit("cancelled"))}succeeded(e){this.emit("succeeded",e)}failed(e,t){if(this.timeout)throw new Error("Retrier attempt is already in progress");this.scheduleAttempt(t)}}function xe(e){return null!=e}class Se extends me{maxDelay;initialDelay;factor;randomisationFactor;backoffDelay=0;nextBackoffDelay=0;backoffNumber=0;timeoutID=null;maxNumberOfRetry=-1;constructor(e){super(),e=e||{};const{initialDelay:t,maxDelay:n,randomisationFactor:i,factor:r}=e;if(xe(t)&&t<1)throw new Error("The initial timeout must be equal to or greater than 1.");if(xe(n)&&n<=1)throw new Error("The maximal timeout must be greater than 1.");if(xe(i)&&(i<0||i>1))throw new Error("The randomisation factor must be between 0 and 1.");if(xe(r)&&r<=1)throw new Error("Exponential factor should be greater than 1.");if(this.initialDelay=t||100,this.maxDelay=n||1e4,this.maxDelay<=this.initialDelay)throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");this.randomisationFactor=i||0,this.factor=r||2,this.reset()}static exponential(e){return new Se(e)}backoff(e){null==this.timeoutID&&(this.backoffNumber===this.maxNumberOfRetry?(this.emit("fail",e),this.reset()):(this.backoffDelay=this.next(),this.timeoutID=setTimeout(this.onBackoff.bind(this),this.backoffDelay),this.emit("backoff",this.backoffNumber,this.backoffDelay,e)))}reset(){this.backoffDelay=0,this.nextBackoffDelay=this.initialDelay,this.backoffNumber=0,this.timeoutID&&clearTimeout(this.timeoutID),this.timeoutID=null}failAfter(e){if(e<=0)throw new Error(`Expected a maximum number of retry greater than 0 but got ${e}`);this.maxNumberOfRetry=e}next(){this.backoffDelay=Math.min(this.nextBackoffDelay,this.maxDelay),this.nextBackoffDelay=this.backoffDelay*this.factor;const e=1+Math.random()*this.randomisationFactor;return Math.min(this.maxDelay,Math.round(this.backoffDelay*e))}onBackoff(){this.timeoutID=null,this.emit("ready",this.backoffNumber,this.backoffDelay),this.backoffNumber++}}var ke=pe.AsyncRetrier=class extends me{retrier;resolve=()=>{};reject=()=>{};constructor(e){super(),this.retrier=new we(e)}run(e){return this.retrier.on("attempt",(()=>{e().then((e=>this.retrier.succeeded(e))).catch((e=>this.retrier.failed(e)))})),this.retrier.on("succeeded",(e=>this.resolve(e))),this.retrier.on("cancelled",(()=>this.reject(new Error("Cancelled")))),this.retrier.on("failed",(e=>this.reject(e))),new Promise(((e,t)=>{this.resolve=e,this.reject=t,this.retrier.start()}))}cancel(){this.retrier.cancel()}};pe.Backoff=Se;var Ee=pe.Retrier=we,Te={},Ie={};let Ce=e=>crypto.getRandomValues(new Uint8Array(e)),Re=(e,t,n)=>{let i=(2<<Math.log(e.length-1)/Math.LN2)-1,r=-~(1.6*i*t/e.length);return function(){let s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t,a="";for(;;){let t=n(r),o=r;for(;o--;)if(a+=e[t[o]&i]||"",a.length===s)return a}}},Pe=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:21;return crypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),"")};var Me=Object.freeze({__proto__:null,nanoid:Pe,customAlphabet:function(e){return Re(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:21,Ce)},customRandom:Re,urlAlphabet:"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",random:Ce}),Oe=s(Me);
|
170
|
-
/*
|
171
|
-
@license
|
172
|
-
Copyright (c) 2022 Twilio Inc.
|
173
|
-
|
174
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
175
|
-
|
176
|
-
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
177
|
-
|
178
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
179
|
-
|
180
|
-
|
181
|
-
*/
|
182
|
-
Object.defineProperty(Ie,"__esModule",{value:!0});var Ae=u.exports,je=Oe;function $e(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var Ne=$e(Ae);const Ue=e=>{const t=Ne.default.getLevel();Ne.default.setLevel("warn"),Ne.default.warn(e),Ne.default.setLevel(t)};class Le extends Error{constructor(){super("Promise was cancelled")}}class Fe extends Promise{static#i=new Map;#r;#s;constructor(e){const t=je.nanoid();let n;super(((i,r)=>(n=r,e((e=>{Fe.#i.delete(t),i(e)}),(e=>{Fe.#i.delete(t),r(e)}),(e=>{Fe.#i.set(t,e)}))))),this.#r=t,this.#s=n}cancel(){const e=Fe.#i.get(this.#r);return e?.(),this.#s&&(this.catch((()=>{})),this.#s(new Le)),this}static withAsyncExecutor(e){return new Fe((async(t,n,i)=>{try{t(await e(i))}catch(e){n(e)}}))}}const qe={unknown:"Unknown error",cancelled:"Job was cancelled",timeout:"Timeout occurred",mediaUploadError:"Media upload error",mediaFetchError:"Media fetch error",tooManyAttachments:"Too many attachments",unsupportedEmailBodyContentType:"Unsupported email body content type",unsupportedEmailHistoryContentType:"Unsupported email history content type",transportDisconnected:"Transport has been disconnected",networkBecameUnreachable:"Network became unreachable",unauthorized:"Unauthorized",tokenExpired:"Token expired",tokenUpdatedLocally:"Transport disconnected, token updated locally and will be used at reconnect",tooManyRequests:"Request failed with 429 reply",hostnameUnverified:"Failed on ssl handshake: CERTIFICATE_VERIFY_FAILED",sslHandshakeError:"Failed on ssl handshake: UNAUTHORIZED",closeMessageReceived:"Twilsock received a close message from the server",cannotParse:"Error while parsing an incoming message"};class De extends Error{errorInfo;constructor(e){super(`${e}`),this.errorInfo=e,Object.freeze(e)}}var Be=Ie.CancellablePromise=Fe,ze=Ie.CancellationError=Le;Ie.Deferred=class{promise;#a;#o;#c=!1;constructor(){this.promise=new Promise(((e,t)=>{this.#a=t=>{this.#c=!0,e(t)},this.#o=e=>{this.#c=!0,t(e)}}))}get resolve(){return this.#a}get reject(){return this.#o}get isDone(){return this.#c}},Ie.ErrorInfo=class{reason;message;status;code;description;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:qe[e];this.reason=e,this.message=t,this.status=n,this.code=i,this.description=r}toString(){return`${this.description} ${this.status}:${this.code} ${this.message}`}},Ie.Logger=class{#u;#l;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.#u=t,this.#l=Ae.getLogger(e)}setLevel(e){this.#l.setLevel(e)}trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.trace.apply(null,this.#d("T",t))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.debug.apply(null,this.#d("D",t))}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.info.apply(null,this.#d("I",t))}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.warn.apply(null,this.#d("W",t))}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.error.apply(null,this.#d("E",t))}#d(e,t){return[`${(new Date).toISOString()} ${this.#u} ${e}:`,...t]}};var We=Ie.TwilioError=De;Ie.deprecated=(e,t,n)=>(i,r,s)=>{if("function"!=typeof s.value&&void 0===s?.get)throw new Error("The deprecated decorator can only be applied to methods or getters");if("function"==typeof s.value){const i=s.value;return void(s.value=function(){Ue(`The method ${e} is deprecated${t?", use "+t+" instead":""}${n?", "+n:"."}`);for(var r=arguments.length,s=new Array(r),a=0;a<r;a++)s[a]=arguments[a];return i.apply(this,s)})}const a=s.get;s.get=function(){return Ue(`The getter ${e} is deprecated${t?", use "+t+" instead":""}${n?", "+n:"."}`),a?.apply(this)}},Ie.deprecationWarning=Ue;var Ke={exports:{}};
|
183
|
-
/*!
|
184
|
-
* Platform.js v1.3.6
|
185
|
-
* Copyright 2014-2020 Benjamin Tan
|
186
|
-
* Copyright 2011-2013 John-David Dalton
|
187
|
-
* Available under MIT license
|
188
|
-
*/!function(e,t){(function(){var n={function:!0,object:!0}[typeof window]&&window||this,i=t,s=e&&!e.nodeType&&e,a=i&&s&&"object"==typeof r&&r;!a||a.global!==a&&a.window!==a&&a.self!==a||(n=a);var o=Math.pow(2,53)-1,c=/\bOpera/,u=Object.prototype,l=u.hasOwnProperty,d=u.toString;function h(e){return(e=String(e)).charAt(0).toUpperCase()+e.slice(1)}function p(e){return e=v(e),/^(?:webOS|i(?:OS|P))/.test(e)?e:h(e)}function f(e,t){for(var n in e)l.call(e,n)&&t(e[n],n,e)}function m(e){return null==e?h(e):d.call(e).slice(8,-1)}function g(e){return String(e).replace(/([ -])(?!$)/g,"$1?")}function y(e,t){var n=null;return function(e,t){var n=-1,i=e?e.length:0;if("number"==typeof i&&i>-1&&i<=o)for(;++n<i;)t(e[n],n,e);else f(e,t)}(e,(function(i,r){n=t(n,i,r,e)})),n}function v(e){return String(e).replace(/^ +| +$/g,"")}var b=function e(t){var i=n,r=t&&"object"==typeof t&&"String"!=m(t);r&&(i=t,t=null);var s=i.navigator||{},a=s.userAgent||"";t||(t=a);var o,u,l=r?!!s.likeChrome:/\bChrome\b/.test(t)&&!/internal|\n/i.test(d.toString()),h="Object",b=r?h:"ScriptBridgingProxyObject",_=r?h:"Environment",w=r&&i.java?"JavaPackage":m(i.java),x=r?h:"RuntimeObject",S=/\bJava/.test(w)&&i.java,k=S&&m(i.environment)==_,E=S?"a":"α",T=S?"b":"β",I=i.document||{},C=i.operamini||i.opera,R=c.test(R=r&&C?C["[[Class]]"]:m(C))?R:C=null,P=t,M=[],O=null,A=t==a,j=A&&C&&"function"==typeof C.version&&C.version(),$=y([{label:"EdgeHTML",pattern:"Edge"},"Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"],(function(e,n){return e||RegExp("\\b"+(n.pattern||g(n))+"\\b","i").exec(t)&&(n.label||n)})),N=function(e){return y(e,(function(e,n){return e||RegExp("\\b"+(n.pattern||g(n))+"\\b","i").exec(t)&&(n.label||n)}))}(["Adobe AIR","Arora","Avant Browser","Breach","Camino","Electron","Epiphany","Fennec","Flock","Galeon","GreenBrowser","iCab","Iceweasel","K-Meleon","Konqueror","Lunascape","Maxthon",{label:"Microsoft Edge",pattern:"(?:Edge|Edg|EdgA|EdgiOS)"},"Midori","Nook Browser","PaleMoon","PhantomJS","Raven","Rekonq","RockMelt",{label:"Samsung Internet",pattern:"SamsungBrowser"},"SeaMonkey",{label:"Silk",pattern:"(?:Cloud9|Silk-Accelerated)"},"Sleipnir","SlimBrowser",{label:"SRWare Iron",pattern:"Iron"},"Sunrise","Swiftfox","Vivaldi","Waterfox","WebPositive",{label:"Yandex Browser",pattern:"YaBrowser"},{label:"UC Browser",pattern:"UCBrowser"},"Opera Mini",{label:"Opera Mini",pattern:"OPiOS"},"Opera",{label:"Opera",pattern:"OPR"},"Chromium","Chrome",{label:"Chrome",pattern:"(?:HeadlessChrome)"},{label:"Chrome Mobile",pattern:"(?:CriOS|CrMo)"},{label:"Firefox",pattern:"(?:Firefox|Minefield)"},{label:"Firefox for iOS",pattern:"FxiOS"},{label:"IE",pattern:"IEMobile"},{label:"IE",pattern:"MSIE"},"Safari"]),U=q([{label:"BlackBerry",pattern:"BB10"},"BlackBerry",{label:"Galaxy S",pattern:"GT-I9000"},{label:"Galaxy S2",pattern:"GT-I9100"},{label:"Galaxy S3",pattern:"GT-I9300"},{label:"Galaxy S4",pattern:"GT-I9500"},{label:"Galaxy S5",pattern:"SM-G900"},{label:"Galaxy S6",pattern:"SM-G920"},{label:"Galaxy S6 Edge",pattern:"SM-G925"},{label:"Galaxy S7",pattern:"SM-G930"},{label:"Galaxy S7 Edge",pattern:"SM-G935"},"Google TV","Lumia","iPad","iPod","iPhone","Kindle",{label:"Kindle Fire",pattern:"(?:Cloud9|Silk-Accelerated)"},"Nexus","Nook","PlayBook","PlayStation Vita","PlayStation","TouchPad","Transformer",{label:"Wii U",pattern:"WiiU"},"Wii","Xbox One",{label:"Xbox 360",pattern:"Xbox"},"Xoom"]),L=function(e){return y(e,(function(e,n,i){return e||(n[U]||n[/^[a-z]+(?: +[a-z]+\b)*/i.exec(U)]||RegExp("\\b"+g(i)+"(?:\\b|\\w*\\d)","i").exec(t))&&i}))}({Apple:{iPad:1,iPhone:1,iPod:1},Alcatel:{},Archos:{},Amazon:{Kindle:1,"Kindle Fire":1},Asus:{Transformer:1},"Barnes & Noble":{Nook:1},BlackBerry:{PlayBook:1},Google:{"Google TV":1,Nexus:1},HP:{TouchPad:1},HTC:{},Huawei:{},Lenovo:{},LG:{},Microsoft:{Xbox:1,"Xbox One":1},Motorola:{Xoom:1},Nintendo:{"Wii U":1,Wii:1},Nokia:{Lumia:1},Oppo:{},Samsung:{"Galaxy S":1,"Galaxy S2":1,"Galaxy S3":1,"Galaxy S4":1},Sony:{PlayStation:1,"PlayStation Vita":1},Xiaomi:{Mi:1,Redmi:1}}),F=function(e){return y(e,(function(e,n){var i=n.pattern||g(n);return!e&&(e=RegExp("\\b"+i+"(?:/[\\d.]+|[ \\w.]*)","i").exec(t))&&(e=function(e,t,n){var i={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};return t&&n&&/^Win/i.test(e)&&!/^Windows Phone /i.test(e)&&(i=i[/[\d.]+$/.exec(e)])&&(e="Windows "+i),e=String(e),t&&n&&(e=e.replace(RegExp(t,"i"),n)),p(e.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").replace(/\b(Chrome OS \w+) [\d.]+\b/,"$1").split(" on ")[0])}(e,i,n.label||n)),e}))}(["Windows Phone","KaiOS","Android","CentOS",{label:"Chrome OS",pattern:"CrOS"},"Debian",{label:"DragonFly BSD",pattern:"DragonFly"},"Fedora","FreeBSD","Gentoo","Haiku","Kubuntu","Linux Mint","OpenBSD","Red Hat","SuSE","Ubuntu","Xubuntu","Cygwin","Symbian OS","hpwOS","webOS ","webOS","Tablet OS","Tizen","Linux","Mac OS X","Macintosh","Mac","Windows 98;","Windows "]);function q(e){return y(e,(function(e,n){var i=n.pattern||g(n);return!e&&(e=RegExp("\\b"+i+" *\\d+[.\\w_]*","i").exec(t)||RegExp("\\b"+i+" *\\w+-[\\w]*","i").exec(t)||RegExp("\\b"+i+"(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)","i").exec(t))&&((e=String(n.label&&!RegExp(i,"i").test(n.label)?n.label:e).split("/"))[1]&&!/[\d.]+/.test(e[0])&&(e[0]+=" "+e[1]),n=n.label||n,e=p(e[0].replace(RegExp(i,"i"),n).replace(RegExp("; *(?:"+n+"[_-])?","i")," ").replace(RegExp("("+n+")[-_.]?(\\w)","i"),"$1 $2"))),e}))}function D(e){return y(e,(function(e,n){return e||(RegExp(n+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(t)||0)[1]||null}))}if($&&($=[$]),/\bAndroid\b/.test(F)&&!U&&(o=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(t))&&(U=v(o[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,"")||null),L&&!U?U=q([L]):L&&U&&(U=U.replace(RegExp("^("+g(L)+")[-_.\\s]","i"),L+" ").replace(RegExp("^("+g(L)+")[-_.]?(\\w)","i"),L+" $2")),(o=/\bGoogle TV\b/.exec(U))&&(U=o[0]),/\bSimulator\b/i.test(t)&&(U=(U?U+" ":"")+"Simulator"),"Opera Mini"==N&&/\bOPiOS\b/.test(t)&&M.push("running in Turbo/Uncompressed mode"),"IE"==N&&/\blike iPhone OS\b/.test(t)?(L=(o=e(t.replace(/like iPhone OS/,""))).manufacturer,U=o.product):/^iP/.test(U)?(N||(N="Safari"),F="iOS"+((o=/ OS ([\d_]+)/i.exec(t))?" "+o[1].replace(/_/g,"."):"")):"Konqueror"==N&&/^Linux\b/i.test(F)?F="Kubuntu":L&&"Google"!=L&&(/Chrome/.test(N)&&!/\bMobile Safari\b/i.test(t)||/\bVita\b/.test(U))||/\bAndroid\b/.test(F)&&/^Chrome/.test(N)&&/\bVersion\//i.test(t)?(N="Android Browser",F=/\bAndroid\b/.test(F)?F:"Android"):"Silk"==N?(/\bMobi/i.test(t)||(F="Android",M.unshift("desktop mode")),/Accelerated *= *true/i.test(t)&&M.unshift("accelerated")):"UC Browser"==N&&/\bUCWEB\b/.test(t)?M.push("speed mode"):"PaleMoon"==N&&(o=/\bFirefox\/([\d.]+)\b/.exec(t))?M.push("identifying as Firefox "+o[1]):"Firefox"==N&&(o=/\b(Mobile|Tablet|TV)\b/i.exec(t))?(F||(F="Firefox OS"),U||(U=o[1])):!N||(o=!/\bMinefield\b/i.test(t)&&/\b(?:Firefox|Safari)\b/.exec(N))?(N&&!U&&/[\/,]|^[^(]+?\)/.test(t.slice(t.indexOf(o+"/")+8))&&(N=null),(o=U||L||F)&&(U||L||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(F))&&(N=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(F)?F:o)+" Browser")):"Electron"==N&&(o=(/\bChrome\/([\d.]+)\b/.exec(t)||0)[1])&&M.push("Chromium "+o),j||(j=D(["(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)","Version",g(N),"(?:Firefox|Minefield|NetFront)"])),(o=("iCab"==$&&parseFloat(j)>3?"WebKit":/\bOpera\b/.test(N)&&(/\bOPR\b/.test(t)?"Blink":"Presto"))||/\b(?:Midori|Nook|Safari)\b/i.test(t)&&!/^(?:Trident|EdgeHTML)$/.test($)&&"WebKit"||!$&&/\bMSIE\b/i.test(t)&&("Mac OS"==F?"Tasman":"Trident")||"WebKit"==$&&/\bPlayStation\b(?! Vita\b)/i.test(N)&&"NetFront")&&($=[o]),"IE"==N&&(o=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(t)||0)[1])?(N+=" Mobile",F="Windows Phone "+(/\+$/.test(o)?o:o+".x"),M.unshift("desktop mode")):/\bWPDesktop\b/i.test(t)?(N="IE Mobile",F="Windows Phone 8.x",M.unshift("desktop mode"),j||(j=(/\brv:([\d.]+)/.exec(t)||0)[1])):"IE"!=N&&"Trident"==$&&(o=/\brv:([\d.]+)/.exec(t))&&(N&&M.push("identifying as "+N+(j?" "+j:"")),N="IE",j=o[1]),A){if(function(e,t){var n=null!=e?typeof e[t]:"number";return!(/^(?:boolean|number|string|undefined)$/.test(n)||"object"==n&&!e[t])}(i,"global"))if(S&&(P=(o=S.lang.System).getProperty("os.arch"),F=F||o.getProperty("os.name")+" "+o.getProperty("os.version")),k){try{j=i.require("ringo/engine").version.join("."),N="RingoJS"}catch(e){(o=i.system)&&o.global.system==i.system&&(N="Narwhal",F||(F=o[0].os||null))}N||(N="Rhino")}else"object"==typeof i.process&&!i.process.browser&&(o=i.process)&&("object"==typeof o.versions&&("string"==typeof o.versions.electron?(M.push("Node "+o.versions.node),N="Electron",j=o.versions.electron):"string"==typeof o.versions.nw&&(M.push("Chromium "+j,"Node "+o.versions.node),N="NW.js",j=o.versions.nw)),N||(N="Node.js",P=o.arch,F=o.platform,j=(j=/[\d.]+/.exec(o.version))?j[0]:null));else m(o=i.runtime)==b?(N="Adobe AIR",F=o.flash.system.Capabilities.os):m(o=i.phantom)==x?(N="PhantomJS",j=(o=o.version||null)&&o.major+"."+o.minor+"."+o.patch):"number"==typeof I.documentMode&&(o=/\bTrident\/(\d+)/i.exec(t))?(j=[j,I.documentMode],(o=+o[1]+4)!=j[1]&&(M.push("IE "+j[1]+" mode"),$&&($[1]=""),j[1]=o),j="IE"==N?String(j[1].toFixed(1)):j[0]):"number"==typeof I.documentMode&&/^(?:Chrome|Firefox)\b/.test(N)&&(M.push("masking as "+N+" "+j),N="IE",j="11.0",$=["Trident"],F="Windows");F=F&&p(F)}if(j&&(o=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(j)||/(?:alpha|beta)(?: ?\d)?/i.exec(t+";"+(A&&s.appMinorVersion))||/\bMinefield\b/i.test(t)&&"a")&&(O=/b/i.test(o)?"beta":"alpha",j=j.replace(RegExp(o+"\\+?$"),"")+("beta"==O?T:E)+(/\d+\+?/.exec(o)||"")),"Fennec"==N||"Firefox"==N&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(F))N="Firefox Mobile";else if("Maxthon"==N&&j)j=j.replace(/\.[\d.]+/,".x");else if(/\bXbox\b/i.test(U))"Xbox 360"==U&&(F=null),"Xbox 360"==U&&/\bIEMobile\b/.test(t)&&M.unshift("mobile mode");else if(!/^(?:Chrome|IE|Opera)$/.test(N)&&(!N||U||/Browser|Mobi/.test(N))||"Windows CE"!=F&&!/Mobi/i.test(t))if("IE"==N&&A)try{null===i.external&&M.unshift("platform preview")}catch(e){M.unshift("embedded")}else(/\bBlackBerry\b/.test(U)||/\bBB10\b/.test(t))&&(o=(RegExp(U.replace(/ +/g," *")+"/([.\\d]+)","i").exec(t)||0)[1]||j)?(F=((o=[o,/BB10/.test(t)])[1]?(U=null,L="BlackBerry"):"Device Software")+" "+o[0],j=null):this!=f&&"Wii"!=U&&(A&&C||/Opera/.test(N)&&/\b(?:MSIE|Firefox)\b/i.test(t)||"Firefox"==N&&/\bOS X (?:\d+\.){2,}/.test(F)||"IE"==N&&(F&&!/^Win/.test(F)&&j>5.5||/\bWindows XP\b/.test(F)&&j>8||8==j&&!/\bTrident\b/.test(t)))&&!c.test(o=e.call(f,t.replace(c,"")+";"))&&o.name&&(o="ing as "+o.name+((o=o.version)?" "+o:""),c.test(N)?(/\bIE\b/.test(o)&&"Mac OS"==F&&(F=null),o="identify"+o):(o="mask"+o,N=R?p(R.replace(/([a-z])([A-Z])/g,"$1 $2")):"Opera",/\bIE\b/.test(o)&&(F=null),A||(j=null)),$=["Presto"],M.push(o));else N+=" Mobile";(o=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(t)||0)[1])&&(o=[parseFloat(o.replace(/\.(\d)$/,".0$1")),o],"Safari"==N&&"+"==o[1].slice(-1)?(N="WebKit Nightly",O="alpha",j=o[1].slice(0,-1)):j!=o[1]&&j!=(o[2]=(/\bSafari\/([\d.]+\+?)/i.exec(t)||0)[1])||(j=null),o[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(t)||0)[1],537.36==o[0]&&537.36==o[2]&&parseFloat(o[1])>=28&&"WebKit"==$&&($=["Blink"]),A&&(l||o[1])?($&&($[1]="like Chrome"),o=o[1]||((o=o[0])<530?1:o<532?2:o<532.05?3:o<533?4:o<534.03?5:o<534.07?6:o<534.1?7:o<534.13?8:o<534.16?9:o<534.24?10:o<534.3?11:o<535.01?12:o<535.02?"13+":o<535.07?15:o<535.11?16:o<535.19?17:o<536.05?18:o<536.1?19:o<537.01?20:o<537.11?"21+":o<537.13?23:o<537.18?24:o<537.24?25:o<537.36?26:"Blink"!=$?"27":"28")):($&&($[1]="like Safari"),o=(o=o[0])<400?1:o<500?2:o<526?3:o<533?4:o<534?"4+":o<535?5:o<537?6:o<538?7:o<601?8:o<602?9:o<604?10:o<606?11:o<608?12:"12"),$&&($[1]+=" "+(o+="number"==typeof o?".x":/[.+]/.test(o)?"":"+")),"Safari"==N&&(!j||parseInt(j)>45)?j=o:"Chrome"==N&&/\bHeadlessChrome/i.test(t)&&M.unshift("headless")),"Opera"==N&&(o=/\bzbov|zvav$/.exec(F))?(N+=" ",M.unshift("desktop mode"),"zvav"==o?(N+="Mini",j=null):N+="Mobile",F=F.replace(RegExp(" *"+o+"$"),"")):"Safari"==N&&/\bChrome\b/.exec($&&$[1])?(M.unshift("desktop mode"),N="Chrome Mobile",j=null,/\bOS X\b/.test(F)?(L="Apple",F="iOS 4.3+"):F=null):/\bSRWare Iron\b/.test(N)&&!j&&(j=D("Chrome")),j&&0==j.indexOf(o=/[\d.]+$/.exec(F))&&t.indexOf("/"+o+"-")>-1&&(F=v(F.replace(o,""))),F&&-1!=F.indexOf(N)&&!RegExp(N+" OS").test(F)&&(F=F.replace(RegExp(" *"+g(N)+" *"),"")),$&&!/\b(?:Avant|Nook)\b/.test(N)&&(/Browser|Lunascape|Maxthon/.test(N)||"Safari"!=N&&/^iOS/.test(F)&&/\bSafari\b/.test($[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(N)&&$[1])&&(o=$[$.length-1])&&M.push(o),M.length&&(M=["("+M.join("; ")+")"]),L&&U&&U.indexOf(L)<0&&M.push("on "+L),U&&M.push((/^on /.test(M[M.length-1])?"":"on ")+U),F&&(o=/ ([\d.+]+)$/.exec(F),u=o&&"/"==F.charAt(F.length-o[0].length-1),F={architecture:32,family:o&&!u?F.replace(o[0],""):F,version:o?o[1]:null,toString:function(){var e=this.version;return this.family+(e&&!u?" "+e:"")+(64==this.architecture?" 64-bit":"")}}),(o=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(P))&&!/\bi686\b/i.test(P)?(F&&(F.architecture=64,F.family=F.family.replace(RegExp(" *"+o),"")),N&&(/\bWOW64\b/i.test(t)||A&&/\w(?:86|32)$/.test(s.cpuClass||s.platform)&&!/\bWin64; x64\b/i.test(t))&&M.unshift("32-bit")):F&&/^OS X/.test(F.family)&&"Chrome"==N&&parseFloat(j)>=39&&(F.architecture=64),t||(t=null);var B={};return B.description=t,B.layout=$&&$[0],B.manufacturer=L,B.name=N,B.prerelease=O,B.product=U,B.ua=t,B.version=N&&j,B.os=F||{architecture:null,family:null,version:null,toString:function(){return"null"}},B.parse=e,B.toString=function(){return this.description||""},B.version&&M.unshift(j),B.name&&M.unshift(N),F&&N&&(F!=String(F).split(" ")[0]||F!=N.split(" ")[0]&&!U)&&M.push(U?"("+F+")":"on "+F),M.length&&(B.description=M.join(" ")),B}();i&&s?f(b,(function(e,t){i[t]=e})):n.platform=b}).call(r)}(Ke,Ke.exports);var He={},Ve=Symbol("@ts-pattern/matcher"),Je="@ts-pattern/anonymous-select-key",Ge=function(e){return Boolean(e&&"object"==typeof e)},Qe=function(e){return e&&!!e[Ve]},Xe=function e(t,n,i){if(Ge(t)){if(Qe(t)){var r=t[Ve]().match(n),s=r.matched,a=r.selections;return s&&a&&Object.keys(a).forEach((function(e){return i(e,a[e])})),s}if(!Ge(n))return!1;if(Array.isArray(t))return!!Array.isArray(n)&&t.length===n.length&&t.every((function(t,r){return e(t,n[r],i)}));if(t instanceof Map)return n instanceof Map&&Array.from(t.keys()).every((function(r){return e(t.get(r),n.get(r),i)}));if(t instanceof Set){if(!(n instanceof Set))return!1;if(0===t.size)return 0===n.size;if(1===t.size){var o=Array.from(t.values())[0];return Qe(o)?Array.from(n.values()).every((function(t){return e(o,t,i)})):n.has(o)}return Array.from(t.values()).every((function(e){return n.has(e)}))}return Object.keys(t).every((function(r){var s,a=t[r];return(r in n||Qe(s=a)&&"optional"===s[Ve]().matcherType)&&e(a,n[r],i)}))}return Object.is(n,t)},Ze=function e(t){var n,i,r;return Ge(t)?Qe(t)?null!=(n=null==(i=(r=t[Ve]()).getSelectionKeys)?void 0:i.call(r))?n:[]:Array.isArray(t)?Ye(t,e):Ye(Object.values(t),e):[]},Ye=function(e,t){return e.reduce((function(e,n){return e.concat(t(n))}),[])};function et(e){var t;return(t={})[Ve]=function(){return{match:function(t){var n={},i=function(e,t){n[e]=t};return void 0===t?(Ze(e).forEach((function(e){return i(e,void 0)})),{matched:!0,selections:n}):{matched:Xe(e,t,i),selections:n}},getSelectionKeys:function(){return Ze(e)},matcherType:"optional"}},t}function tt(e){var t;return(t={})[Ve]=function(){return{match:function(t){if(!Array.isArray(t))return{matched:!1};var n={};if(0===t.length)return Ze(e).forEach((function(e){n[e]=[]})),{matched:!0,selections:n};var i=function(e,t){n[e]=(n[e]||[]).concat([t])};return{matched:t.every((function(t){return Xe(e,t,i)})),selections:n}},getSelectionKeys:function(){return Ze(e)}}},t}function nt(){var e,t=[].slice.call(arguments);return(e={})[Ve]=function(){return{match:function(e){var n={},i=function(e,t){n[e]=t};return{matched:t.every((function(t){return Xe(t,e,i)})),selections:n}},getSelectionKeys:function(){return Ye(t,Ze)},matcherType:"and"}},e}function it(){var e,t=[].slice.call(arguments);return(e={})[Ve]=function(){return{match:function(e){var n={},i=function(e,t){n[e]=t};return Ye(t,Ze).forEach((function(e){return i(e,void 0)})),{matched:t.some((function(t){return Xe(t,e,i)})),selections:n}},getSelectionKeys:function(){return Ye(t,Ze)},matcherType:"or"}},e}function rt(e){var t;return(t={})[Ve]=function(){return{match:function(t){return{matched:!Xe(e,t,(function(){}))}},getSelectionKeys:function(){return[]},matcherType:"not"}},t}function st(e){var t;return(t={})[Ve]=function(){return{match:function(t){return{matched:Boolean(e(t))}}}},t}function at(){var e,t=[].slice.call(arguments),n="string"==typeof t[0]?t[0]:void 0,i=2===t.length?t[1]:"string"==typeof t[0]?void 0:t[0];return(e={})[Ve]=function(){return{match:function(e){var t,r=((t={})[null!=n?n:Je]=e,t);return{matched:void 0===i||Xe(i,e,(function(e,t){r[e]=t})),selections:r}},getSelectionKeys:function(){return[null!=n?n:Je].concat(void 0===i?[]:Ze(i))}}},e}var ot=st((function(e){return!0})),ct=ot,ut=st((function(e){return"string"==typeof e})),lt=st((function(e){return"number"==typeof e})),dt=st((function(e){return"boolean"==typeof e})),ht=st((function(e){return"bigint"==typeof e})),pt=st((function(e){return"symbol"==typeof e})),ft=st((function(e){return null==e})),mt={__proto__:null,optional:et,array:tt,intersection:nt,union:it,not:rt,when:st,select:at,any:ot,_:ct,string:ut,number:lt,boolean:dt,bigint:ht,symbol:pt,nullish:ft,instanceOf:function(e){return st(function(e){return function(t){return t instanceof e}}(e))},typed:function(){return{array:tt,optional:et,intersection:nt,union:it,not:rt,select:at,when:st}}},gt=function(){function e(e,t){this.value=void 0,this.cases=void 0,this.value=e,this.cases=t}var t=e.prototype;return t.with=function(){var t=[].slice.call(arguments),n=t[t.length-1],i=[t[0]],r=[];return 3===t.length&&"function"==typeof t[1]?(i.push(t[0]),r.push(t[1])):t.length>2&&i.push.apply(i,t.slice(1,t.length-1)),new e(this.value,this.cases.concat([{match:function(e){var t={},n=Boolean(i.some((function(n){return Xe(n,e,(function(e,n){t[e]=n}))}))&&r.every((function(t){return t(e)})));return{matched:n,value:n&&Object.keys(t).length?Je in t?t[Je]:t:e}},handler:n}]))},t.when=function(t,n){return new e(this.value,this.cases.concat([{match:function(e){return{matched:Boolean(t(e)),value:e}},handler:n}]))},t.otherwise=function(t){return new e(this.value,this.cases.concat([{match:function(e){return{matched:!0,value:e}},handler:t}])).run()},t.exhaustive=function(){return this.run()},t.run=function(){for(var e=this.value,t=void 0,n=0;n<this.cases.length;n++){var i=this.cases[n],r=i.match(this.value);if(r.matched){e=r.value,t=i.handler;break}}if(!t){var s;try{s=JSON.stringify(this.value)}catch(e){s=this.value}throw new Error("Pattern matching error: no pattern matches value "+s)}return t(e,this.value)},e}();He.P=mt,He.Pattern=mt,He.isMatching=function(){var e=[].slice.call(arguments);if(1===e.length){var t=e[0];return function(e){return Xe(t,e,(function(){}))}}if(2===e.length){var n=e,i=n[0],r=n[1];return Xe(i,r,(function(){}))}throw new Error("isMatching wasn't given the right number of arguments: expected 1 or 2, received "+e.length+".")},He.match=function(e){return new gt(e,[])};var yt={};const vt="[a-fA-F\\d:]",bt=e=>e&&e.includeBoundaries?`(?:(?<=\\s|^)(?=${vt})|(?<=${vt})(?=\\s|$))`:"",_t="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",wt="[a-fA-F\\d]{1,4}",xt=`\n(?:\n(?:${wt}:){7}(?:${wt}|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:${wt}:){6}(?:${_t}|:${wt}|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:${wt}:){5}(?::${_t}|(?::${wt}){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:${wt}:){4}(?:(?::${wt}){0,1}:${_t}|(?::${wt}){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:${wt}:){3}(?:(?::${wt}){0,2}:${_t}|(?::${wt}){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:${wt}:){2}(?:(?::${wt}){0,3}:${_t}|(?::${wt}){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:${wt}:){1}(?:(?::${wt}){0,4}:${_t}|(?::${wt}){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::${wt}){0,5}:${_t}|(?::${wt}){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n`.replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),St=new RegExp(`(?:^${_t}$)|(?:^${xt}$)`),kt=new RegExp(`^${_t}$`),Et=new RegExp(`^${xt}$`),Tt=e=>e&&e.exact?St:new RegExp(`(?:${bt(e)}${_t}${bt(e)})|(?:${bt(e)}${xt}${bt(e)})`,"g");Tt.v4=e=>e&&e.exact?kt:new RegExp(`${bt(e)}${_t}${bt(e)}`,"g"),Tt.v6=e=>e&&e.exact?Et:new RegExp(`${bt(e)}${xt}${bt(e)}`,"g");const It=Tt,Ct=e=>It({exact:!0}).test(e);Ct.v4=e=>It.v4({exact:!0}).test(e),Ct.v6=e=>It.v6({exact:!0}).test(e),Ct.version=e=>Ct(e)?Ct.v4(e)?4:6:void 0;const Rt=Ct;class Pt extends Error{constructor(){super("Request was cancelled"),this.name="CancelError"}get isCanceled(){return!0}}const Mt={timeout:5e3},Ot={v4:["https://ipv4.icanhazip.com/","https://api.ipify.org/"],v6:["https://ipv6.icanhazip.com/","https://api6.ipify.org/"]},At=(e,t,n)=>{const i=new XMLHttpRequest;let r;const s=new Promise(((s,a)=>{r=a,i.addEventListener("error",a,{once:!0}),i.addEventListener("timeout",a,{once:!0}),i.addEventListener("load",(()=>{const e=i.responseText.trim();e&&Rt[n](e)?s(e):a()}),{once:!0}),i.open("GET",e),i.timeout=t.timeout,i.send()}));return s.cancel=()=>{i.abort(),r(new Pt)},s},jt=(e,t)=>{let n;const i=async function(){const i=[].concat.apply(Ot[e],t.fallbackUrls||[]);for(const r of i)try{n=At(r,t,e);return await n}catch(e){if(e instanceof Pt)throw e}throw new Error("Couldn't find your IP")}();return i.cancel=()=>{n.cancel()},i};yt.v4=e=>jt("v4",{...Mt,...e}),yt.v6=e=>jt("v6",{...Mt,...e});const $t=yt;var Nt=async e=>{if(e={timeout:5e3,ipVersion:4,...e},navigator&&!navigator.onLine)return!1;const t=4===e.ipVersion?"v4":"v6";try{return await $t[t](e),!0}catch(e){return!1}};var Ut={nanoid:function(){let e="",t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:21;for(;t--;)e+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return e},customAlphabet:function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:21;return function(){let n="",i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:t;for(;i--;)n+=e[Math.random()*e.length|0];return n}}},Lt={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Type=e.TypeBuilder=e.Modifier=e.Hint=e.Kind=void 0,e.Kind=Symbol.for("TypeBox.Kind"),e.Hint=Symbol.for("TypeBox.Hint"),e.Modifier=Symbol.for("TypeBox.Modifier");let t=0;class n{ReadonlyOptional(t){return{[e.Modifier]:"ReadonlyOptional",...t}}Readonly(t){return{[e.Modifier]:"Readonly",...t}}Optional(t){return{[e.Modifier]:"Optional",...t}}Any(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Any"})}Array(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.Create({...n,[e.Kind]:"Array",type:"array",items:t})}Boolean(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Boolean",type:"boolean"})}ConstructorParameters(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.Tuple([...e.parameters],{...t})}Constructor(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("Tuple"===t[e.Kind]){const r=void 0===t.items?[]:t.items;return this.Create({...i,[e.Kind]:"Constructor",type:"constructor",parameters:r,returns:n})}if(globalThis.Array.isArray(t))return this.Create({...i,[e.Kind]:"Constructor",type:"constructor",parameters:t,returns:n});throw new Error("TypeBuilder.Constructor: Invalid parameters")}Enum(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=Object.keys(t).filter((e=>isNaN(e))).map((e=>t[e])).map((t=>"string"==typeof t?{[e.Kind]:"Literal",type:"string",const:t}:{[e.Kind]:"Literal",type:"number",const:t}));return this.Create({...n,[e.Kind]:"Union",[e.Hint]:"Enum",anyOf:i})}Function(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("Tuple"===t[e.Kind]){const r=void 0===t.items?[]:t.items;return this.Create({...i,[e.Kind]:"Function",type:"function",parameters:r,returns:n})}if(globalThis.Array.isArray(t))return this.Create({...i,[e.Kind]:"Function",type:"function",parameters:t,returns:n});throw new Error("TypeBuilder.Function: Invalid parameters")}InstanceType(e){return{...arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},...this.Clone(e.returns)}}Integer(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Integer",type:"integer"})}Intersect(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=t=>t[e.Modifier]&&"Optional"===t[e.Modifier]||"ReadonlyOptional"===t[e.Modifier],[r,s]=[new Set,new Set];for(const e of t)for(const[t,n]of Object.entries(e.properties))i(n)&&s.add(t);for(const e of t)for(const t of Object.keys(e.properties))s.has(t)||r.add(t);const a={};for(const n of t)for(const[t,i]of Object.entries(n.properties))a[t]=void 0===a[t]?i:{[e.Kind]:"Union",anyOf:[a[t],{...i}]};return r.size>0?this.Create({...n,[e.Kind]:"Object",type:"object",properties:a,required:[...r]}):this.Create({...n,[e.Kind]:"Object",type:"object",properties:a})}KeyOf(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=Object.keys(t.properties).map((t=>this.Create({...n,[e.Kind]:"Literal",type:"string",const:t})));return this.Create({...n,[e.Kind]:"Union",[e.Hint]:"KeyOf",anyOf:i})}Literal(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.Create({...n,[e.Kind]:"Literal",const:t,type:typeof t})}Never(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Never",allOf:[{type:"boolean",const:!1},{type:"boolean",const:!0}]})}Null(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Null",type:"null"})}Number(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Number",type:"number"})}Object(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=Object.keys(t),r=i.filter((n=>{const i=t[n][e.Modifier];return i&&("Optional"===i||"ReadonlyOptional"===i)})),s=i.filter((e=>!r.includes(e)));return s.length>0?this.Create({...n,[e.Kind]:"Object",type:"object",properties:t,required:s}):this.Create({...n,[e.Kind]:"Object",type:"object",properties:t})}Omit(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r="Union"===n[e.Kind]?n.anyOf.map((e=>e.const)):n,s={...this.Clone(t),...i,[e.Hint]:"Omit"};s.required&&(s.required=s.required.filter((e=>!r.includes(e))),0===s.required.length&&delete s.required);for(const e of Object.keys(s.properties))r.includes(e)&&delete s.properties[e];return this.Create(s)}Parameters(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.Type.Tuple(t.parameters,{...n})}Partial(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i={...this.Clone(t),...n,[e.Hint]:"Partial"};delete i.required;for(const t of Object.keys(i.properties)){const n=i.properties[t];switch(n[e.Modifier]){case"ReadonlyOptional":case"Readonly":n[e.Modifier]="ReadonlyOptional";break;default:n[e.Modifier]="Optional"}}return this.Create(i)}Pick(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r="Union"===n[e.Kind]?n.anyOf.map((e=>e.const)):n,s={...this.Clone(t),...i,[e.Hint]:"Pick"};s.required&&(s.required=s.required.filter((e=>r.includes(e))),0===s.required.length&&delete s.required);for(const e of Object.keys(s.properties))r.includes(e)||delete s.properties[e];return this.Create(s)}Promise(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.Create({...n,[e.Kind]:"Promise",type:"promise",item:t})}Record(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if("Union"===t[e.Kind])return this.Object(t.anyOf.reduce(((e,t)=>({...e,[t.const]:n})),{}),{...i,[e.Hint]:"Record"});const r=["Integer","Number"].includes(t[e.Kind])?"^(0|[1-9][0-9]*)$":"String"===t[e.Kind]&&t.pattern?t.pattern:"^.*$";return this.Create({...i,[e.Kind]:"Record",type:"object",patternProperties:{[r]:n},additionalProperties:!1})}Recursive(n){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};void 0===i.$id&&(i.$id="T"+t++);const r=n({[e.Kind]:"Self",$ref:`${i.$id}`});return r.$id=i.$id,this.Create({...i,...r})}Ref(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(void 0===t.$id)throw Error("TypeBuilder.Ref: Referenced schema must specify an $id");return this.Create({...n,[e.Kind]:"Ref",$ref:t.$id})}RegEx(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.Create({...n,[e.Kind]:"String",type:"string",pattern:t.source})}Required(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i={...this.Clone(t),...n,[e.Hint]:"Required"};i.required=Object.keys(i.properties);for(const t of Object.keys(i.properties)){const n=i.properties[t];switch(n[e.Modifier]){case"ReadonlyOptional":case"Readonly":n[e.Modifier]="Readonly";break;default:delete n[e.Modifier]}}return this.Create(i)}ReturnType(e){return{...arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},...this.Clone(e.returns)}}Strict(e){return JSON.parse(JSON.stringify(e))}String(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"String",type:"string"})}Tuple(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=t.length,r=t.length,s=t.length>0?{...n,[e.Kind]:"Tuple",type:"array",items:t,additionalItems:!1,minItems:i,maxItems:r}:{...n,[e.Kind]:"Tuple",type:"array",minItems:i,maxItems:r};return this.Create(s)}Undefined(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Undefined",type:"object",specialized:"Undefined"})}Union(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return 0===t.length?e.Type.Never({...n}):this.Create({...n,[e.Kind]:"Union",anyOf:t})}Uint8Array(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Uint8Array",type:"object",specialized:"Uint8Array"})}Unknown(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Unknown"})}Unsafe(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:t[e.Kind]||"Unsafe"})}Void(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.Create({...t,[e.Kind]:"Void",type:"null"})}Create(e){return e}Clone(e){return"object"!=typeof(t=e)||null===t||Array.isArray(t)?(e=>"object"==typeof e&&null!==e&&Array.isArray(e))(e)?e.map((e=>this.Clone(e))):e:Object.keys(e).reduce(((t,n)=>({...t,[n]:this.Clone(e[n])})),Object.getOwnPropertySymbols(e).reduce(((t,n)=>({...t,[n]:this.Clone(e[n])})),{}));var t}}e.TypeBuilder=n,e.Type=new n}(Lt);var Ft={},qt={},Dt={},Bt={},zt={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Format=void 0,function(e){const t=new Map;e.Clear=function(){return t.clear()},e.Has=function(e){return t.has(e)},e.Set=function(e,n){t.set(e,n)},e.Get=function(e){return t.get(e)}}(e.Format||(e.Format={}))}(zt),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),n=r&&r.__exportStar||function(e,n){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(n,i)||t(n,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(zt,e)}(Bt),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueErrors=e.ValueErrorsUnknownTypeError=e.ValueErrorType=void 0;const t=Lt,n=Bt;var i;!function(e){e[e.Array=0]="Array",e[e.ArrayMinItems=1]="ArrayMinItems",e[e.ArrayMaxItems=2]="ArrayMaxItems",e[e.ArrayUniqueItems=3]="ArrayUniqueItems",e[e.Boolean=4]="Boolean",e[e.Function=5]="Function",e[e.Integer=6]="Integer",e[e.IntegerMultipleOf=7]="IntegerMultipleOf",e[e.IntegerExclusiveMinimum=8]="IntegerExclusiveMinimum",e[e.IntegerExclusiveMaximum=9]="IntegerExclusiveMaximum",e[e.IntegerMinimum=10]="IntegerMinimum",e[e.IntegerMaximum=11]="IntegerMaximum",e[e.Literal=12]="Literal",e[e.Never=13]="Never",e[e.Null=14]="Null",e[e.Number=15]="Number",e[e.NumberMultipleOf=16]="NumberMultipleOf",e[e.NumberExclusiveMinimum=17]="NumberExclusiveMinimum",e[e.NumberExclusiveMaximum=18]="NumberExclusiveMaximum",e[e.NumberMinumum=19]="NumberMinumum",e[e.NumberMaximum=20]="NumberMaximum",e[e.Object=21]="Object",e[e.ObjectMinProperties=22]="ObjectMinProperties",e[e.ObjectMaxProperties=23]="ObjectMaxProperties",e[e.ObjectAdditionalProperties=24]="ObjectAdditionalProperties",e[e.ObjectRequiredProperties=25]="ObjectRequiredProperties",e[e.Promise=26]="Promise",e[e.RecordKeyNumeric=27]="RecordKeyNumeric",e[e.RecordKeyString=28]="RecordKeyString",e[e.String=29]="String",e[e.StringMinLength=30]="StringMinLength",e[e.StringMaxLength=31]="StringMaxLength",e[e.StringPattern=32]="StringPattern",e[e.StringFormatUnknown=33]="StringFormatUnknown",e[e.StringFormat=34]="StringFormat",e[e.TupleZeroLength=35]="TupleZeroLength",e[e.TupleLength=36]="TupleLength",e[e.Undefined=37]="Undefined",e[e.Union=38]="Union",e[e.Uint8Array=39]="Uint8Array",e[e.Uint8ArrayMinByteLength=40]="Uint8ArrayMinByteLength",e[e.Uint8ArrayMaxByteLength=41]="Uint8ArrayMaxByteLength",e[e.Void=42]="Void"}(i=e.ValueErrorType||(e.ValueErrorType={}));class r extends Error{constructor(e){super("ValueErrors: Unknown type"),this.schema=e}}e.ValueErrorsUnknownTypeError=r,function(e){function*s(e,a,o,c){const u=void 0===e.$id?a:[e,...a],l=e;switch(l[t.Kind]){case"Any":case"Unknown":return yield*function*(e,t,n,i){}();case"Array":return yield*function*(e,t,n,r){if(!globalThis.Array.isArray(r))return yield{type:i.Array,schema:e,path:n,value:r,message:"Expected array"};void 0===e.minItems||r.length>=e.minItems||(yield{type:i.ArrayMinItems,schema:e,path:n,value:r,message:`Expected array length to be greater or equal to ${e.minItems}`}),void 0===e.maxItems||r.length<=e.maxItems||(yield{type:i.ArrayMinItems,schema:e,path:n,value:r,message:`Expected array length to be less or equal to ${e.maxItems}`}),!0===e.uniqueItems&&new Set(r).size!==r.length&&(yield{type:i.ArrayUniqueItems,schema:e,path:n,value:r,message:"Expected array elements to be unique"});for(let i=0;i<r.length;i++)yield*s(e.items,t,`${n}/${i}`,r[i])}(l,u,o,c);case"Boolean":return yield*function*(e,t,n,r){if("boolean"!=typeof r)return yield{type:i.Boolean,schema:e,path:n,value:r,message:"Expected boolean"}}(l,0,o,c);case"Constructor":return yield*function*(e,t,n,i){yield*s(e.returns,t,n,i.prototype)}(l,u,o,c);case"Function":return yield*function*(e,t,n,r){if("function"!=typeof r)return yield{type:i.Function,schema:e,path:n,value:r,message:"Expected function"}}(l,0,o,c);case"Integer":return yield*function*(e,t,n,r){if("number"!=typeof r)return yield{type:i.Number,schema:e,path:n,value:r,message:"Expected number"};globalThis.Number.isInteger(r)||(yield{type:i.Integer,schema:e,path:n,value:r,message:"Expected integer"}),e.multipleOf&&r%e.multipleOf!=0&&(yield{type:i.IntegerMultipleOf,schema:e,path:n,value:r,message:`Expected integer to be a multiple of ${e.multipleOf}`}),!e.exclusiveMinimum||r>e.exclusiveMinimum||(yield{type:i.IntegerExclusiveMinimum,schema:e,path:n,value:r,message:`Expected integer to be greater than ${e.exclusiveMinimum}`}),!e.exclusiveMaximum||r<e.exclusiveMaximum||(yield{type:i.IntegerExclusiveMaximum,schema:e,path:n,value:r,message:`Expected integer to be less than ${e.exclusiveMaximum}`}),!e.minimum||r>=e.minimum||(yield{type:i.IntegerMinimum,schema:e,path:n,value:r,message:`Expected integer to be greater or equal to ${e.minimum}`}),!e.maximum||r<=e.maximum||(yield{type:i.IntegerMaximum,schema:e,path:n,value:r,message:`Expected integer to be less or equal to ${e.maximum}`})}(l,0,o,c);case"Literal":return yield*function*(e,t,n,r){if(r!==e.const){const t="string"==typeof e.const?`'${e.const}'`:e.const;return yield{type:i.Literal,schema:e,path:n,value:r,message:`Expected ${t}`}}}(l,0,o,c);case"Never":return yield*function*(e,t,n,r){yield{type:i.Never,schema:e,path:n,value:r,message:"Value cannot be validated"}}(l,0,o,c);case"Null":return yield*function*(e,t,n,r){if(null!==r)return yield{type:i.Null,schema:e,path:n,value:r,message:"Expected null"}}(l,0,o,c);case"Number":return yield*function*(e,t,n,r){if("number"!=typeof r)return yield{type:i.Number,schema:e,path:n,value:r,message:"Expected number"};e.multipleOf&&r%e.multipleOf!=0&&(yield{type:i.NumberMultipleOf,schema:e,path:n,value:r,message:`Expected number to be a multiple of ${e.multipleOf}`}),!e.exclusiveMinimum||r>e.exclusiveMinimum||(yield{type:i.NumberExclusiveMinimum,schema:e,path:n,value:r,message:`Expected number to be greater than ${e.exclusiveMinimum}`}),!e.exclusiveMaximum||r<e.exclusiveMaximum||(yield{type:i.NumberExclusiveMaximum,schema:e,path:n,value:r,message:`Expected number to be less than ${e.exclusiveMaximum}`}),!e.minimum||r>=e.minimum||(yield{type:i.NumberMaximum,schema:e,path:n,value:r,message:`Expected number to be greater or equal to ${e.minimum}`}),!e.maximum||r<=e.maximum||(yield{type:i.NumberMinumum,schema:e,path:n,value:r,message:`Expected number to be less or equal to ${e.maximum}`})}(l,0,o,c);case"Object":return yield*function*(e,t,n,r){if("object"!=typeof r||null===r||globalThis.Array.isArray(r))return yield{type:i.Object,schema:e,path:n,value:r,message:"Expected object"};void 0===e.minProperties||globalThis.Object.keys(r).length>=e.minProperties||(yield{type:i.ObjectMinProperties,schema:e,path:n,value:r,message:`Expected object to have at least ${e.minProperties} properties`}),void 0===e.maxProperties||globalThis.Object.keys(r).length<=e.maxProperties||(yield{type:i.ObjectMaxProperties,schema:e,path:n,value:r,message:`Expected object to have less than ${e.minProperties} properties`});const a=globalThis.Object.keys(e.properties);if(!1===e.additionalProperties)for(const t of globalThis.Object.keys(r))a.includes(t)||(yield{type:i.ObjectAdditionalProperties,schema:e,path:`${n}/${t}`,value:r[t],message:"Unexpected property"});if(e.required&&e.required.length>0){const t=globalThis.Object.keys(r);for(const r of e.required)t.includes(r)||(yield{type:i.ObjectRequiredProperties,schema:e.properties[r],path:`${n}/${r}`,value:void 0,message:"Expected required property"})}if("object"==typeof e.additionalProperties)for(const i of globalThis.Object.keys(r))a.includes(i)||(yield*s(e.additionalProperties,t,`${n}/${i}`,r[i]));for(const i of a){const a=e.properties[i];(e.required&&e.required.includes(i)||void 0!==r[i])&&(yield*s(a,t,`${n}/${i}`,r[i]))}}(l,u,o,c);case"Promise":return yield*function*(e,t,n,r){"object"==typeof r&&"function"==typeof r.then||(yield{type:i.Promise,schema:e,path:n,value:r,message:"Expected Promise"})}(l,0,o,c);case"Record":return yield*function*(e,t,n,r){if("object"!=typeof r||null===r||globalThis.Array.isArray(r))return yield{type:i.Object,schema:e,path:n,value:r,message:"Expected object"};const[a,o]=globalThis.Object.entries(e.patternProperties)[0],c=new RegExp(a);if(!globalThis.Object.keys(r).every((e=>c.test(e)))){const t="^(0|[1-9][0-9]*)$"===a,s=t?i.RecordKeyNumeric:i.RecordKeyString,o=t?"Expected all object property keys to be numeric":"Expected all object property keys to be strings";return yield{type:s,schema:e,path:n,value:r,message:o}}for(const[e,i]of globalThis.Object.entries(r))yield*s(o,t,`${n}/${e}`,i)}(l,u,o,c);case"Ref":return yield*function*(e,t,n,i){const r=t.find((t=>t.$id===e.$ref));if(void 0===r)throw new Error(`ValueErrors.Ref: Cannot find schema with $id '${e.$ref}'.`);yield*s(r,t,n,i)}(l,u,o,c);case"Self":return yield*function*(e,t,n,i){const r=t.find((t=>t.$id===e.$ref));if(void 0===r)throw new Error(`ValueErrors.Self: Cannot find schema with $id '${e.$ref}'.`);yield*s(r,t,n,i)}(l,u,o,c);case"String":return yield*function*(e,t,r,s){if("string"!=typeof s)return yield{type:i.String,schema:e,path:r,value:s,message:"Expected string"};void 0===e.minLength||s.length>=e.minLength||(yield{type:i.StringMinLength,schema:e,path:r,value:s,message:`Expected string length greater or equal to ${e.minLength}`}),void 0===e.maxLength||s.length<=e.maxLength||(yield{type:i.StringMaxLength,schema:e,path:r,value:s,message:`Expected string length less or equal to ${e.maxLength}`}),void 0!==e.pattern&&(new RegExp(e.pattern).test(s)||(yield{type:i.StringPattern,schema:e,path:r,value:s,message:`Expected string to match pattern ${e.pattern}`}));void 0!==e.format&&(n.Format.Has(e.format)?n.Format.Get(e.format)(s)||(yield{type:i.StringFormat,schema:e,path:r,value:s,message:`Expected string to match format '${e.format}'`}):yield{type:i.StringFormatUnknown,schema:e,path:r,value:s,message:`Unknown string format '${e.format}'`})}(l,0,o,c);case"Tuple":return yield*function*(e,t,n,r){if(!globalThis.Array.isArray(r))return yield{type:i.Array,schema:e,path:n,value:r,message:"Expected Array"};if(void 0===e.items&&0!==r.length)return yield{type:i.TupleZeroLength,schema:e,path:n,value:r,message:"Expected tuple to have 0 elements"};if(r.length!==e.maxItems&&(yield{type:i.TupleLength,schema:e,path:n,value:r,message:`Expected tuple to have ${e.maxItems} elements`}),e.items)for(let i=0;i<e.items.length;i++)yield*s(e.items[i],t,`${n}/${i}`,r[i])}(l,u,o,c);case"Undefined":return yield*function*(e,t,n,r){void 0!==r&&(yield{type:i.Undefined,schema:e,path:n,value:r,message:"Expected undefined"})}(l,0,o,c);case"Union":return yield*function*(e,t,n,r){const a=[];for(const i of e.anyOf){const e=[...s(i,t,n,r)];if(0===e.length)return;a.push(...e)}for(const e of a)yield e;a.length>0&&(yield{type:i.Union,schema:e,path:n,value:r,message:"Expected value of union"})}(l,u,o,c);case"Uint8Array":return yield*function*(e,t,n,r){if(!(r instanceof globalThis.Uint8Array))return yield{type:i.Uint8Array,schema:e,path:n,value:r,message:"Expected Uint8Array"};!e.maxByteLength||r.length<=e.maxByteLength||(yield{type:i.Uint8ArrayMaxByteLength,schema:e,path:n,value:r,message:`Expected Uint8Array to have a byte length less or equal to ${e.maxByteLength}`}),!e.minByteLength||r.length>=e.minByteLength||(yield{type:i.Uint8ArrayMinByteLength,schema:e,path:n,value:r,message:`Expected Uint8Array to have a byte length greater or equal to ${e.maxByteLength}`})}(l,0,o,c);case"Void":return yield*function*(e,t,n,r){if(null!==r)return yield{type:i.Void,schema:e,path:n,value:r,message:"Expected null"}}(l,0,o,c);default:throw new r(e)}}e.Errors=function*(e,t,n){yield*s(e,t,"",n)}}(e.ValueErrors||(e.ValueErrors={}))}(Dt),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),n=r&&r.__exportStar||function(e,n){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(n,i)||t(n,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(Dt,e)}(qt);var Wt={},Kt={},Ht={};!function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TypeGuard=e.TypeGuardInvalidTypeError=void 0;const t=Lt;class n extends Error{constructor(e){super("TypeGuard: Invalid type"),this.schema=e}}e.TypeGuardInvalidTypeError=n,function(e){function i(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function r(e){return"object"==typeof e&&null!==e&&Array.isArray(e)}function s(e){try{return new RegExp(e),!0}catch{return!1}}function a(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=7&&n<=13||27===n||127===n)return!1}return!0}function o(e){return"string"==typeof e}function c(e){return"number"==typeof e}function u(e){return"boolean"==typeof e}function l(e){return void 0===e||void 0!==e&&c(e)}function d(e){return void 0===e||void 0!==e&&u(e)}function h(e){return void 0===e||void 0!==e&&o(e)}function p(e){return i(e)&&"Any"===e[t.Kind]&&h(e.$id)}function f(e){return i(e)&&"Array"===e[t.Kind]&&"array"===e.type&&h(e.$id)&&$(e.items)&&l(e.minItems)&&l(e.maxItems)&&d(e.uniqueItems)}function m(e){return i(e)&&"Boolean"===e[t.Kind]&&"boolean"===e.type&&h(e.$id)}function g(e){if(!(i(e)&&"Constructor"===e[t.Kind]&&"constructor"===e.type&&h(e.$id)&&r(e.parameters)&&$(e.returns)))return!1;for(const t of e.parameters)if(!$(t))return!1;return!0}function y(e){if(!(i(e)&&"Function"===e[t.Kind]&&"function"===e.type&&h(e.$id)&&r(e.parameters)&&$(e.returns)))return!1;for(const t of e.parameters)if(!$(t))return!1;return!0}function v(e){return i(e)&&"Integer"===e[t.Kind]&&"integer"===e.type&&h(e.$id)&&l(e.multipleOf)&&l(e.minimum)&&l(e.maximum)&&l(e.exclusiveMinimum)&&l(e.exclusiveMaximum)}function b(e){return i(e)&&"Literal"===e[t.Kind]&&h(e.$id)&&(o(e.const)||c(e.const)||u(e.const))}function _(e){return i(e)&&"Never"===e[t.Kind]&&r(e.allOf)&&2===e.allOf.length&&i(e.allOf[0])&&o(e.allOf[0].type)&&"boolean"===e.allOf[0].type&&!1===e.allOf[0].const&&i(e.allOf[1])&&o(e.allOf[1].type)&&"boolean"===e.allOf[1].type&&!0===e.allOf[1].const}function w(e){return i(e)&&"Null"===e[t.Kind]&&"null"===e.type&&h(e.$id)}function x(e){return i(e)&&"Number"===e[t.Kind]&&"number"===e.type&&h(e.$id)&&l(e.multipleOf)&&l(e.minimum)&&l(e.maximum)&&l(e.exclusiveMinimum)&&l(e.exclusiveMaximum)}function S(e){if(!(i(e)&&"Object"===e[t.Kind]&&"object"===e.type&&h(e.$id)&&i(e.properties)&&(d(e.additionalProperties)||(n=e.additionalProperties,void 0===n||$(n)))&&l(e.minProperties)&&l(e.maxProperties)))return!1;var n;for(const[t,n]of Object.entries(e.properties)){if(!a(t))return!1;if(!$(n))return!1}return!0}function k(e){return i(e)&&"Promise"===e[t.Kind]&&"promise"===e.type&&h(e.$id)&&$(e.item)}function E(e){if(!(i(e)&&"Record"===e[t.Kind]&&"object"===e.type&&h(e.$id)&&!1===e.additionalProperties&&i(e.patternProperties)))return!1;const n=Object.keys(e.patternProperties);return 1===n.length&&(!!s(n[0])&&!!$(e.patternProperties[n[0]]))}function T(e){return i(e)&&"Self"===e[t.Kind]&&h(e.$id)&&o(e.$ref)}function I(e){return i(e)&&"Ref"===e[t.Kind]&&h(e.$id)&&o(e.$ref)}function C(e){return i(e)&&"String"===e[t.Kind]&&"string"===e.type&&h(e.$id)&&l(e.minLength)&&l(e.maxLength)&&(void 0===(n=e.pattern)||void 0!==n&&o(n)&&a(n)&&s(n))&&function(e){return void 0===e||void 0!==e&&o(e)&&a(e)}(e.format);var n}function R(e){if(!(i(e)&&"Tuple"===e[t.Kind]&&"array"===e.type&&h(e.$id)&&c(e.minItems)&&c(e.maxItems)&&e.minItems===e.maxItems))return!1;if(void 0===e.items&&void 0===e.additionalItems&&0===e.minItems)return!0;if(!r(e.items))return!1;for(const t of e.items)if(!$(t))return!1;return!0}function P(e){return i(e)&&"Undefined"===e[t.Kind]&&"object"===e.type&&h(e.$id)&&"Undefined"===e.specialized}function M(e){if(!(i(e)&&"Union"===e[t.Kind]&&r(e.anyOf)&&h(e.$id)))return!1;for(const t of e.anyOf)if(!$(t))return!1;return!0}function O(e){return i(e)&&"Uint8Array"===e[t.Kind]&&"object"===e.type&&h(e.$id)&&"Uint8Array"===e.specialized&&l(e.minByteLength)&&l(e.maxByteLength)}function A(e){return i(e)&&"Unknown"===e[t.Kind]&&h(e.$id)}function j(e){return i(e)&&"Void"===e[t.Kind]&&"null"===e.type&&h(e.$id)}function $(e){return p(e)||f(e)||m(e)||g(e)||y(e)||v(e)||b(e)||_(e)||w(e)||x(e)||S(e)||k(e)||E(e)||T(e)||I(e)||C(e)||R(e)||P(e)||M(e)||O(e)||A(e)||j(e)}e.TAny=p,e.TArray=f,e.TBoolean=m,e.TConstructor=g,e.TFunction=y,e.TInteger=v,e.TLiteral=b,e.TNever=_,e.TNull=w,e.TNumber=x,e.TObject=S,e.TPromise=k,e.TRecord=E,e.TSelf=T,e.TRef=I,e.TString=C,e.TTuple=R,e.TUndefined=P,e.TUnion=M,e.TUint8Array=O,e.TUnknown=A,e.TVoid=j,e.TSchema=$,e.Assert=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];if(!$(e))throw new n(e);for(const e of t)if(!$(e))throw new n(e)}}(e.TypeGuard||(e.TypeGuard={}))}(Ht),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),n=r&&r.__exportStar||function(e,n){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(n,i)||t(n,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),n(Ht,e)}(Kt),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TypeCompiler=e.TypeCompilerUnknownTypeError=e.Property=e.TypeCheck=void 0;const t=qt,n=Kt,i=Bt,r=Lt;class s{constructor(e,t,n,i){this.schema=e,this.references=t,this.checkFunc=n,this.code=i}Code(){return this.code}Errors(e){return t.ValueErrors.Errors(this.schema,this.references,e)}Check(e){return this.checkFunc(e)}}var a;e.TypeCheck=s,function(e){function t(e){return 36===e}function n(e){return 95===e}function i(e){return e>=48&&e<=57}function r(e){return e>=65&&e<=90||e>=97&&e<=122}e.Check=function(e){if(0===e.length)return!1;{const i=e.charCodeAt(0);if(!(t(i)||n(i)||r(i)))return!1}for(let s=1;s<e.length;s++){const a=e.charCodeAt(s);if(!(t(a)||n(a)||r(a)||i(a)))return!1}return!0}}(a=e.Property||(e.Property={}));class o extends Error{constructor(e){super("TypeCompiler: Unknown type"),this.schema=e}}e.TypeCompilerUnknownTypeError=o,function(e){function*t(e,i){if(e.$id&&!l.has(e.$id)){l.add(e.$id);const t=p(e.$id),n=f(t,e,"value");return s=n,u.add(s),void(yield`(${t}(${i}))`)}var s;const d=e;switch(d[r.Kind]){case"Any":case"Unknown":return yield*function*(e,t){yield"(true)"}();case"Array":return yield*function*(e,t){const n=h(e.items,"value");void 0!==e.minItems&&(yield`(${t}.length >= ${e.minItems})`),void 0!==e.maxItems&&(yield`(${t}.length <= ${e.maxItems})`),void 0!==e.uniqueItems&&(yield`(new Set(${t}).size === ${t}.length)`),yield`(Array.isArray(${t}) && ${t}.every(value => ${n}))`}(d,i);case"Boolean":return yield*function*(e,t){yield`(typeof ${t} === 'boolean')`}(0,i);case"Constructor":return yield*function*(e,n){yield*t(e.returns,`${n}.prototype`)}(d,i);case"Function":return yield*function*(e,t){yield`(typeof ${t} === 'function')`}(0,i);case"Integer":return yield*function*(e,t){yield`(typeof ${t} === 'number' && Number.isInteger(${t}))`,void 0!==e.multipleOf&&(yield`(${t} % ${e.multipleOf} === 0)`),void 0!==e.exclusiveMinimum&&(yield`(${t} > ${e.exclusiveMinimum})`),void 0!==e.exclusiveMaximum&&(yield`(${t} < ${e.exclusiveMaximum})`),void 0!==e.minimum&&(yield`(${t} >= ${e.minimum})`),void 0!==e.maximum&&(yield`(${t} <= ${e.maximum})`)}(d,i);case"Literal":return yield*function*(e,t){"number"==typeof e.const||"boolean"==typeof e.const?yield`(${t} === ${e.const})`:yield`(${t} === '${e.const}')`}(d,i);case"Never":return yield*function*(e,t){yield"(false)"}();case"Null":case"Void":return yield*function*(e,t){yield`(${t} === null)`}(0,i);case"Number":return yield*function*(e,t){yield`(typeof ${t} === 'number')`,void 0!==e.multipleOf&&(yield`(${t} % ${e.multipleOf} === 0)`),void 0!==e.exclusiveMinimum&&(yield`(${t} > ${e.exclusiveMinimum})`),void 0!==e.exclusiveMaximum&&(yield`(${t} < ${e.exclusiveMaximum})`),void 0!==e.minimum&&(yield`(${t} >= ${e.minimum})`),void 0!==e.maximum&&(yield`(${t} <= ${e.maximum})`)}(d,i);case"Object":return yield*function*(e,i){yield`(typeof ${i} === 'object' && ${i} !== null && !Array.isArray(${i}))`,void 0!==e.minProperties&&(yield`(Object.keys(${i}).length >= ${e.minProperties})`),void 0!==e.maxProperties&&(yield`(Object.keys(${i}).length <= ${e.maxProperties})`);const r=globalThis.Object.keys(e.properties);if(!1===e.additionalProperties)if(e.required&&e.required.length===r.length)yield`(Object.keys(${i}).length === ${r.length})`;else{const e=`[${r.map((e=>`'${e}'`)).join(", ")}]`;yield`(Object.keys(${i}).every(key => ${e}.includes(key)))`}if(n.TypeGuard.TSchema(e.additionalProperties)){const t=h(e.additionalProperties,"value[key]"),n=`[${r.map((e=>`'${e}'`)).join(", ")}]`;yield`(Object.keys(${i}).every(key => ${n}.includes(key) || ${t}))`}for(const n of r){const r=a.Check(n)?`${i}.${n}`:`${i}['${n}']`,s=e.properties[n];if(e.required&&e.required.includes(n))yield*t(s,r);else{const e=h(s,r);yield`(${r} === undefined ? true : (${e}))`}}}(d,i);case"Promise":return yield*function*(e,t){yield`(typeof value === 'object' && typeof ${t}.then === 'function')`}(0,i);case"Record":return yield*function*(e,t){yield`(typeof ${t} === 'object' && ${t} !== null && !Array.isArray(${t}))`;const[n,i]=globalThis.Object.entries(e.patternProperties)[0],r=m(`new RegExp(/${n}/)`);yield`(Object.keys(${t}).every(key => ${r}.test(key)))`;const s=h(i,"value");yield`(Object.values(${t}).every(value => ${s}))`}(d,i);case"Ref":return yield*function*(e,n){if(l.has(e.$ref))return yield`(${p(e.$ref)}(${n}))`;if(!c.has(e.$ref))throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${e.$ref}'`);const i=c.get(e.$ref);yield*t(i,n)}(d,i);case"Self":return yield*function*(e,t){const n=p(e.$ref);yield`(${n}(${t}))`}(d,i);case"String":return yield*function*(e,t){if(yield`(typeof ${t} === 'string')`,void 0!==e.minLength&&(yield`(${t}.length >= ${e.minLength})`),void 0!==e.maxLength&&(yield`(${t}.length <= ${e.maxLength})`),void 0!==e.pattern){const n=m(`new RegExp(/${e.pattern}/);`);yield`(${n}.test(${t}))`}void 0!==e.format&&(yield`(format('${e.format}', ${t}))`)}(d,i);case"Tuple":return yield*function*(e,t){if(yield`(Array.isArray(${t}))`,void 0===e.items)return yield`(${t}.length === 0)`;yield`(${t}.length === ${e.maxItems})`;for(let n=0;n<e.items.length;n++){const i=h(e.items[n],`${t}[${n}]`);yield`(${i})`}}(d,i);case"Undefined":return yield*function*(e,t){yield`(${t} === undefined)`}(0,i);case"Union":return yield*function*(e,t){const n=e.anyOf.map((e=>h(e,t)));yield`(${n.join(" || ")})`}(d,i);case"Uint8Array":return yield*function*(e,t){yield`(${t} instanceof Uint8Array)`,e.maxByteLength&&(yield`(${t}.length <= ${e.maxByteLength})`),e.minByteLength&&(yield`(${t}.length >= ${e.minByteLength})`)}(d,i);default:throw new o(e)}}const c=new Map,u=new Set,l=new Set;function d(){c.clear(),u.clear(),l.clear()}function h(e,n){return[...t(e,n)].join(" && ")}function p(e){return`check_${e.replace(/-/g,"_")}`}function f(e,n,i){return`function ${e}(value) {\n return (\n${[...t(n,i)].map((e=>` ${e}`)).join(" &&\n")}\n )\n}`}function m(e){const t=`local_${u.size}`;return u.add(`const ${t} = ${e}`),t}function g(){return[...u.values()]}function y(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];d(),function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];for(const t of e){if(!t.$id)throw new Error("TypeCompiler: Referenced schemas must specify an $id.");if(c.has(t.$id))throw new Error(`TypeCompiler: Duplicate schema $id found for '${t.$id}'`);c.set(t.$id,t)}}(t);const n=f("check",e,"value");return`${g().join("\n")}\nreturn ${n}`}e.Compile=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];n.TypeGuard.Assert(e,t);const r=y(e,t),a=globalThis.Function("format",r)(((e,t)=>{if(!i.Format.Has(e))return!1;return i.Format.Get(e)(t)}));return new s(e,t,a,r)}}(e.TypeCompiler||(e.TypeCompiler={}))}(Wt),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var r=Object.getOwnPropertyDescriptor(t,n);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,r)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),n=r&&r.__exportStar||function(e,n){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(n,i)||t(n,e,i)};Object.defineProperty(e,"__esModule",{value:!0}),e.ValueErrorType=void 0;var i=qt;Object.defineProperty(e,"ValueErrorType",{enumerable:!0,get:function(){return i.ValueErrorType}}),n(Wt,e)}(Ft);var Vt={},Jt={},Gt=r&&r.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.StateMachine=void 0;var Qt=function(){function e(e){var t,n,i=this;if(this._configuration={},this._listeners=new Set,this._scopeStack=[],"function"!=typeof e)throw new Error("The StateMachine constructor expects a callback as the first argument");if(this._scopeStack.unshift("config"),e({initialState:function(e){i._checkConfigScope(),i._currentState=e},state:function(e,t){i._checkConfigScope();var n={on:{}};i._scopeStack.unshift("state"),t({onEnter:function(e){i._checkStateScope("onEnter"),n.onEnter=e},onExit:function(e){i._checkStateScope("onExit"),n.onExit=e},on:function(e,t){i._checkStateScope("on"),n.on[e]=t}}),i._scopeStack.shift(),i._configuration[e]=n}}),this._scopeStack.shift(),void 0===this._currentState)throw new Error("No initial state provided");if(0===Object.keys(this._configuration).length)throw new Error("No state definition was provided");null===(n=null===(t=this._configuration[this._currentState.type])||void 0===t?void 0:t.onEnter)||void 0===n||n.call(t,{state:this._currentState})}return e.prototype.transition=function(e){var t,n,i,r,s,a=this._configuration[this._currentState.type];if(a){var o=a.on[e.type];if(o){var c=o({state:this._currentState,event:e,transitionTo:function(e,t){return{state:e,sideEffect:null!=t?t:null}},dontTransition:function(e){return{state:null,sideEffect:null!=e?e:null}}}),u=c.state,l=c.sideEffect,d=this._currentState;null!==u&&(null===(i=a.onExit)||void 0===i||i.call(a,{state:this._currentState}),this._currentState=u,null===(s=null===(r=this._configuration[u.type])||void 0===r?void 0:r.onEnter)||void 0===s||s.call(r,{state:u}));try{for(var h=Gt(this._listeners),p=h.next();!p.done;p=h.next()){(0,p.value)(d,null!=u?u:d,e)}}catch(e){t={error:e}}finally{try{p&&!p.done&&(n=h.return)&&n.call(h)}finally{if(t)throw t.error}}l&&setTimeout((function(){null==l||l()}),0)}}},e.prototype.subscribe=function(e){var t=this;return this._listeners.add(e),e(null,this._currentState,null),function(){t._listeners.delete(e)}},Object.defineProperty(e.prototype,"state",{get:function(){return this._currentState},enumerable:!1,configurable:!0}),e.prototype._checkConfigScope=function(){if("config"!==this._scopeStack[0])throw new Error("Call to `initialState` is allowed only from within the config callback, but not inside a state callback")},e.prototype._checkStateScope=function(e){if("state"!==this._scopeStack[0])throw new Error("Call to `".concat(e,"` is allowed only from within a state callback"))},e}();function Xt(e,t){if(t?.message&&"string"==typeof t.message)return t.message;switch(e.statusCode){case 429:return"Throttled by server";case 404:return"Not found from server";default:return"Error from server"}}function Zt(e){return e?.code??0}function Yt(e,t){return 409===e.statusCode?new Error(`${Xt(e,t)} ${e.statusCode}:${Zt(t)} ${t}`):e.statusCode?new Error(`${Xt(e,t)} ${e.statusCode}:${Zt(t)}`):e instanceof We&&"transportDisconnected"===e.errorInfo.reason?e:new Error(t?.message??e.message??"Unexpected error")}Jt.StateMachine=Qt,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.StateMachine=void 0;var t=Jt;Object.defineProperty(e,"StateMachine",{enumerable:!0,get:function(){return t.StateMachine}})}(Vt),
|
189
|
-
/*
|
190
|
-
@license
|
191
|
-
The following license applies to all parts of this software except as
|
192
|
-
documented below.
|
193
|
-
|
194
|
-
Copyright (c) 2016, Twilio, inc.
|
195
|
-
All rights reserved.
|
196
|
-
|
197
|
-
Redistribution and use in source and binary forms, with or without
|
198
|
-
modification, are permitted provided that the following conditions are
|
199
|
-
met:
|
200
|
-
|
201
|
-
1. Redistributions of source code must retain the above copyright
|
202
|
-
notice, this list of conditions and the following disclaimer.
|
203
|
-
|
204
|
-
2. Redistributions in binary form must reproduce the above copyright
|
205
|
-
notice, this list of conditions and the following disclaimer in
|
206
|
-
the documentation and/or other materials provided with the
|
207
|
-
distribution.
|
208
|
-
|
209
|
-
3. Neither the name of Twilio nor the names of its contributors may
|
210
|
-
be used to endorse or promote products derived from this software
|
211
|
-
without specific prior written permission.
|
212
|
-
|
213
|
-
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
214
|
-
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
215
|
-
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
216
|
-
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
217
|
-
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
218
|
-
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
219
|
-
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
220
|
-
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
221
|
-
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
222
|
-
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
223
|
-
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
224
|
-
|
225
|
-
This software includes javascript-state-machine under the following license.
|
226
|
-
|
227
|
-
Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
|
228
|
-
|
229
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
230
|
-
of this software and associated documentation files (the "Software"), to deal
|
231
|
-
in the Software without restriction, including without limitation the rights
|
232
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
233
|
-
copies of the Software, and to permit persons to whom the Software is
|
234
|
-
furnished to do so, subject to the following conditions:
|
235
|
-
|
236
|
-
The above copyright notice and this permission notice shall be included in all
|
237
|
-
copies or substantial portions of the Software.
|
238
|
-
|
239
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
240
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
241
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
242
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
243
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
244
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
245
|
-
|
246
|
-
This software includes loglevel under the following license.
|
247
|
-
|
248
|
-
Copyright (c) 2013 Tim Perry
|
249
|
-
|
250
|
-
Permission is hereby granted, free of charge, to any person
|
251
|
-
obtaining a copy of this software and associated documentation
|
252
|
-
files (the "Software"), to deal in the Software without
|
253
|
-
restriction, including without limitation the rights to use,
|
254
|
-
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
255
|
-
copies of the Software, and to permit persons to whom the
|
256
|
-
Software is furnished to do so, subject to the following
|
257
|
-
conditions:
|
258
|
-
|
259
|
-
The above copyright notice and this permission notice shall be
|
260
|
-
included in all copies or substantial portions of the Software.
|
261
|
-
|
262
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
263
|
-
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
264
|
-
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
265
|
-
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
266
|
-
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
267
|
-
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
268
|
-
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
269
|
-
OTHER DEALINGS IN THE SOFTWARE.
|
270
|
-
|
271
|
-
|
272
|
-
*/
|
273
|
-
function(e){var t=void 0!==t?t:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};Object.defineProperty(e,"__esModule",{value:!0});var n=Ie,i=te,r=He,s=Nt,a=Ut,o=Lt,c=Ft,u=Vt;function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function d(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var h=d(Ke.exports),p=l(s);class f{message;#h=null;#p;#f=new n.Deferred;constructor(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.message=e,this.#h=i,this.#p=setTimeout((()=>{if(this.#f.isDone)return;const e=new n.ErrorInfo("timeout",`Request timeout: ${this.message.id}`);this.#f.reject(new n.TwilioError(e)),this.#h?.(this)}),t)}get promise(){return this.#f.promise}complete(e){this.#f.isDone||(clearTimeout(this.#p),this.#f.resolve(e),this.#h?.(this))}cancel(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new n.ErrorInfo("cancelled","Request has been cancelled");this.#f.isDone||(clearTimeout(this.#p),this.#f.reject(new n.TwilioError(e)),this.#h?.(this))}}const m=new n.Logger("twilsock","Twilsock"),g=new TextEncoder,y=new TextDecoder,v=t.WebSocket??{};class b extends i.ReplayEventSubject{#m=null;#g="disconnected";#y=[];#t;constructor(){const e=new i.ReplayEventEmitter;super(e),this.#t=e}connect(e){if(m.info(`Call to Transport.connect(${e})`),"disconnected"===this.#g){this.#g="connecting";try{this.#m=new v(e)}catch(e){return m.error("Error in Transport.connect:",e),void this.#v(new n.ErrorInfo("unknown","Error in Transport.connect"))}this.#m.binaryType="arraybuffer",this.#b("open",(()=>{m.info('WebSocket "open" event'),this.#g="connected",this.#t.emitNextTick("connected")})),this.#b("error",(e=>{m.info('WebSocket "error" event:',e),this.#v(new n.ErrorInfo("unknown","Failed to connect WebSocket"))})),this.#b("close",(e=>{m.info('WebSocket "close" event:',e),this.#v(new n.ErrorInfo("transportDisconnected",'WebSocket "close" event received'))})),this.#b("message",(e=>{m.info('WebSocket "message" event:',y.decode(e.data));const t=e.data;t instanceof ArrayBuffer&&this.#t.emitNextTick("messageReceived",t)}))}else m.warn(`Cannot connect in state "${this.#g}". Ignored.`)}sendMessage(e){m.info(`Call to Transport.sendMessage(${y.decode(e)})`);const t=new Error("Transport is not ready. Call `connect()` first");if(null===this.#m)throw t;try{this.#m.send(e)}catch{throw t}}disconnect(e){this.#v(new n.ErrorInfo("transportDisconnected",`Transport.Disconnect called: ${e}`))}#v(e){m.info(`Call to Transport.doDisconnect(${e}): ${this.#g}`),"disconnected"!==this.#g&&(this.#g="disconnected",this.#m?.close(),this.#_(),this.#t.emitNextTick("disconnected",e))}#b(e,t){this.#m?.addEventListener(e,t),this.#y.push([e,t])}#_(){for(const[e,t]of this.#y)this.#m?.removeEventListener(e,t);this.#y=[]}}class _{retryPolicy;url;activeGrant;logLevel;clientMetadata;tweaks;token;continuationToken;initRegistrations;constructor(e,t,n){const i=`wss://tsock.${n.region??"us1"}.twilio.com/v3/wsconnect`,r=n.twilsock??{};var s;this.token=e,this.continuationToken=n.continuationToken??null,this.activeGrant=t,this.url=r.uri??i,this.logLevel=n.logLevel??"error",this.retryPolicy=n.retryPolicy??{min:1e3,max:12e4,randomness:.2},this.clientMetadata=(s=n.clientMetadata??{},{env:h.name??"unknown",envv:h.version??"unknown",os:h.os?.family??"unknown",osv:h.os?.version??"unknown",osa:String(h.os?.architecture??"unknown"),sdk:"js-default",...s}),this.clientMetadata.ver="1.0.0-rc.8",this.initRegistrations=new Set,this.tweaks=n.tweaks??null}}class w extends i.ReplayEventSubject{#p=null;#w=!0;#t;constructor(){const e=new i.ReplayEventEmitter;super(e),this.#t=e}get isNetworkAvailable(){return this.#w}start(){null===this.#p&&(this.#t.emitNextTick("changed",this.#w),this.#x())}stop(){var e;null!==this.#p&&("number"==typeof(e=this.#p)&&"function"==typeof t.clearTimeout?t.clearTimeout(e):function(e){e&&"function"==typeof e.close&&e.close()}(e),this.#p=null)}#x(){const e=this.#w;p.default().then((e=>{this.#w=e})).catch((e=>{m.warn("Error on checking connectivity",e),this.#w=!1})).finally((()=>{e!==this.#w&&this.#t.emitNextTick("changed",this.#w),this.#p=setTimeout((()=>{this.#x()}),5e3)}))}}const x=o.Type.Union([o.Type.Literal("init"),o.Type.Literal("update"),o.Type.Literal("ping"),o.Type.Literal("close"),o.Type.Literal("notification"),o.Type.Literal("message"),o.Type.Literal("reply"),o.Type.Literal("client_update")]),S=o.Type.Object({method:x,id:o.Type.String(),payload_size:o.Type.Optional(o.Type.Number()),payload_type:o.Type.Optional(o.Type.String())}),k=c.TypeCompiler.Compile(S),E="TWILSOCK V3.0",T=a.customAlphabet("1234567890abcdef",32);class Message{method;headers;payloadType;payload;id;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"",i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"",r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:`RQ${T()}`;this.method=e,this.headers=t,this.payloadType=n,this.payload=i,this.id=r}encode(){const e={method:this.method,id:this.id};""!==this.payload&&(e.payload_size=g.encode(this.payload).length,e.payload_type=this.payloadType);const t=JSON.stringify({...this.headers??{},...e}),n=g.encode(t).length,i=""===this.payload?"":"\r\n";return g.encode(`${E} ${n}\r\n${t}\r\n${this.payload}${i}`)}static parse(e){const t=y.decode(e);if(!t.startsWith(E))throw new Error("Invalid Twilsock prefix");const[n,i,r]=t.split("\r\n"),s=Number(n.split(" ")[2]);if(i.length!==s)throw new Error(`Invalid header size: expected ${s}, got ${i.length}`);const a=JSON.parse(i);if(!k.Check(a))throw new Error("Invalid headers received");const o=a.payload_type??"";return new Message(a.method,a,o,r,a.id)}}class I{product;type;notification_protocol_version;message_types;constructor(e){let{product:t,type:n="ers",notification_protocol_version:i=4,message_types:r=[]}=e;this.product=t,this.type=n,this.notification_protocol_version=i,this.message_types=r,Object.freeze(r)}}const C=o.Type.Object({code:o.Type.Number(),status:o.Type.String(),errorCode:o.Type.Optional(o.Type.Number()),description:o.Type.Optional(o.Type.String())}),R=o.Type.Object({status:C,http_status:o.Type.Optional(C),continuation_token:o.Type.Optional(o.Type.String()),http_headers:o.Type.Optional(o.Type.Record(o.Type.String(),o.Type.String()))}),P=c.TypeCompiler.Compile(R),M=o.Type.Object({backoff_policy:o.Type.Optional(o.Type.Object({reconnect_min_ms:o.Type.Optional(o.Type.Number()),reconnect_max_ms:o.Type.Optional(o.Type.Number())}))}),O=c.TypeCompiler.Compile(M);class A extends Message{replyHeaders;replyPayload;constructor(e,t,n,i){if(super("reply",t,n,i,e),!P.Check(t))throw new Error("Invalid reply headers passed");let r,s;this.replyHeaders={status:t.status,httpStatus:t.http_status??{code:200,status:"ok"},continuationToken:t.continuation_token??"",httpHeaders:t.http_headers??{}};try{const e=JSON.parse(i);O.Check(e)&&(r=e.backoff_policy?.reconnect_min_ms,s=e.backoff_policy?.reconnect_max_ms)}catch{}finally{this.replyPayload={backoffPolicy:{reconnectMinMs:r??1e3,reconnectMaxMs:s??2e3}}}}}class j{capabilities;token;continuation_token;registrations;tweaks;metadata;constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,s=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null;this.capabilities=e,this.token=t,this.continuation_token=n,this.registrations=i,this.tweaks=r,this.metadata=s,Object.freeze(i),Object.freeze(r),Object.freeze(s)}}class ${host;path;method;params;headers;constructor(e,t,n,i,r){this.host=e,this.path=t,this.method=n,this.params=i,this.headers=r,Object.freeze(i),Object.freeze(r)}static from(e){const t=new URL(e.url),n=[...new URLSearchParams(t.searchParams).entries()].reduce(((e,t)=>{let[n,i]=t;return{...e,[n]:i}}),{});return new $(t.host,t.pathname,e.method,n,e.headers)}}class N{active_grant;http_request;constructor(e,t){this.active_grant=e,this.http_request=t,Object.freeze(t)}}const U=o.Type.Object({status:C}),L=c.TypeCompiler.Compile(U);class F extends Message{status;constructor(e,t,n,i){if(super("close",t,n,i,e),!L.Check(t))throw new Error("Invalid close headers passed");this.status=t.status}}const q=o.Type.Object({client_update_type:o.Type.Optional(o.Type.String())}),D=c.TypeCompiler.Compile(q);class B extends Message{clientUpdateType;constructor(e,t,n,i){if(super("client_update",t,n,i,e),!D.Check(t))throw new Error("Invalid client update headers passed");this.clientUpdateType=t.client_update_type??""}}const z=o.Type.Object({message_type:o.Type.Optional(o.Type.String())}),W=c.TypeCompiler.Compile(z);class K extends Message{messageType;constructor(e,t,n,i){if(super("notification",t,n,i,e),!W.Check(t))throw new Error("Invalid notification headers passed");this.messageType=t.message_type??""}}class H{statusCode;status;headers;payload;constructor(e,t,n,i){this.statusCode=e,this.status=t,this.headers=n,this.payload=i,Object.freeze(n)}}const V=o.Type.Object({message:o.Type.String()}),J=c.TypeCompiler.Compile(V),G=Math.sqrt(5),Q=(1+G)/2,X=1e4,Z={code:200,status:"Ok"},Y={code:400,status:"Bad Request"},ee=20104,ne=(e,t)=>new n.ErrorInfo(t,e.status,e.code,e.errorCode,e.description);class ie extends i.ReplayEventSubject{#S;static connecting="connecting";static connected="connected";static disconnected="disconnected";static fatalError="fatalError";static nonFatalError="nonFatalError";static tokenExpired="tokenExpired";static tokenAboutToExpire="tokenAboutToExpire";static messageReceived="messageReceived";constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=new i.ReplayEventEmitter;super(r),this.#S=new re(e,t,n,r)}connect(){this.#S.connect()}disconnect(){this.#S.disconnect()}sendRequest(e){return this.#S.sendRequest(e)}updateToken(e){return this.#S.updateToken(e)}populateInitRegistrations(e){this.#S.populateInitRegistrations(e)}}class re extends i.ReplayEventSubject{fsm;pendingRequests=new Map;config;failedReconnectionAttempts=0;#k=new Map;#E=new w;#t;#m=null;#T=null;constructor(e,t,i,r){super(r),this.#t=r,this.config=new _(e,t,i),i.logLevel&&m.setLevel(i.logLevel);const s=e=>{let{event:t,dontTransition:n}=e;return n((()=>{this.#I(t.message)}))},a=e=>{let{transitionTo:t}=e;return t({type:"disconnected",errorInfo:new n.ErrorInfo("unknown","Disconnect called")})},o=e=>{let{event:t,transitionTo:n}=e;return n({type:"waitAndReconnect"},(()=>{this.#t.emitNextTick("nonFatalError",t.errorInfo)}))},c=e=>{let{transitionTo:t}=e;return t({type:"waitAndReconnect"},(()=>{this.#t.emitNextTick("nonFatalError",new n.ErrorInfo("networkBecameUnreachable","Network became unreachable"))}))},l=e=>{let{event:t,transitionTo:n}=e;return n({type:"disconnected",errorInfo:t.errorInfo},(()=>{this.#t.emitNextTick("fatalError",t.errorInfo)}))};this.fsm=new u.StateMachine((e=>{let{initialState:t,state:i}=e;t({type:"disconnected",errorInfo:new n.ErrorInfo("unknown","Twilsock created")}),i("disconnected",(e=>{let{onEnter:t,onExit:i,on:r}=e;t((e=>{let{state:t}=e;this.failedReconnectionAttempts=0,this.#E.stop(),this.#C(t.errorInfo),this.#R(t.errorInfo),this.#P(),this.#t.emitNextTick("disconnected",t.errorInfo.message)})),i((()=>{this.#E.start()})),r("connect",(e=>{let{transitionTo:t}=e;return t({type:"connecting"})})),r("updateToken",(e=>{let{event:t,transitionTo:i}=e;return this.config.token=t.token,t.request.cancel(new n.ErrorInfo("tokenUpdatedLocally")),i({type:"connecting"})})),r("sendRequest",(e=>{let{event:t,dontTransition:i}=e;const r=new n.ErrorInfo("transportDisconnected","Cannot send request in the disconnected state");return t.request.cancel(r),i()}))})),i("connecting",(e=>{let{onEnter:t,on:i}=e;t((()=>{this.#M(),this.#t.emitNextTick("connecting")})),i("updateToken",(e=>{let{event:t,dontTransition:i}=e;const r=new n.ErrorInfo("tokenUpdatedLocally");return this.config.token=t.token,t.request.cancel(r),i()})),i("sendRequest",(e=>{let{event:t,dontTransition:n}=e;return this.#O(t.request),n()})),i("transportConnected",(e=>{let{transitionTo:t}=e;return t({type:"initializing"})})),i("disconnect",(e=>a(e))),i("networkBecameUnreachable",(e=>c(e))),i("nonFatalError",(e=>o(e))),i("fatalError",(e=>l(e)))})),i("initializing",(e=>{let t,{onEnter:i,onExit:r,on:u}=e;i((()=>{t=this.#A(2e3),t.promise.then((()=>{m.debug("Init message received"),this.fsm.transition({type:"initMessageReceived"})})).catch((e=>{if(e instanceof n.TwilioError&&"timeout"===e.errorInfo.reason)return void this.#j();const t=e instanceof n.ErrorInfo?e.description:J.Check(e)?e.message:"unknown error",i=new n.ErrorInfo("unknown",`Init request failed: ${t}`);this.fsm.transition({type:"fatalError",errorInfo:i})})),this.#$(t)})),r((()=>{t.cancel()})),u("timeout",(e=>{let{transitionTo:t}=e;return t({type:"waitAndReconnect"},(()=>{const e=new n.ErrorInfo("timeout");this.#t.emitNextTick("nonFatalError",e)}))})),u("updateToken",(e=>{let{event:t,dontTransition:n}=e;return this.config.token=t.token,this.#O(t.request),n()})),u("sendRequest",(e=>{let{event:t,dontTransition:n}=e;return this.#O(t.request),n()})),u("initMessageReceived",(e=>{let{transitionTo:t}=e;return t({type:"connected"})})),u("tooManyRequests",(e=>{let{event:t,transitionTo:n}=e;return n({type:"waitAndReconnect",waitTime:t.waitTime},(()=>{this.#t.emitNextTick("nonFatalError",t.errorInfo)}))})),u("messageReceived",(e=>s(e))),u("disconnect",(e=>a(e))),u("networkBecameUnreachable",(e=>c(e))),u("nonFatalError",(e=>o(e))),u("fatalError",(e=>l(e)))})),i("connected",(e=>{let{onEnter:t,onExit:n,on:i}=e;t((()=>{this.failedReconnectionAttempts=0,this.#N(),this.#U(),this.#t.emitNextTick("connected")})),n((()=>{this.#L()})),i("updateToken",(e=>{let{event:t,dontTransition:n}=e;return this.config.token=t.token,this.#$(t.request),n()})),i("sendRequest",(e=>{let{event:t,dontTransition:n}=e;return this.#$(t.request),n()})),i("tooManyRequests",(e=>{let{event:t,transitionTo:n}=e;return n({type:"throttling",waitTime:t.waitTime},(()=>{this.#t.emitNextTick("nonFatalError",t.errorInfo)}))})),i("messageReceived",(e=>s(e))),i("disconnect",(e=>a(e))),i("networkBecameUnreachable",(e=>c(e))),i("nonFatalError",(e=>o(e))),i("fatalError",(e=>l(e)))})),i("waitAndReconnect",(e=>{let{onEnter:t,onExit:i,on:r}=e,s=null;t((e=>{let{state:t}=e;const i=t.waitTime??this.#F();m.debug(`Started the reconnection timer for ${i} ms`);const r=new n.ErrorInfo("transportDisconnected","Transport disconnected, started the reconnection timer...");this.#C(r),this.#P(),this.#E.isNetworkAvailable&&(s=setTimeout((()=>{this.#j()}),i)),this.failedReconnectionAttempts++,this.#t.emitNextTick("disconnected","Wait and reconnect")})),i((()=>{null!==s&&(clearTimeout(s),s=null)})),r("timeout",(e=>{let{transitionTo:t}=e;return t({type:"connecting"})})),r("connect",(e=>{let{transitionTo:t}=e;return t({type:"connecting"})})),r("updateToken",(e=>{let{event:t,dontTransition:i}=e;this.config.token=t.token;const r=new n.ErrorInfo("tokenUpdatedLocally");return t.request.cancel(r),i()})),r("sendRequest",(e=>{let{event:t,dontTransition:n}=e;return this.#O(t.request),n()})),r("networkBecameReachable",(e=>{let{transitionTo:t}=e;return this.failedReconnectionAttempts=0,t({type:"connecting"})})),r("networkBecameUnreachable",(e=>{let{dontTransition:t}=e;return null!==s&&(clearTimeout(s),s=null),t()})),r("disconnect",(e=>a(e)))})),i("throttling",(e=>{let t,{onEnter:n,onExit:i,on:r}=e;n((e=>{let{state:n}=e;t=setTimeout((()=>{this.#j()}),n.waitTime)})),i((()=>{clearTimeout(t)})),r("timeout",(e=>{let{transitionTo:t}=e;return t({type:"connected"})})),r("updateToken",(e=>{let{event:t,dontTransition:n}=e;return this.config.token=t.token,this.#O(t.request),n()})),r("sendRequest",(e=>{let{event:t,dontTransition:n}=e;return this.#O(t.request),n()})),r("messageReceived",(e=>s(e))),r("disconnect",(e=>a(e))),r("networkBecameUnreachable",(e=>c(e))),r("nonFatalError",(e=>o(e))),r("fatalError",(e=>l(e)))}))})),this.fsm.subscribe(((e,t,n)=>{null!==e&&null!==n?m.debug(`FSM transition ${n.type}: ${e.type} -> ${t.type}`):m.debug(`FSM initiated: ${t.type}`)})),this.#E.on("changed",(e=>{m.debug(`ConnectivityMonitor "changed" event: ${e}`),this.fsm.transition({type:e?"networkBecameReachable":"networkBecameUnreachable"})}))}connect(){m.debug("Call to TwilsockClient.connect"),this.fsm.transition({type:"connect"})}disconnect(){m.debug("Call to TwilsockClient.disconnect"),this.fsm.transition({type:"disconnect"})}sendRequest(e){return n.CancellablePromise.withAsyncExecutor((async t=>{m.debug("Call to TwilsockClient.sendRequest:",JSON.stringify(e));const n=this.#q(e);this.fsm.transition({type:"sendRequest",request:n}),t((()=>{m.debug(`Request ${n.message.id} has been cancelled by the user`),n.cancel()}));const i=await n.promise;if(!(i instanceof A))throw new Error("Expected instance of ReplyMessage");let r=i.payload;if(e.typeCheck){const t=JSON.parse(i.payload);if(!e.typeCheck.Check(t))throw new Error("Payload doesn't match the provided schema");r=t}return new H(i.replyHeaders.httpStatus.code,i.replyHeaders.httpStatus.status,i.replyHeaders.httpHeaders,r)}))}updateToken(e){return n.CancellablePromise.withAsyncExecutor((async t=>{m.debug("Call to TwilsockClient.updateToken:",e);const i=this.#D(e);this.fsm.transition({type:"updateToken",token:e,request:i}),t((()=>{m.debug("Update token request has been cancelled by the user"),i.cancel()}));try{await i.promise}catch(e){if(e instanceof n.TwilioError&&"tokenUpdatedLocally"===e.errorInfo.reason)return void m.debug("Token was updated locally");throw e}m.debug("Token was updated remotely")}))}populateInitRegistrations(e){const t=[...e.values()];m.debug("Call to TwilsockClient.populateInitRegistrations:",t.join(", ")),this.config.initRegistrations=new Set([...this.config.initRegistrations,...e])}#R(e){for(const t of this.pendingRequests.values())t.cancel(e);this.pendingRequests.clear()}#C(e){for(const t of this.#k.values())t.cancel(e);this.#k.clear()}#U(){for(const e of this.pendingRequests.values())this.#$(e);this.pendingRequests.clear()}#O(e){this.pendingRequests.set(e.message.id,e)}#F(){const e=Math.min((e=>Math.round(Math.pow(Q,e)/G))(this.failedReconnectionAttempts),45);return 1e3*(e+.2*e*Math.random())}#M(){if(m.debug("Call to TwilsockClient.#connectWebSocket"),null!==this.#m)throw new Error("Websocket already exists");this.#m=new b,this.#m.on("connected",(()=>{m.debug('TwilsockTransport "connected" event'),this.fsm.transition({type:"transportConnected"})})),this.#m.on("disconnected",(e=>{this.fsm.transition({type:"nonFatalError",errorInfo:e})})),this.#m.on("messageReceived",(e=>{let t;this.#B();try{t=Message.parse(e)}catch(e){m.warn("Error while parsing an incoming message",e);const t=new n.ErrorInfo("cannotParse");return void this.fsm.transition({type:"fatalError",errorInfo:t})}this.fsm.transition({type:"messageReceived",message:t})})),this.#m.connect(this.config.url)}#P(){m.debug("Call to TwilsockClient.#disconnectWebSocket"),this.#m?.disconnect("TwilsockClient.#disconnectWebSocket called"),this.#m=null}#N(){if(null!==this.#T)throw new Error("The watchdog time is already running");this.#T=setTimeout((()=>{m.warn("Watchdog timeout"),this.fsm.transition({type:"nonFatalError",errorInfo:new n.ErrorInfo("timeout","Watchdog timeout")})}),45e3)}#A(e){const t=new I({product:this.config.activeGrant,message_types:[...this.config.initRegistrations]}),n=new j(["client_update"],this.config.token,this.config.continuationToken,t.message_types.length>0?[t]:null,this.config.tweaks,this.config.clientMetadata),i=new Message("init",n);return new f(i,e,(e=>{this.#z(e)}))}#D(e){const t=new Message("update",{token:e});return new f(t,6e4,(e=>{this.#z(e)}))}#q(e){const t=new N(e.grant??this.config.activeGrant,$.from(e)),n=new Message("message",t,e.headers["Content-Type"]??"application/json",e.payload);return new f(n,e.timeout,(e=>{this.#z(e)}))}#z(e){this.pendingRequests.delete(e.message.id),this.#k.delete(e.message.id)}#j(){m.debug("Call to TwilsockClient.#onTimeout"),this.fsm.transition({type:"timeout"})}#L(){if(null===this.#T)throw new Error("The watchdog time is not running");clearTimeout(this.#T),this.#T=null}#B(){null!==this.#T&&(this.#L(),this.#N())}#I(e){const t=[e.id,e.headers,e.payloadType,e.payload];r.match(e.method).with("reply",(()=>{this.#W(new A(...t))})).with("close",(()=>{this.#K(new F(...t))})).with("client_update",(()=>{this.#H(new B(...t))})).with("notification",(()=>{this.#V(new K(...t))})).with("ping",(()=>{this.#J(e,Z)})).otherwise((e=>{m.warn(`Skipped a message with an unexpected method "${e}"`)}))}#W(e){const t=this.#k.get(e.id);if(!t)return void m.warn(`Skipped a reply to an unknown request: ${e.id}`);const n=e.replyHeaders.status;if(n.code<200||n.code>=300){const i=r.match(n).with({errorCode:ee},(()=>ne(n,"tokenExpired"))).with({code:401},(()=>ne(n,"unauthorized"))).with({code:429},(()=>ne(n,"tooManyRequests"))).otherwise((()=>ne(n,"unknown")));return t.cancel(i),n.errorCode===ee&&(m.warn("Received a token expired reply"),this.#t.emitNextTick("tokenExpired")),void r.match(n.code).with(401,(()=>{this.fsm.transition({type:"fatalError",errorInfo:i})})).with(429,(()=>{const t=e.replyPayload.backoffPolicy,n=t.reconnectMinMs,r=t.reconnectMaxMs,s=Math.floor(Math.random()*(r-n)+n);this.fsm.transition({type:"tooManyRequests",waitTime:s,errorInfo:i})})).otherwise((()=>{this.fsm.transition({type:"nonFatalError",errorInfo:i})}))}const i=e.replyHeaders.continuationToken;void 0!==i&&(this.config.continuationToken=i),t.complete(e)}#K(e){m.debug(`Server has initiated the process of closing the connection: ${e.payload}`),this.#J(e,Z);const t=ne(e.status,"closeMessageReceived");if(308===e.status.code&&51232===e.status.errorCode)return m.debug("Token with a different instanceSid"),void this.fsm.transition({type:"fatalError",errorInfo:t});const n=e.status.code;r.match(n).with(308,(()=>{m.debug("Offloading to another instance"),this.fsm.transition({type:"nonFatalError",errorInfo:t})})).with(401,406,410,417,(()=>{m.debug(`Server closed connection due to a fatal error: ${t}`);const n=r.match(e.status).with({code:410},{errorCode:ee},(()=>(this.#t.emitNextTick("tokenExpired"),ne(e.status,"tokenExpired")))).with({code:401},(()=>ne(e.status,"unauthorized"))).otherwise((()=>t));this.fsm.transition({type:"fatalError",errorInfo:n})})).otherwise((()=>{m.warn(`Unexpected close message ${t}`),this.fsm.transition({type:"nonFatalError",errorInfo:t})}))}#H(e){this.#J(e,Z),"token_about_to_expire"!==e.clientUpdateType?m.warn(`Ignoring an unknown client update ${e.clientUpdateType}`):this.#t.emitNextTick("tokenAboutToExpire")}#V(e){if(""===e.payload)return m.warn(`Skipped a notification message with no payload: ${e.id}`),void this.#J(e,Y,"Notification message must carry data");this.#J(e,Z),this.#t.emitNextTick("messageReceived",e.messageType,e.payload)}#J(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";if(null===this.#m)return;const i=new Message("reply",{status:t},""!==n?"text/plain":"",n,e.id);this.#m.sendMessage(i.encode())}#$(e){if(null===this.#m)throw new Error("WebSocket not initialized");this.#m.sendMessage(e.message.encode()),this.#k.set(e.message.id,e)}}Object.defineProperty(e,"CancellablePromise",{enumerable:!0,get:function(){return n.CancellablePromise}}),Object.defineProperty(e,"CancellationError",{enumerable:!0,get:function(){return n.CancellationError}}),Object.defineProperty(e,"ErrorInfo",{enumerable:!0,get:function(){return n.ErrorInfo}}),Object.defineProperty(e,"TwilioError",{enumerable:!0,get:function(){return n.TwilioError}}),e.HttpRequest=class{url;method;headers;payload;grant;timeout;typeCheck;constructor(e){let{url:t,method:n="GET",headers:i={},payload:r="",grant:s=null,timeout:a=X,typeCheck:o=null}=e;this.url=t,this.method=n,this.headers=i,this.payload="string"==typeof r?r:JSON.stringify(r),this.grant=s,this.timeout=a,this.typeCheck=o,Object.freeze(i)}},e.TwilsockClient=ie}(Te);class en{configuration;services;cacheLifetime;cache;timer;pendingRequests;isShutdownInitiated=!1;constructor(e,t){this.configuration=e,this.services=t,this.cache=new Map,this.cacheLifetime=100*this.configuration.httpCacheInterval,this.pendingRequests=new Set,this.cleanupCache()}isExpired(e){return!this.cacheLifetime||Date.now()-e>this.cacheLifetime}cleanupCache(){for(const[e,t]of this.cache)this.isExpired(t.timestamp)&&this.cache.delete(e);0===this.cache.size&&clearInterval(this.timer)}pokeTimer(){this.timer=this.timer||setInterval((()=>this.cleanupCache()),2*this.cacheLifetime)}static responsePostProcess(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return{status:{code:e.statusCode,status:e.status},headers:e.headers,body:t}}executeWithRetry(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise(((n,i)=>{const r=[502,503,504];t&&r.push(429);const s=new Ee(this.configuration.backoffConfiguration);s.on("attempt",(()=>{e().then((e=>{if(!(e.statusCode>=400))return void s.succeeded(e);let t={};try{t=JSON.parse(e.payload)}catch{}if(r.includes(e.statusCode)){const n=parseInt(e.headers?e.headers["Retry-After"]:null);s.failed(Yt(e,t),isNaN(n)?void 0:1e3*n)}else"Twilsock disconnected"===t.message?s.failed(Yt(e,t)):(s.removeAllListeners(),s.cancel(),i(Yt(e,t)))})).catch((e=>{s.removeAllListeners(),s.cancel(),i(e)}))})),s.on("succeeded",(e=>{n(e)})),s.on("cancelled",(e=>i(e))),s.on("failed",(e=>i(e))),s.start()}))}async get(e){if(this.isShutdownInitiated)throw new Error("Client has been shut down.");const t=this.cache.get(e);if(t&&!this.isExpired(t.timestamp))return t.response;const n=this.executeWithRetry((()=>this.services.transport.sendRequest(new Te.HttpRequest({url:e,grant:this.configuration.productId}))),this.configuration.retryWhenThrottled);this.pendingRequests.add(n);const i=await n;this.pendingRequests.delete(n);const r=en.responsePostProcess(i);return this.cache.set(e,{response:r,timestamp:Date.now()}),this.pokeTimer(),r}async disconnect(){this.isShutdownInitiated=!0;try{await Promise.all([...this.pendingRequests])}catch{}await this.services.syncClient.shutdown()}}class tn{static TYPING_INDICATOR="twilio.ipmsg.typing_indicator";static NEW_MESSAGE="twilio.conversations.new_message";static ADDED_TO_CONVERSATION="twilio.conversations.added_to_conversation";static REMOVED_FROM_CONVERSATION="twilio.conversations.removed_from_conversation";static CONSUMPTION_UPDATE="twilio.channel.consumption_update"}var nn={};
|
274
|
-
/*
|
275
|
-
@license
|
276
|
-
The MIT License (MIT)
|
277
|
-
|
278
|
-
Copyright (c) 2016 Twilio Inc.
|
279
|
-
|
280
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
281
|
-
of this software and associated documentation files (the "Software"), to deal
|
282
|
-
in the Software without restriction, including without limitation the rights
|
283
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
284
|
-
copies of the Software, and to permit persons to whom the Software is
|
285
|
-
furnished to do so, subject to the following conditions:
|
286
|
-
|
287
|
-
The above copyright notice and this permission notice shall be included in all
|
288
|
-
copies or substantial portions of the Software.
|
289
|
-
|
290
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
291
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
292
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
293
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
294
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
295
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
296
|
-
SOFTWARE.
|
297
|
-
|
298
|
-
*/!function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=Te,n=pe,i=u.exports,r=Oe,s=P;function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var o=a(i);function c(e,t,n,i){var r,s=arguments.length,a=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,n,a):r(t,n))||a);return s>3&&a&&Object.defineProperty(t,n,a),a}function l(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(){}function h(){h.init.call(this)}function p(e){return void 0===e._maxListeners?h.defaultMaxListeners:e._maxListeners}function f(e,t,n,i){var r,s,a;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((s=e._events)?(s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),a=s[t]):(s=e._events=new d,e._eventsCount=0),a){if("function"==typeof a?a=s[t]=i?[n,a]:[a,n]:i?a.unshift(n):a.push(n),!a.warned&&(r=p(e))&&r>0&&a.length>r){a.warned=!0;var o=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");o.name="MaxListenersExceededWarning",o.emitter=e,o.type=t,o.count=a.length,function(e){"function"==typeof console.warn?console.warn(e):console.log(e)}(o)}}else a=s[t]=n,++e._eventsCount;return e}function m(e,t,n){var i=!1;function r(){e.removeListener(t,r),i||(i=!0,n.apply(e,arguments))}return r.listener=n,r}function g(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function y(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}d.prototype=Object.create(null),h.EventEmitter=h,h.usingDomains=!1,h.prototype.domain=void 0,h.prototype._events=void 0,h.prototype._maxListeners=void 0,h.defaultMaxListeners=10,h.init=function(){this.domain=null,h.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new d,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},h.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},h.prototype.getMaxListeners=function(){return p(this)},h.prototype.emit=function(e){var t,n,i,r,s,a,o,c="error"===e;if(a=this._events)c=c&&null==a.error;else if(!c)return!1;if(o=this.domain,c){if(t=arguments[1],!o){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=a[e]))return!1;var l="function"==typeof n;switch(i=arguments.length){case 1:!function(e,t,n){if(t)e.call(n);else for(var i=e.length,r=y(e,i),s=0;s<i;++s)r[s].call(n)}(n,l,this);break;case 2:!function(e,t,n,i){if(t)e.call(n,i);else for(var r=e.length,s=y(e,r),a=0;a<r;++a)s[a].call(n,i)}(n,l,this,arguments[1]);break;case 3:!function(e,t,n,i,r){if(t)e.call(n,i,r);else for(var s=e.length,a=y(e,s),o=0;o<s;++o)a[o].call(n,i,r)}(n,l,this,arguments[1],arguments[2]);break;case 4:!function(e,t,n,i,r,s){if(t)e.call(n,i,r,s);else for(var a=e.length,o=y(e,a),c=0;c<a;++c)o[c].call(n,i,r,s)}(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(r=new Array(i-1),s=1;s<i;s++)r[s-1]=arguments[s];!function(e,t,n,i){if(t)e.apply(n,i);else for(var r=e.length,s=y(e,r),a=0;a<r;++a)s[a].apply(n,i)}(n,l,this,r)}return!0},h.prototype.addListener=function(e,t){return f(this,e,t,!1)},h.prototype.on=h.prototype.addListener,h.prototype.prependListener=function(e,t){return f(this,e,t,!0)},h.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,m(this,e,t)),this},h.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,m(this,e,t)),this},h.prototype.removeListener=function(e,t){var n,i,r,s,a;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(i=this._events))return this;if(!(n=i[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new d:(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(r=-1,s=n.length;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){a=n[s].listener,r=s;break}if(r<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new d,this;delete i[e]}else!function(e,t){for(var n=t,i=n+1,r=e.length;i<r;n+=1,i+=1)e[n]=e[i];e.pop()}(n,r);i.removeListener&&this.emit("removeListener",e,a||t)}return this},h.prototype.off=function(e,t){return this.removeListener(e,t)},h.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new d,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new d:delete n[e]),this;if(0===arguments.length){for(var i,r=Object.keys(n),s=0;s<r.length;++s)"removeListener"!==(i=r[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=new d,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},h.prototype.listeners=function(e){var t,n,i=this._events;return n=i&&(t=i[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},h.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},h.prototype.listenerCount=g,h.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};const v=o.getLogger("twilio-notificatiions");function b(e,t){return[`${(new Date).toISOString()} Twilio.Notifications ${e}:`].concat(Array.from(t))}const _=new class{setLevel(e){v.setLevel(e)}trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];v.trace.apply(null,b("T",t))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];v.debug.apply(null,b("D",t))}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];v.info.apply(null,b("I",t))}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];v.warn.apply(null,b("W",t))}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];v.error.apply(null,b("E",t))}};class w{token;notificationId;messageTypes;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Set;this.token=e,this.notificationId=t,this.messageTypes=n}}class x extends h{channelType;desiredState=new w;currentState=new w;_hasActiveAttempt=!1;constructor(e){super(),this.channelType=e}setNotificationId(e){this.desiredState.notificationId=e}isActive(){return""!==this.desiredState.notificationId}subscribe(e){this.desiredState.messageTypes.has(e)?_.debug(`message type '${e}' for channel ${this.channelType} is already registered`):this.desiredState.messageTypes.add(e)}unsubscribe(e){this.desiredState.messageTypes.has(e)&&this.desiredState.messageTypes.delete(e)}updateToken(e){this.desiredState.token=e}async commitChanges(){if(this._hasActiveAttempt)throw _.error("One registration attempt is already in progress"),new Error("One registration attempt is already in progress");const[e,t]=function(e,t){const n=new Set;return e.notificationId!==t.notificationId&&n.add("notificationId"),e.token!==t.token&&n.add("token"),function(e,t){return[...[...e].filter((e=>!t.has(e))),...[...t].filter((t=>!e.has(t)))]}(e.messageTypes,t.messageTypes).length>0&&n.add("messageType"),[n.size>0,n]}(this.desiredState,this.currentState);if(e){this.currentState.notificationId||t.delete("notificationId"),_.trace(`Persisting ${this.channelType} registration`,t,this.desiredState);try{this._hasActiveAttempt=!0;const e=new w;if(e.token=this.desiredState.token,e.notificationId=this.desiredState.notificationId,e.messageTypes=new Set(this.desiredState.messageTypes),e.messageTypes.size>0){const n=await this.updateRegistration(e,t);this.currentState.token=n.token,this.currentState.notificationId=n.notificationId,this.currentState.messageTypes=new Set(n.messageTypes),this.emit("stateChanged",this.channelType,"registered",this.currentState)}else await this.removeRegistration(),this.currentState.token=e.token,this.currentState.notificationId=e.notificationId,this.currentState.messageTypes.clear(),this.emit("stateChanged",this.channelType,"unregistered",this.currentState)}catch(e){throw e}finally{this._hasActiveAttempt=!1}}}}const S={min:2e3,max:12e4,randomness:.2};class k extends x{context;twilsock;registrarUrl;registrationId=null;constructor(e,t,n,i){super(e),this.context=t,this.twilsock=n,this.registrarUrl=i}async updateRegistration(e,i){if(i.has("notificationId")&&await this.removeRegistration(),!e.notificationId||!e.notificationId.length)throw _.error("No push notification ID for registration"),new Error("No push notification ID for registration");_.trace("Registering",this.channelType,e);const r={endpoint_platform:this.context.platform,channel_type:this.channelType,version:this.context.protocolVersion.toString(),message_types:Array.from(e.messageTypes),data:{registration_id:e.notificationId}},s=this.context.productId,a=`${this.registrarUrl}?productId=${s}`,o={"Content-Type":"application/json"};_.trace(`Creating registration for channel ${this.channelType}`);try{const e=JSON.parse((await new n.AsyncRetrier(S).run((()=>this.twilsock.sendRequest(new t.HttpRequest({method:"POST",url:a,headers:o,payload:r,grant:s}))))).payload);this.registrationId=e.id,_.debug("Registration created: ",e)}catch(e){throw _.error("Registration failed: ",e),e}return e}async removeRegistration(){if(!this.registrationId)return;const e=this.context.productId,i=`${this.registrarUrl}/${this.registrationId}?productId=${e}`,r={"Content-Type":"application/json"};_.trace(`Removing registration for ${this.channelType}`);try{await new n.AsyncRetrier(Object.assign(S,{maxAttemptsCount:3})).run((()=>this.twilsock.sendRequest(new t.HttpRequest({method:"DELETE",url:i,headers:r,grant:e})))),this.registrationId=null,this.currentState.notificationId="",_.debug(`Registration removed for ${this.channelType}`)}catch(e){throw _.error("Failed to remove registration ",this.channelType,e),e}}async sendDeviceRemoveRequest(e){if(""===e)throw new Error("Empty registration ID");const i=this.context.productId,r=`${this.registrarUrl}?productId=${i}`,s={"Content-Type":"application/json"},a={binding_type:this.channelType,address:e};try{_.trace(`Removing old registrations for ${this.channelType}`),await new n.AsyncRetrier(Object.assign(S,{maxAttemptsCount:3})).run((()=>this.twilsock.sendRequest(new t.HttpRequest({method:"DELETE",url:r,headers:s,payload:a,grant:i})))),this.registrationId=null,this.currentState.notificationId="",_.debug(`Registration removed for ${this.channelType}`)}catch(e){throw _.error("Failed to remove registration ",this.channelType,e),e}}}class E extends x{productId;platform;twilsock;contextId=r.nanoid();constructor(e,t,n){super("twilsock"),this.productId=e,this.platform=t,this.twilsock=n}async updateRegistration(e,t){if(!t.has("messageType"))return e;Array.from(e.messageTypes);return this.productId,this.platform,e}async removeRegistration(){}async sendDeviceRemoveRequest(e){}}var T;const I=s.literal("apn","fcm","twilsock");e.Notifications=T=class extends h{twilsock;connectors;constructor(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),n.logLevel=n.logLevel??"error",_.setLevel(n.logLevel);const i=n.productId??"notifications",r=!n.twilsockClient,s=n.twilsockClient=n.twilsockClient??new t.TwilsockClient(e,i,n),a=n.notifications??{},o=`https://ers.${a.region??n.region??"us1"}.twilio.com/v1/registrations`,c=a.ersUrl||o;this.connectors=new Map;const u=T._detectPlatform();this.connectors.set("apn",new k("apn",{protocolVersion:4,productId:i,platform:u},s,c)),this.connectors.set("fcm",new k("fcm",{protocolVersion:3,productId:i,platform:u},s,c)),this.connectors.set("twilsock",new E(i,u,s)),s.on("connecting",(()=>this.emit("transportState","connecting"))),s.on("connected",(()=>this.emit("transportState","connected"))),s.on("disconnected",(()=>this.emit("transportState","disconnected"))),this._connector("twilsock").on("stateChanged",((e,t,n)=>this.emit("stateChanged",e,t,n))),this._connector("apn").on("stateChanged",((e,t,n)=>this.emit("stateChanged",e,t,n))),this._connector("fcm").on("stateChanged",((e,t,n)=>this.emit("stateChanged",e,t,n))),s.on("messageReceived",((e,t)=>this._routeMessage(e,t))),this.updateToken(e),r&&(s.connect(),this.twilsock=s)}async shutdown(){this.connectors.clear(),this.twilsock&&await this.twilsock.disconnect()}setPushRegistrationId(e,t){_.debug(`Set ${e} push registration id '${t}'`),this._connector(e).setNotificationId(t)}subscribe(e,t){_.debug(`Add ${e} subscriptions for message type ${t}`),this._connector(e).subscribe(t)}unsubscribe(e,t){_.debug(`Remove ${e} subscriptions for message type ${t}`),this._connector(e).unsubscribe(t)}updateToken(e){this.connectors.forEach((t=>t.updateToken(e)))}async commitChanges(){const e=[];this.connectors.forEach((t=>{t.isActive()&&e.push(t.commitChanges())})),await Promise.all(e)}async removeRegistrations(e,t){await this._connector(e).sendDeviceRemoveRequest(t)}handlePushNotification(e){return{messageType:e.twi_message_type,payload:e.payload}}_routeMessage(e,t){_.debug("Notification message arrived: ",e,t),this.emit("message",e,t)}_connector(e){const t=this.connectors.get(e);if(!t)throw new Error(`Unknown channel type: ${e}`);return t}static _detectPlatform(){let e="";return"undefined"!=typeof navigator?(e="unknown",void 0!==navigator.product&&(e=navigator.product),void 0!==navigator.userAgent&&(e=navigator.userAgent)):e="web",e.substring(0,128)}},c([s.validateTypes(I,s.nonEmptyString),l("design:type",Function),l("design:paramtypes",[String,String]),l("design:returntype",void 0)],e.Notifications.prototype,"setPushRegistrationId",null),c([s.validateTypes(I,s.nonEmptyString),l("design:type",Function),l("design:paramtypes",[String,String]),l("design:returntype",void 0)],e.Notifications.prototype,"subscribe",null),c([s.validateTypes(I,s.nonEmptyString),l("design:type",Function),l("design:paramtypes",[String,String]),l("design:returntype",void 0)],e.Notifications.prototype,"unsubscribe",null),c([s.validateTypes(s.nonEmptyString),l("design:type",Function),l("design:paramtypes",[String]),l("design:returntype",void 0)],e.Notifications.prototype,"updateToken",null),c([s.validateTypesAsync(I,s.nonEmptyString),l("design:type",Function),l("design:paramtypes",[String,String]),l("design:returntype",Promise)],e.Notifications.prototype,"removeRegistrations",null),e.Notifications=T=c([s.validateConstructorTypes(s.nonEmptyString,[s.pureObject,"undefined",s.literal(null)]),l("design:paramtypes",[String,Object])],e.Notifications)}(nn);var rn={};Object.defineProperty(rn,"__esModule",{value:!0});var sn=P,an=Te,on=u.exports,cn=pe,un=Oe,ln=te,dn=Ke.exports;function hn(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function pn(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var fn=pn(on),mn=hn(on),gn=hn(un),yn=pn(dn);function vn(e,t,n,i){var r,s=arguments.length,a=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,n,a):r(t,n))||a);return s>3&&a&&Object.defineProperty(t,n,a),a}function bn(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}class _n{base;args;paths;constructor(e){this.base=e,this.args=new Array,this.paths=new Array}pathSegment(e){return this.paths.push(encodeURIComponent(e)),this}queryParam(e,t){return void 0!==t&&this.args.push(encodeURIComponent(e)+"="+encodeURIComponent(t)),this}build(){let e=this.base;return this.paths.length&&(e+="/"+this.paths.join("/")),this.args.length&&(e+="?"+this.args.join("&")),e}}class SyncError extends Error{name;message;status;code;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;super(),this.name=this.constructor.name,this.message=`${e} (status: ${t}, code: ${n})`,this.status=t,this.code=n}}class wn extends SyncError{body;constructor(e){let t=arguments.length>3?arguments[3]:void 0;super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,arguments.length>2&&void 0!==arguments[2]?arguments[2]:0),this.body=t}}function xn(e){return JSON.parse(JSON.stringify(e))}function Sn(e){if(!(void 0===e||kn(e)))throw new SyncError(`Invalid pageSize parameter. Expected a positive integer, was '${e}'.`,400,20007)}function kn(e){return function(e){return!isNaN(parseInt(e))&&isFinite(e)}(e)&&e>0}const En=fn.getLogger("twilio-sync");function Tn(e,t){return[`${(new Date).toISOString()} Sync ${e}:`].concat(Array.from(t))}var In=function(e){En.setLevel(e)},Cn=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];En.trace.apply(null,Tn("T",t))},Rn=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];En.debug.apply(null,Tn("D",t))},Pn=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];En.error.apply(null,Tn("E",t))};class Mn{settings;constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=`https://cds.${e.region||"us1"}.twilio.com`,n=e.cdsUri||t;var i,r,s;this.settings={subscriptionsUri:n+"/v4/Subscriptions",documentsUri:n+"/v3/Documents",listsUri:n+"/v3/Lists",mapsUri:n+"/v3/Maps",streamsUri:n+"/v3/Streams",insightsUri:n+"/v3/Insights",sessionStorageEnabled:(i=e.Sync,r="enableSessionStorage",s=!0,i&&void 0!==i[r]?i[r]:s),productId:e.productId}}get subscriptionsUri(){return this.settings.subscriptionsUri}get documentsUri(){return this.settings.documentsUri}get listsUri(){return this.settings.listsUri}get mapsUri(){return this.settings.mapsUri}get streamsUri(){return this.settings.streamsUri}get insightsUri(){return this.settings.insightsUri}get backoffConfig(){return this.settings.backoffConfig||{}}get sessionStorageEnabled(){return this.settings.sessionStorageEnabled}get productId(){return this.settings.productId}}var On="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==r?r:"undefined"!=typeof self?self:{},An={};
|
299
|
-
/*
|
300
|
-
@license
|
301
|
-
Copyright (c) 2022 Twilio Inc.
|
302
|
-
|
303
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
304
|
-
|
305
|
-
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
306
|
-
|
307
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
308
|
-
|
309
|
-
|
310
|
-
*/
|
311
|
-
Object.defineProperty(An,"__esModule",{value:!0});var jn=mn.default,$n=gn.default;function Nn(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var Un=Nn(jn);const Ln=e=>{const t=Un.default.getLevel();Un.default.setLevel("warn"),Un.default.warn(e),Un.default.setLevel(t)};class Fn extends Error{constructor(){super("Promise was cancelled")}}class qn extends Promise{static#i=new Map;#r;#s;constructor(e){const t=$n.nanoid();let n;super(((i,r)=>(n=r,e((e=>{qn.#i.delete(t),i(e)}),(e=>{qn.#i.delete(t),r(e)}),(e=>{qn.#i.set(t,e)}))))),this.#r=t,this.#s=n}cancel(){const e=qn.#i.get(this.#r);return e?.(),this.#s&&(this.catch((()=>{})),this.#s(new Fn)),this}static withAsyncExecutor(e){return new qn((async(t,n,i)=>{try{t(await e(i))}catch(e){n(e)}}))}}const Dn={unknown:"Unknown error",cancelled:"Job was cancelled",timeout:"Timeout occurred",mediaUploadError:"Media upload error",mediaFetchError:"Media fetch error",tooManyAttachments:"Too many attachments",unsupportedEmailBodyContentType:"Unsupported email body content type",unsupportedEmailHistoryContentType:"Unsupported email history content type",transportDisconnected:"Transport has been disconnected",networkBecameUnreachable:"Network became unreachable",unauthorized:"Unauthorized",tokenExpired:"Token expired",tokenUpdatedLocally:"Transport disconnected, token updated locally and will be used at reconnect",tooManyRequests:"Request failed with 429 reply",hostnameUnverified:"Failed on ssl handshake: CERTIFICATE_VERIFY_FAILED",sslHandshakeError:"Failed on ssl handshake: UNAUTHORIZED",closeMessageReceived:"Twilsock received a close message from the server",cannotParse:"Error while parsing an incoming message"};class Bn extends Error{errorInfo;constructor(e){super(`${e}`),this.errorInfo=e,Object.freeze(e)}}An.CancellablePromise=qn,An.CancellationError=Fn,An.Deferred=class{promise;#a;#o;#c=!1;constructor(){this.promise=new Promise(((e,t)=>{this.#a=t=>{this.#c=!0,e(t)},this.#o=e=>{this.#c=!0,t(e)}}))}get resolve(){return this.#a}get reject(){return this.#o}get isDone(){return this.#c}},An.ErrorInfo=class{reason;message;status;code;description;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Dn[e];this.reason=e,this.message=t,this.status=n,this.code=i,this.description=r}toString(){return`${this.description} ${this.status}:${this.code} ${this.message}`}},An.Logger=class{#u;#l;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.#u=t,this.#l=jn.getLogger(e)}setLevel(e){this.#l.setLevel(e)}trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.trace.apply(null,this.#d("T",t))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.debug.apply(null,this.#d("D",t))}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.info.apply(null,this.#d("I",t))}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.warn.apply(null,this.#d("W",t))}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.#l.error.apply(null,this.#d("E",t))}#d(e,t){return[`${(new Date).toISOString()} ${this.#u} ${e}:`,...t]}};var zn=An.TwilioError=Bn;An.deprecated=(e,t,n)=>(i,r,s)=>{if("function"!=typeof s.value&&void 0===s?.get)throw new Error("The deprecated decorator can only be applied to methods or getters");if("function"==typeof s.value){const i=s.value;return void(s.value=function(){Ln(`The method ${e} is deprecated${t?", use "+t+" instead":""}${n?", "+n:"."}`);for(var r=arguments.length,s=new Array(r),a=0;a<r;a++)s[a]=arguments[a];return i.apply(this,s)})}const a=s.get;s.get=function(){return Ln(`The getter ${e} is deprecated${t?", use "+t+" instead":""}${n?", "+n:"."}`),a?.apply(this)}},An.deprecationWarning=Ln;class Wn{localObject;pendingCorrelationId;pendingAction;rejectedWithError;retryCount;established;constructor(e){this.localObject=e,this.pendingCorrelationId=null,this.pendingAction=null,this.established=!1,this.retryCount=0}get sid(){return this.localObject.sid}get type(){return this.localObject.type}get lastEventId(){return this.localObject.lastEventId}get indexName(){return this.localObject.indexName}get queryString(){return this.localObject.queryString}get isEstablished(){return this.established}update(e,t){this.localObject._update(e,t)}updatePending(e,t){this.pendingAction=e,this.pendingCorrelationId=t}reset(){this.updatePending(null,null),this.retryCount=0,this.established=!1,this.setSubscriptionState("none")}markAsFailed(e){this.rejectedWithError=e.error,this.updatePending(null,null),this.localObject.reportFailure(new SyncError(`Failed to subscribe on service events: ${e.error.message}`,e.error.status,e.error.code))}complete(e){this.updatePending(null,null),this.established=!0,this.localObject._advanceLastEventId(e)}setSubscriptionState(e){this.localObject._setSubscriptionState(e)}}class Kn{services;subscriptions;persisted;latestPokeResponseArrivalTimestampByCorrelationId;backoff;isConnected=!1;maxBatchSize=100;subscriptionTtlTimer=null;pendingPokeReason=null;constructor(e){this.services=e,this.subscriptions=new Map,this.persisted=new Map,this.latestPokeResponseArrivalTimestampByCorrelationId=new Map;this.backoff=cn.Backoff.exponential(Object.assign({randomisationFactor:.2,initialDelay:100,maxDelay:12e4},this.services.config.backoffConfig)),this.backoff.on("ready",(()=>{let{action:e,subscriptions:t}=this.getSubscriptionUpdateBatch();e?this.applyNewSubscriptionUpdateBatch(e,t):(this.backoff.reset(),Rn("All subscriptions resolved."))}))}getSubscriptionUpdateBatch(){function e(e,t,n,i){let r=[];for(let[s,a]of e){if(!t.get(s)&&n!==a.pendingAction&&!a.rejectedWithError&&(r.push(a),i&&r.length>=i))break}return r}let t=e(this.subscriptions,this.persisted,"establish",this.maxBatchSize);if(t.length>0)return{action:"establish",subscriptions:t};let n=e(this.persisted,this.subscriptions,"cancel",this.maxBatchSize);return n.length>0?{action:"cancel",subscriptions:n}:{action:null,subscriptions:null}}persist(){this.backoff.backoff()}async applyNewSubscriptionUpdateBatch(e,t){if(!this.isConnected)return Rn("Twilsock connection (required for subscription) not ready; waiting…"),void this.backoff.reset();t=this.processLocalActions(e,t);const n=(new Date).getTime();for(const i of t)this.recordActionAttemptOn(i,e,n);let i=this.pendingPokeReason;this.pendingPokeReason=null;try{let r=await this.request(e,n,i,t),s=r.body.max_batch_size;if(!isNaN(parseInt(s))&&isFinite(s)&&s>0&&(this.maxBatchSize=s),!this.subscriptionTtlTimer){let e=r.body.ttl_in_s;!isNaN(parseFloat(e))&&isFinite(e)&&e>0&&(this.subscriptionTtlTimer=setTimeout((()=>this.onSubscriptionTtlElapsed()),1e3*e))}if("establish"===e){const e=r.body.estimated_delivery_in_ms;!isNaN(parseFloat(e))&&isFinite(e)&&e>0?setTimeout((()=>this.verifyPokeDelivery(n,e,t)),e):Pn(`Invalid timeout: ${e}`),t.filter((e=>e.pendingCorrelationId===n)).forEach((e=>e.setSubscriptionState("response_in_flight")))}this.backoff.reset()}catch(i){for(const n of t)this.recordActionFailureOn(n,e);i instanceof zn&&"transportDisconnected"===i.errorInfo.reason?(Rn(`Twilsock connection (required for subscription) not ready (c:${n}); waiting…`),this.backoff.reset()):(Rn(`Failed an attempt to ${e} subscriptions (c:${n}); retrying`,i),this.persist())}}verifyPokeDelivery(e,t,n){const i=this.latestPokeResponseArrivalTimestampByCorrelationId.get(e),r=i?(new Date).getTime()-i:t;if(r>=t)n.filter((t=>t.pendingCorrelationId===e)).forEach((e=>{e.updatePending(null,null),e.retryCount++,this.persisted.delete(e.sid)})),this.persist(),this.latestPokeResponseArrivalTimestampByCorrelationId.delete(e);else{setTimeout((()=>this.verifyPokeDelivery(e,t,n)),t-r)}}processLocalActions(e,t){return"cancel"===e?t.filter((e=>!e.rejectedWithError)):t}recordActionAttemptOn(e,t,n){if(e.setSubscriptionState("request_in_flight"),"establish"===t)this.persisted.set(e.sid,e),e.updatePending(t,n);else{let i=this.persisted.get(e.sid);i&&i.updatePending(t,n)}}recordActionFailureOn(e,t){e.setSubscriptionState("none"),e.updatePending(null,null),"establish"===t&&this.persisted.delete(e.sid)}request(e,t,n,i){let r=i.map((t=>({object_sid:t.sid,object_type:t.type,last_event_id:"establish"===e?t.lastEventId:void 0,index_name:"establish"===e?t.indexName:void 0,query_string:"establish"===e?t.queryString:void 0}))),s=i.filter((e=>e.retryCount>0)).length;Rn(`Attempting '${e}' request (c:${t}):`,r);const a={event_protocol_version:4,action:e,correlation_id:t,retried_requests:s,ttl_in_s:-1,requests:r};return"ttl"===n&&(a.reason=n),this.services.network.post(this.services.config.subscriptionsUri,a)}add(e,t){Rn(`Establishing intent to subscribe to ${e}`);const n=this.subscriptions.get(e);n&&t&&n.lastEventId===t.lastEventId||(this.persisted.delete(e),this.subscriptions.set(e,new Wn(t)),this.persist())}remove(e){Rn(`Establishing intent to unsubscribe from ${e}`);this.subscriptions.delete(e)&&this.persist()}acceptMessage(e,t){Cn("Subscriptions received",e);const n=e.event_type,i=void 0!==e.events?e.events:[e.event],r=e.correlation_id;r&&this.latestPokeResponseArrivalTimestampByCorrelationId.set(r,(new Date).getTime());for(const s of i){let i;switch(e.event_type){case"subscription_established":this.applySubscriptionEstablishedMessage(s,r);break;case"subscription_canceled":this.applySubscriptionCancelledMessage(s,r);break;case"subscription_failed":this.applySubscriptionFailedMessage(s,r);break;case(i=n.match(/^(?:map|list|document|stream|live_query)_/)||{}).input:{let r;switch(i[0]){case"map_":r=s.map_sid;break;case"list_":r=s.list_sid;break;case"document_":r=s.document_sid;break;case"stream_":r=s.stream_sid;break;case"live_query_":r=s.query_id,t=!1,!0===e.strictly_ordered&&(t=!0);break;default:r=void 0}this.applyEventToSubscribedEntity(r,s,n,t);break}default:Rn(`Dropping unknown message type ${n}`)}}}applySubscriptionEstablishedMessage(e,t){const n=e.object_sid;let i=this.persisted.get(e.object_sid);i&&i.pendingCorrelationId===t?"interrupted"===e.replay_status?(Rn(`Event Replay for subscription to ${n} (c:${t}) interrupted; continuing eagerly.`),i.updatePending(null,null),this.persisted.delete(i.sid),this.backoff.reset()):"completed"===e.replay_status&&(Rn(`Event Replay for subscription to ${n} (c:${t}) completed. Subscription is ready.`),i.complete(e.last_event_id),this.persisted.set(e.object_sid,i),i.setSubscriptionState("established"),this.backoff.reset()):Rn(`Late message for ${e.object_sid} (c:${t}) dropped.`),this.persist()}applySubscriptionCancelledMessage(e,t){let n=this.persisted.get(e.object_sid);n&&n.pendingCorrelationId===t?(n.updatePending(null,null),n.setSubscriptionState("none"),this.persisted.delete(e.object_sid)):Rn(`Late message for ${e.object_sid} (c:${t}) dropped.`),this.persist()}applySubscriptionFailedMessage(e,t){const n=e.object_sid;let i=this.subscriptions.get(n),r=this.persisted.get(n);i&&r?r.pendingCorrelationId===t&&(Pn(`Failed to subscribe on ${r.sid}`,e.error),r.markAsFailed(e),r.setSubscriptionState("none")):!i&&r&&(this.persisted.delete(n),r.setSubscriptionState("none")),this.persist()}applyEventToSubscribedEntity(e,t,n,i){if(!e)return;i=i||(()=>{let t=this.persisted.get(e);return t&&t.isEstablished})();let r=this.subscriptions.get(e);r?(t.type=n,r.update(t,i)):Rn(`Message dropped for SID '${e}', for which there is no subscription.`)}onConnectionStateChanged(e){this.isConnected=e,e&&this.poke("reconnect")}onSubscriptionTtlElapsed(){this.isConnected&&this.poke("ttl")}poke(e){Rn(`Triggering event replay for all subscriptions, reason=${e}`),this.pendingPokeReason=e,this.subscriptionTtlTimer&&(clearTimeout(this.subscriptionTtlTimer),this.subscriptionTtlTimer=null);let t=[];for(let e of this.persisted.values())e.reset(),e.rejectedWithError&&t.push(e);this.persisted.clear();for(let e of t)this.persisted.set(e.sid,e);this.persist()}shutdown(){this.backoff.reset(),this.subscriptions.clear()}}const Hn=un.customAlphabet("1234567890abcdef",32);function Vn(e,t){if(t?.message)return t.message;switch(e.statusCode){case 429:return"Throttled by server";case 404:return"Not found from server";default:return"Error from server"}}function Jn(e){return e?.code??0}function Gn(e,t){return 409===e.statusCode?new wn(Vn(e,t),e.statusCode,Jn(t),t):e.statusCode?new SyncError(Vn(e,t),e.statusCode,Jn(t)):e instanceof zn&&"transportDisconnected"===e.errorInfo.reason?e:new SyncError(t?.message??e.message??"Unexpected error",0,0)}class Qn{clientInfo;config;transport;pendingRequests;isShutdownInitiated=!1;constructor(e,t,n){this.clientInfo=e,this.config=t,this.transport=n,this.pendingRequests=new Set}createHeaders(){return{"Content-Type":"application/json","Twilio-Sync-Client-Info":JSON.stringify(this.clientInfo),"Twilio-Request-Id":`RQ${Hn()}`}}backoffConfig(){return Object.assign({min:4e3,max:6e4,maxAttemptsTime:9e4,randomness:.2},this.config.backoffConfig)}executeWithRetry(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return new Promise(((n,i)=>{let r=[502,503,504];t&&r.push(429);let s=new cn.Retrier(this.backoffConfig());s.on("attempt",(()=>{e().then((e=>{if(!(e.statusCode>=400))return void s.succeeded(e);let t={};try{t=JSON.parse(e.payload)}catch{}if(r.includes(e.statusCode)){let n=parseInt(e.headers?e.headers["Retry-After"]:null);s.failed(Gn(e,t),isNaN(n)?null:1e3*n)}else"Twilsock disconnected"===t.message?s.failed(Gn(e,t)):(s.removeAllListeners(),s.cancel(),i(Gn(e,t)))})).catch((e=>{s.removeAllListeners(),s.cancel(),i(Gn(e,null))}))})),s.on("succeeded",(e=>{n(e)})),s.on("cancelled",(e=>i(Gn(e,null)))),s.on("failed",(e=>i(Gn(e,null)))),s.start()}))}responsePostProcess(e){let t={};try{t=JSON.parse(e.payload)}catch{}return{status:{code:e.statusCode,status:e.status},headers:e.headers,body:t}}get(e){if(this.isShutdownInitiated)throw new Error("Client has been shut down.");let t=this.createHeaders();Rn("GET",e,"ID:",t["Twilio-Request-Id"]);const n=this.executeWithRetry((()=>this.transport.sendRequest(new an.HttpRequest({url:e,headers:t,grant:this.config.productId}))),!0);return this.pendingRequests.add(n),n.then((e=>(this.pendingRequests.delete(n),this.responsePostProcess(e))))}post(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(this.isShutdownInitiated)throw new Error("Client has been shut down.");let r=this.createHeaders();null!=n&&(r["If-Match"]=n),Rn("POST",e,"ID:",r["Twilio-Request-Id"]);const s=this.executeWithRetry((()=>this.transport.sendRequest(new an.HttpRequest({method:"POST",url:e,headers:r,payload:t,grant:this.config.productId}))),i);return this.pendingRequests.add(s),s.then((e=>(this.pendingRequests.delete(s),this.responsePostProcess(e))))}put(e,t,n){if(this.isShutdownInitiated)throw new Error("Client has been shut down.");let i=this.createHeaders();null!=n&&(i["If-Match"]=n),Rn("PUT",e,"ID:",i["Twilio-Request-Id"]);const r=this.executeWithRetry((()=>this.transport.sendRequest(new an.HttpRequest({method:"PUT",url:e,headers:i,payload:t,grant:this.config.productId}))),!1);return this.pendingRequests.add(r),r.then((e=>(this.pendingRequests.delete(r),this.responsePostProcess(e))))}delete(e){if(this.isShutdownInitiated)throw new Error("Client has been shut down.");let t=this.createHeaders();Rn("DELETE",e,"ID:",t["Twilio-Request-Id"]);const n=this.executeWithRetry((()=>this.transport.sendRequest(new an.HttpRequest({method:"DELETE",url:e,headers:t,grant:this.config.productId}))),!1);return this.pendingRequests.add(n),n.then((e=>(this.pendingRequests.delete(n),this.responsePostProcess(e))))}async disconnect(){this.isShutdownInitiated=!0;try{await Promise.all([...this.pendingRequests])}catch{}await this.transport.disconnect()}}class Xn{config;storage;storageId;constructor(e,t){this.config=e,this.storageId=null;try{this.storage=t||sessionStorage}catch(e){}}storageKey(e,t){return`${this.storageId}::${e}::${t}`}get isReady(){return this.config.sessionStorageEnabled&&!!this.storageId}updateStorageId(e){this.storageId=e}store(e,t,n){return this.isReady?this._store(this.storageKey(e,t),n):null}read(e,t){return this.isReady?this._read(this.storageKey(e,t)):null}remove(e,t,n){if(!this.isReady)return null;try{this.storage.removeItem(this.storageKey(e,t)),n&&this.storage.removeItem(this.storageKey(e,n))}catch(e){}}update(e,t,n,i){if(!this.isReady)return null;this._apply(this.storageKey(e,t),i),n&&this._apply(this.storageKey(e,n),i)}_store(e,t){try{this.storage.setItem(e,JSON.stringify(t))}catch(e){}}_read(e){try{let t=this.storage.getItem(e);if(t)return JSON.parse(t)}catch(e){}return null}_apply(e,t){let n=this._read(e);if(!n)return!1;this._store(e,Object.assign(n,t))}}class Zn{services;removalHandler;subscriptionState;_attachedListeners;constructor(e,t){this.services=e,this.removalHandler=t,this.subscriptionState="none",this._attachedListeners=new Map}_advanceLastEventId(e,t){}reportFailure(e){404===e.status?this.onRemoved(!1):this.broadcastEventToListeners("failure",e)}_subscribe(){this.services.router._subscribe(this.sid,this)}_unsubscribe(){this.services.router._unsubscribe(this.sid)}_setSubscriptionState(e){this.subscriptionState=e,this.broadcastEventToListeners("_subscriptionStateChanged",e)}close(){this._unsubscribe(),null!=this.removalHandler&&this.removalHandler(this.type,this.sid,this.uniqueName)}attach(e){const t=e.listenerUuid;this._attachedListeners.get(t)||(this._attachedListeners.size||this._subscribe(),this._attachedListeners.set(t,e))}detach(e){this._attachedListeners.delete(e),this._attachedListeners.size||this.close()}broadcastEventToListeners(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];for(let t of this._attachedListeners.values())t.emit(e,...n)}}class Yn{queuedRequests=[];inputMergingFunction;isRequestInFlight=!1;constructor(e){this.inputMergingFunction=e}add(e,t){let n=new Promise(((n,i)=>this.queuedRequests.push({input:e,requestFunction:t,resolve:n,reject:i})));return this.wakeupQueue(),n}squashAndAdd(e,t){let n,i=this.queuedRequests;this.queuedRequests=[],i.length>0?(n=i.map((e=>e.input)).reduce(this.inputMergingFunction),n=this.inputMergingFunction(n,e)):n=e;let r=this.add(n,t);return i.forEach((e=>r.then(e.resolve,e.reject))),r}isEmpty(){return 0===this.queuedRequests.length&&!this.isRequestInFlight}wakeupQueue(){if(0!==this.queuedRequests.length&&!this.isRequestInFlight){let e=this.queuedRequests.shift();this.isRequestInFlight=!0,e.requestFunction(e.input).then(e.resolve,e.reject).then((e=>{this.isRequestInFlight=!1,this.wakeupQueue()}))}}}class ei{inputReducer;queueByNamespaceKey=new Map;constructor(e){this.inputReducer=e}async add(e,t,n){return this.invokeQueueMethod(e,(e=>e.add(t,n)))}async squashAndAdd(e,t,n){return this.invokeQueueMethod(e,(e=>e.squashAndAdd(t,n)))}async invokeQueueMethod(e,t){this.queueByNamespaceKey.has(e)||this.queueByNamespaceKey.set(e,new Yn(this.inputReducer));const n=t(this.queueByNamespaceKey.get(e));return this.queueByNamespaceKey.get(e).isEmpty()&&this.queueByNamespaceKey.delete(e),n}}class ti extends ln.ReplayEventEmitter{uuid;closed;constructor(){super(),this.closed=!1,this.uuid=un.nanoid()}get listenerUuid(){return this.uuid}close(){this.removeAllListeners(),this.closed=!0}ensureNotClosed(){if(this.closed)throw new Error("Invalid operation on closed object")}}class ni extends Zn{updateMergingQueue;descriptor;isDeleted=!1;constructor(e,t,n){super(e,n);this.updateMergingQueue=new Yn(((e,t)=>"number"==typeof t.ttl?{ttl:t.ttl}:e)),this.descriptor=t,this.descriptor.data=this.descriptor.data||{},this.descriptor.date_updated=new Date(this.descriptor.date_updated)}get uri(){return this.descriptor.url}get revision(){return this.descriptor.revision}get lastEventId(){return this.descriptor.last_event_id}get dateExpires(){return this.descriptor.date_expires}static get type(){return"document"}get type(){return"document"}get indexName(){}get queryString(){}get sid(){return this.descriptor.sid}get data(){return this.descriptor.data}get dateUpdated(){return this.descriptor.date_updated}get uniqueName(){return this.descriptor.unique_name||null}_update(e){switch(e.date_created=new Date(e.date_created),e.type){case"document_updated":if(e.id<=this.lastEventId){Cn("Document update skipped, current:",this.lastEventId,", remote:",e.id);break}const t=void 0!==this.descriptor.data?xn(this.descriptor.data):null;this.descriptor.last_event_id=e.id,this.descriptor.revision=e.document_revision,this.descriptor.date_updated=e.date_created,this.descriptor.data=e.document_data,this.broadcastEventToListeners("updated",{data:e.document_data,isLocal:!1,previousData:t}),this.services.storage.update(this.type,this.sid,this.uniqueName,{last_event_id:e.id,revision:e.document_revision,date_updated:e.date_created,data:e.document_data});break;case"document_removed":this.onRemoved(!1)}}async set(e,t){const n=t||{};return this.updateMergingQueue.squashAndAdd(n,(t=>this._setUnconditionally(e,t.ttl)))}async mutate(e,t){const n=t||{};return this.updateMergingQueue.add(n,(t=>this._setWithIfMatch(e,t.ttl)))}async update(e,t){return this.mutate((t=>Object.assign(t,e)),t)}async setTtl(e){const t=await this._postUpdateToServer({ttl:e});this.descriptor.date_expires=t.date_expires}async _setUnconditionally(e,t){let n=await this._postUpdateToServer({data:e,revision:void 0,ttl:t});return this._handleSuccessfulUpdateResult(n),this.descriptor.data}async _setWithIfMatch(e,t){let n=e(xn(this.descriptor.data));if(!n)return this.descriptor.data;{let i=this.revision;try{let e=await this._postUpdateToServer({data:n,revision:i,ttl:t});return this._handleSuccessfulUpdateResult(e),this.descriptor.data}catch(t){if(412===t.status)return await this._softSync(),this._setWithIfMatch(e);throw t}}}_handleSuccessfulUpdateResult(e){if(e.last_event_id<=this.descriptor.last_event_id)return;const t=void 0!==this.descriptor.data?xn(this.descriptor.data):null;this.descriptor.revision=e.revision,this.descriptor.data=e.data,this.descriptor.last_event_id=e.last_event_id,this.descriptor.date_expires=e.date_expires,this.descriptor.date_updated=new Date(e.date_updated),this.services.storage.update(this.type,this.sid,this.uniqueName,{last_event_id:e.last_event_id,revision:e.revision,date_updated:e.date_updated,data:e.data}),this.broadcastEventToListeners("updated",{data:this.descriptor.data,isLocal:!0,previousData:t})}async _postUpdateToServer(e){if(this.isDeleted)return Promise.reject(new SyncError("The Document has been removed",404,54100));{const t={data:e.data};void 0!==e.ttl&&(t.ttl=e.ttl);const n=e.revision;try{const i=await this.services.network.post(this.uri,t,n);return{revision:i.body.revision,data:e.data,last_event_id:i.body.last_event_id,date_updated:i.body.date_updated,date_expires:i.body.date_expires}}catch(e){throw 404===e.status&&this.onRemoved(!1),e}}}async _softSync(){return this.services.network.get(this.uri).then((e=>{const t={type:"document_updated",id:e.body.last_event_id,document_revision:e.body.revision,document_data:e.body.data,date_created:e.body.date_updated};return this._update(t),this})).catch((e=>{404===e.status?this.onRemoved(!1):Pn(`Can't get updates for ${this.sid}:`,e)}))}onRemoved(e){if(this.isDeleted)return;const t=void 0!==this.descriptor.data?xn(this.descriptor.data):null;this.isDeleted=!0,this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e,previousData:t})}async removeDocument(){if(this.isDeleted)return Promise.reject(new SyncError("The Document has been removed",404,54100));await this.services.network.delete(this.uri),this.onRemoved(!0)}}class ii extends ti{syncDocumentImpl;get uri(){return this.syncDocumentImpl.uri}get revision(){return this.syncDocumentImpl.revision}get lastEventId(){return this.syncDocumentImpl.lastEventId}get dateExpires(){return this.syncDocumentImpl.dateExpires}static get type(){return ni.type}get type(){return ni.type}get sid(){return this.syncDocumentImpl.sid}get data(){return this.syncDocumentImpl.data}get dateUpdated(){return this.syncDocumentImpl.dateUpdated}get uniqueName(){return this.syncDocumentImpl.uniqueName}constructor(e){super(),this.syncDocumentImpl=e,this.syncDocumentImpl.attach(this)}static removed="removed";static updated="updated";async set(e,t){return this.ensureNotClosed(),this.syncDocumentImpl.set(e,t)}async mutate(e,t){return this.ensureNotClosed(),this.syncDocumentImpl.mutate(e,t)}async update(e,t){return this.ensureNotClosed(),this.syncDocumentImpl.update(e,t)}async setTtl(e){return this.ensureNotClosed(),this.syncDocumentImpl.setTtl(e)}async removeDocument(){return this.ensureNotClosed(),this.syncDocumentImpl.removeDocument()}close(){super.close(),this.syncDocumentImpl.detach(this.listenerUuid)}}vn([sn.validateTypesAsync(sn.pureObject,["undefined",sn.objectSchema("document metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Object,Object]),bn("design:returntype",Promise)],ii.prototype,"set",null),vn([sn.validateTypesAsync("function",["undefined",sn.objectSchema("document metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Function,Object]),bn("design:returntype",Promise)],ii.prototype,"mutate",null),vn([sn.validateTypesAsync(sn.pureObject,["undefined",sn.objectSchema("document metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Object,Object]),bn("design:returntype",Promise)],ii.prototype,"update",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number]),bn("design:returntype",Promise)],ii.prototype,"setTtl",null);class ri{descriptor;constructor(e){this.descriptor=e}get url(){return this.descriptor.url}get revision(){return this.descriptor.revision}get lastEventId(){return this.descriptor.lastEventId}get dateUpdated(){return this.descriptor.dateUpdated}get dateExpires(){return this.descriptor.dateExpires}get index(){return this.descriptor.index}get data(){return this.descriptor.data}get cacheKey(){return this.index}update(e,t,n,i){return this.descriptor.lastEventId=e,this.descriptor.revision=t,this.descriptor.data=n,this.descriptor.dateUpdated=i,this}updateDateExpires(e){this.descriptor.dateExpires=e}}class Paginator{prevPageItemId;nextPageItemId;source;items;constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;this.items=e,this.source=t,this.prevPageItemId=n,this.nextPageItemId=i}async nextPage(){if(!this.hasNextPage)throw new Error("No next page");return this.source({nextPageItemId:this.nextPageItemId})}async prevPage(){if(!this.hasPrevPage)throw new Error("No previous page");return this.source({prevPageItemId:this.prevPageItemId})}get hasNextPage(){return null!==this.nextPageItemId}get hasPrevPage(){return null!==this.prevPageItemId}}class si{parent;left;right;balanceFactor;key;value;constructor(e,t){this.balanceFactor=0,this.key=e,this.value=t,this.parent=null,this.left=null,this.right=null}get isRoot(){return null===this.parent}get isLeaf(){return null===this.left&&null===this.right}get isLeftChild(){return this.parent.left===this}update(e){this.value=e}replace(e,t){e&&(this.left===t?this.left=t:this.right===t&&(this.right=t))}}class ai{isLessThan;isEqual;root;count;constructor(e,t){this.isLessThan=e||((e,t)=>e<t),this.isEqual=t||((e,t)=>e===t),this.root=null,this.count=null}get size(){return this.count}clear(){this.root=null,this.count=0}set(e,t){let n=this.getNode(e);n?n.update(t):this.insert(e,t)}insert(e,t){let n=new si(e,t);if(this.count++,!this.root)return void(this.root=n);let i=this.root;for(;;)if(this.isLessThan(e,i.key)){if(!i.left){i.left=n;break}i=i.left}else{if(!i.right){i.right=n;break}i=i.right}for(n.parent=i,i=n;i.parent;){let e=i.parent,t=e.balanceFactor;if(i.isLeftChild?e.balanceFactor++:e.balanceFactor--,Math.abs(e.balanceFactor)<Math.abs(t))break;if(e.balanceFactor<-1||e.balanceFactor>1){this.rebalance(e);break}i=e}}get(e){let t=this.root;for(;t;){if(this.isEqual(e,t.key))return t.value;t=this.isLessThan(e,t.key)?t.left:t.right}return null}delete(e){let t=this.getNode(e);if(!t||t.key!==e)return null;let n=t.parent,i=t.left,r=t.right;if(!!i!=!!r){let e=i||r;n||e?n&&!e?this.root=e:(n.replace(t,null),this.rebalance(n)):this.root=null}else{let e=t.left;for(;e.right;)e=e.right;if(t.left===e)t.isRoot?(this.root=e,e.parent=null):(t.isLeftChild?t.parent.left=e:t.parent.right=e,e.parent=t.parent),e.right=t.right,e.right.parent=e,e.balanceFactor=t.balanceFactor,t={parent:e,isLeftChild:!0};else{let n=e.parent,i=e.left;n.right=i,i&&(i.parent=n),t.isRoot?(this.root=e,e.parent=null):(t.isLeftChild?t.parent.left=e:t.parent.right=e,e.parent=t.parent),e.right=t.right,e.right.parent=e,e.left=t.left,e.left.parent=e,e.balanceFactor=t.balanceFactor,t={parent:n,isLeftChild:!1}}}for(this.count--;t.parent;){let e=t.parent,n=e.balanceFactor;if(t.isLeftChild?e.balanceFactor-=1:e.balanceFactor+=1,Math.abs(e.balanceFactor)>Math.abs(n)){if(!(e.balanceFactor<-1||e.balanceFactor>1))break;if(this.rebalance(e),0!==e.parent.balanceFactor)break;t=e.parent}else t=e}return null}getNode(e){let t=this.root;for(;t;){if(this.isEqual(e,t.key))return t;t=this.isLessThan(e,t.key)?t.left:t.right}return null}rebalance(e){e.balanceFactor<0?e.right.balanceFactor>0?(this.rotateRight(e.right),this.rotateLeft(e)):this.rotateLeft(e):e.balanceFactor>0&&(e.left.balanceFactor<0?(this.rotateLeft(e.left),this.rotateRight(e)):this.rotateRight(e))}rotateLeft(e){let t=e.right;e.right=t.left,null!==t.left&&(t.left.parent=e),t.parent=e.parent,null===t.parent?this.root=t:e.isLeftChild?t.parent.left=t:t.parent.right=t,t.left=e,e.parent=t,e.balanceFactor=e.balanceFactor+1-Math.min(t.balanceFactor,0),t.balanceFactor=t.balanceFactor+1-Math.max(e.balanceFactor,0)}rotateRight(e){let t=e.left;e.left=t.right,null!==t.right&&(t.right.parent=e),t.parent=e.parent,null===t.parent?this.root=t:e.isLeftChild?t.parent.left=t:t.parent.right=t,t.right=e,e.parent=t,e.balanceFactor=e.balanceFactor-1-Math.min(t.balanceFactor,0),t.balanceFactor=t.balanceFactor-1-Math.max(e.balanceFactor,0)}*[Symbol.iterator](){for(let e of this.getIterator())yield e}getIterator(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return function*(){let n=e.root;for(;n&&!e.isEqual(t,n.key)&&(null!==t||n.left);)n=e.isLessThan(t,n.key)||null===t?n.left:n.right;if(!n)return null;let i=!0;for(;;)if(i)if(yield[n.key,n.value],i=!1,n.right){for(n=n.right;n.left;)n=n.left;i=!0}else{if(!n.parent)break;i=n.parent.left===n,n=n.parent}else{if(!n.parent)break;i=n.parent.left===n,n=n.parent}return null}()}getReverseIterator(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return function*(){let n=e.root;for(;n&&!e.isEqual(t,n.key)&&(null!==t||n.right);)n=e.isLessThan(t,n.key)&&null!==t?n.left:n.right;if(!n)return null;let i=!0;for(;;)if(i)if(yield[n.key,n.value],i=!1,n.left){for(n=n.left;n.right;)n=n.right;i=!0}else{if(!n.parent)break;i=n.parent.right===n,n=n.parent}else{if(!n.parent)break;i=n.parent.right===n,n=n.parent}return null}()}}class oi{_data;lastEventId;isLeftBound;isRightBound;constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];this._data=e,this.lastEventId=t||0,this.isLeftBound=n,this.isRightBound=i}get isValid(){return!0}get value(){return this._data}}class ci{lastEventId;isLeftBound;isRightBound;constructor(e){this.lastEventId=e,this.isLeftBound=!1,this.isRightBound=!1}get isValid(){return!1}get value(){return null}}class ui{items=new ai;beginKey=null;endKey=null;constructor(){this.items.clear()}get size(){return this.items.size}get collectionBegin(){return this.beginKey}get collectionEnd(){return this.endKey}has(e){let t=this.items.get(e);return t?.isValid??!1}exists(e){return!!this.items.get(e)}getValue(e){let t=this.items.get(e);return t?.value??null}get(e){return this.items.get(e)}getNextItem(e,t,n){return null===e?this.getFirstItem(t):n?this.getValue(e):this.getAdjacentItem(e,t)}getFirstItem(e){const t="asc"===e?this.beginKey:this.endKey;if(this.exists(t)){const n=this.items.get(t);return n.isValid?n.value:this.getAdjacentItem(t,e)}return null}getAdjacentItem(e,t){const n="asc"===t?this.items.getIterator(e):this.items.getReverseIterator(e);for(const[e,i]of n){if("asc"===t?i.isRightBound:i.isLeftBound)break;if(i.isValid)return i.value}return null}store(e,t,n){let i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3],r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],s=this.items.get(e);return s&&s.lastEventId>n?s.value:(this.items.set(e,new oi(t,n,s?s.isLeftBound&&i:i,s?s.isRightBound&&r:r)),null!==this.beginKey&&e<this.beginKey&&(this.beginKey=e),null!==this.endKey&&this.endKey<e&&(this.endKey=e),t)}populate(e,t,n){if(!e.length)return;const i=[...e];if(i.sort(((e,t)=>e.cacheKey===t.cacheKey?0:e.cacheKey>t.cacheKey?1:-1)),i.forEach(((e,t)=>{this.store(e.cacheKey,e,e.lastEventId,0===t,t===i.length-1)})),t){const e=i[0].cacheKey;(!this.beginKey||e<this.beginKey)&&(this.beginKey=e)}if(n){const e=i[i.length-1].cacheKey;(!this.endKey||this.endKey<e)&&(this.endKey=e)}}delete(e,t){let n=this.items.get(e);(null===n||null===t||n.lastEventId<t)&&this.items.set(e,new ci(t))}isKnown(e,t){let n=this.items.get(e);return n&&(n.lastEventId??-1)>=t}*getIterator(e){if(null===e&&null!==this.beginKey&&(e=this.beginKey),null!==e)for(let[t,n]of this.items.getIterator(e))if(n.isValid&&(yield n,n.isRightBound))break}*getReverseIterator(e){if(null===e&&null!==this.endKey&&(e=this.endKey),null!==e)for(let[t,n]of this.items.getReverseIterator(e))if(n.isValid&&(yield n,n.isLeftBound))break}forEach(e){if(this.items)for(let[t,n]of this.items)n.isValid&&e(t,n.value)}}var li={exports:{}};!function(e,t){(function(){var n,i="Expected a function",r="__lodash_hash_undefined__",s="__lodash_placeholder__",a=16,o=32,c=64,u=128,l=256,d=1/0,h=9007199254740991,p=NaN,f=4294967295,m=[["ary",u],["bind",1],["bindKey",2],["curry",8],["curryRight",a],["flip",512],["partial",o],["partialRight",c],["rearg",l]],g="[object Arguments]",y="[object Array]",v="[object Boolean]",b="[object Date]",_="[object Error]",w="[object Function]",x="[object GeneratorFunction]",S="[object Map]",k="[object Number]",E="[object Object]",T="[object Promise]",I="[object RegExp]",C="[object Set]",R="[object String]",P="[object Symbol]",M="[object WeakMap]",O="[object ArrayBuffer]",A="[object DataView]",j="[object Float32Array]",$="[object Float64Array]",N="[object Int8Array]",U="[object Int16Array]",L="[object Int32Array]",F="[object Uint8Array]",q="[object Uint8ClampedArray]",D="[object Uint16Array]",B="[object Uint32Array]",z=/\b__p \+= '';/g,W=/\b(__p \+=) '' \+/g,K=/(__e\(.*?\)|\b__t\)) \+\n'';/g,H=/&(?:amp|lt|gt|quot|#39);/g,V=/[&<>"']/g,J=RegExp(H.source),G=RegExp(V.source),Q=/<%-([\s\S]+?)%>/g,X=/<%([\s\S]+?)%>/g,Z=/<%=([\s\S]+?)%>/g,Y=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ee=/^\w*$/,te=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ne=/[\\^$.*+?()[\]{}|]/g,ie=RegExp(ne.source),re=/^\s+/,se=/\s/,ae=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,oe=/\{\n\/\* \[wrapped with (.+)\] \*/,ce=/,? & /,ue=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,le=/[()=,{}\[\]\/\s]/,de=/\\(\\)?/g,he=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,pe=/\w*$/,fe=/^[-+]0x[0-9a-f]+$/i,me=/^0b[01]+$/i,ge=/^\[object .+?Constructor\]$/,ye=/^0o[0-7]+$/i,ve=/^(?:0|[1-9]\d*)$/,be=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,_e=/($^)/,we=/['\n\r\u2028\u2029\\]/g,xe="\\ud800-\\udfff",Se="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",ke="\\u2700-\\u27bf",Ee="a-z\\xdf-\\xf6\\xf8-\\xff",Te="A-Z\\xc0-\\xd6\\xd8-\\xde",Ie="\\ufe0e\\ufe0f",Ce="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Re="['’]",Pe="["+xe+"]",Me="["+Ce+"]",Oe="["+Se+"]",Ae="\\d+",je="["+ke+"]",$e="["+Ee+"]",Ne="[^"+xe+Ce+Ae+ke+Ee+Te+"]",Ue="\\ud83c[\\udffb-\\udfff]",Le="[^"+xe+"]",Fe="(?:\\ud83c[\\udde6-\\uddff]){2}",qe="[\\ud800-\\udbff][\\udc00-\\udfff]",De="["+Te+"]",Be="\\u200d",ze="(?:"+$e+"|"+Ne+")",We="(?:"+De+"|"+Ne+")",Ke="(?:['’](?:d|ll|m|re|s|t|ve))?",He="(?:['’](?:D|LL|M|RE|S|T|VE))?",Ve="(?:"+Oe+"|"+Ue+")"+"?",Je="["+Ie+"]?",Ge=Je+Ve+("(?:"+Be+"(?:"+[Le,Fe,qe].join("|")+")"+Je+Ve+")*"),Qe="(?:"+[je,Fe,qe].join("|")+")"+Ge,Xe="(?:"+[Le+Oe+"?",Oe,Fe,qe,Pe].join("|")+")",Ze=RegExp(Re,"g"),Ye=RegExp(Oe,"g"),et=RegExp(Ue+"(?="+Ue+")|"+Xe+Ge,"g"),tt=RegExp([De+"?"+$e+"+"+Ke+"(?="+[Me,De,"$"].join("|")+")",We+"+"+He+"(?="+[Me,De+ze,"$"].join("|")+")",De+"?"+ze+"+"+Ke,De+"+"+He,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Ae,Qe].join("|"),"g"),nt=RegExp("["+Be+xe+Se+Ie+"]"),it=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,rt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],st=-1,at={};at[j]=at[$]=at[N]=at[U]=at[L]=at[F]=at[q]=at[D]=at[B]=!0,at[g]=at[y]=at[O]=at[v]=at[A]=at[b]=at[_]=at[w]=at[S]=at[k]=at[E]=at[I]=at[C]=at[R]=at[M]=!1;var ot={};ot[g]=ot[y]=ot[O]=ot[A]=ot[v]=ot[b]=ot[j]=ot[$]=ot[N]=ot[U]=ot[L]=ot[S]=ot[k]=ot[E]=ot[I]=ot[C]=ot[R]=ot[P]=ot[F]=ot[q]=ot[D]=ot[B]=!0,ot[_]=ot[w]=ot[M]=!1;var ct={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},ut=parseFloat,lt=parseInt,dt="object"==typeof On&&On&&On.Object===Object&&On,ht="object"==typeof self&&self&&self.Object===Object&&self,pt=dt||ht||Function("return this")(),ft=t&&!t.nodeType&&t,mt=ft&&e&&!e.nodeType&&e,gt=mt&&mt.exports===ft,yt=gt&&dt.process,vt=function(){try{var e=mt&&mt.require&&mt.require("util").types;return e||yt&&yt.binding&&yt.binding("util")}catch(e){}}(),bt=vt&&vt.isArrayBuffer,_t=vt&&vt.isDate,wt=vt&&vt.isMap,xt=vt&&vt.isRegExp,St=vt&&vt.isSet,kt=vt&&vt.isTypedArray;function Et(e,t,n){switch(n.length){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function Tt(e,t,n,i){for(var r=-1,s=null==e?0:e.length;++r<s;){var a=e[r];t(i,a,n(a),e)}return i}function It(e,t){for(var n=-1,i=null==e?0:e.length;++n<i&&!1!==t(e[n],n,e););return e}function Ct(e,t){for(var n=null==e?0:e.length;n--&&!1!==t(e[n],n,e););return e}function Rt(e,t){for(var n=-1,i=null==e?0:e.length;++n<i;)if(!t(e[n],n,e))return!1;return!0}function Pt(e,t){for(var n=-1,i=null==e?0:e.length,r=0,s=[];++n<i;){var a=e[n];t(a,n,e)&&(s[r++]=a)}return s}function Mt(e,t){return!!(null==e?0:e.length)&&Dt(e,t,0)>-1}function Ot(e,t,n){for(var i=-1,r=null==e?0:e.length;++i<r;)if(n(t,e[i]))return!0;return!1}function At(e,t){for(var n=-1,i=null==e?0:e.length,r=Array(i);++n<i;)r[n]=t(e[n],n,e);return r}function jt(e,t){for(var n=-1,i=t.length,r=e.length;++n<i;)e[r+n]=t[n];return e}function $t(e,t,n,i){var r=-1,s=null==e?0:e.length;for(i&&s&&(n=e[++r]);++r<s;)n=t(n,e[r],r,e);return n}function Nt(e,t,n,i){var r=null==e?0:e.length;for(i&&r&&(n=e[--r]);r--;)n=t(n,e[r],r,e);return n}function Ut(e,t){for(var n=-1,i=null==e?0:e.length;++n<i;)if(t(e[n],n,e))return!0;return!1}var Lt=Kt("length");function Ft(e,t,n){var i;return n(e,(function(e,n,r){if(t(e,n,r))return i=n,!1})),i}function qt(e,t,n,i){for(var r=e.length,s=n+(i?1:-1);i?s--:++s<r;)if(t(e[s],s,e))return s;return-1}function Dt(e,t,n){return t==t?function(e,t,n){var i=n-1,r=e.length;for(;++i<r;)if(e[i]===t)return i;return-1}(e,t,n):qt(e,zt,n)}function Bt(e,t,n,i){for(var r=n-1,s=e.length;++r<s;)if(i(e[r],t))return r;return-1}function zt(e){return e!=e}function Wt(e,t){var n=null==e?0:e.length;return n?Jt(e,t)/n:p}function Kt(e){return function(t){return null==t?n:t[e]}}function Ht(e){return function(t){return null==e?n:e[t]}}function Vt(e,t,n,i,r){return r(e,(function(e,r,s){n=i?(i=!1,e):t(n,e,r,s)})),n}function Jt(e,t){for(var i,r=-1,s=e.length;++r<s;){var a=t(e[r]);a!==n&&(i=i===n?a:i+a)}return i}function Gt(e,t){for(var n=-1,i=Array(e);++n<e;)i[n]=t(n);return i}function Qt(e){return e?e.slice(0,fn(e)+1).replace(re,""):e}function Xt(e){return function(t){return e(t)}}function Zt(e,t){return At(t,(function(t){return e[t]}))}function Yt(e,t){return e.has(t)}function en(e,t){for(var n=-1,i=e.length;++n<i&&Dt(t,e[n],0)>-1;);return n}function tn(e,t){for(var n=e.length;n--&&Dt(t,e[n],0)>-1;);return n}var nn=Ht({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),rn=Ht({"&":"&","<":"<",">":">",'"':""","'":"'"});function sn(e){return"\\"+ct[e]}function an(e){return nt.test(e)}function on(e){var t=-1,n=Array(e.size);return e.forEach((function(e,i){n[++t]=[i,e]})),n}function cn(e,t){return function(n){return e(t(n))}}function un(e,t){for(var n=-1,i=e.length,r=0,a=[];++n<i;){var o=e[n];o!==t&&o!==s||(e[n]=s,a[r++]=n)}return a}function ln(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}function dn(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=[e,e]})),n}function hn(e){return an(e)?function(e){var t=et.lastIndex=0;for(;et.test(e);)++t;return t}(e):Lt(e)}function pn(e){return an(e)?function(e){return e.match(et)||[]}(e):function(e){return e.split("")}(e)}function fn(e){for(var t=e.length;t--&&se.test(e.charAt(t)););return t}var mn=Ht({"&":"&","<":"<",">":">",""":'"',"'":"'"});var gn=function e(t){var se,xe=(t=null==t?pt:gn.defaults(pt.Object(),t,gn.pick(pt,rt))).Array,Se=t.Date,ke=t.Error,Ee=t.Function,Te=t.Math,Ie=t.Object,Ce=t.RegExp,Re=t.String,Pe=t.TypeError,Me=xe.prototype,Oe=Ee.prototype,Ae=Ie.prototype,je=t["__core-js_shared__"],$e=Oe.toString,Ne=Ae.hasOwnProperty,Ue=0,Le=(se=/[^.]+$/.exec(je&&je.keys&&je.keys.IE_PROTO||""))?"Symbol(src)_1."+se:"",Fe=Ae.toString,qe=$e.call(Ie),De=pt._,Be=Ce("^"+$e.call(Ne).replace(ne,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ze=gt?t.Buffer:n,We=t.Symbol,Ke=t.Uint8Array,He=ze?ze.allocUnsafe:n,Ve=cn(Ie.getPrototypeOf,Ie),Je=Ie.create,Ge=Ae.propertyIsEnumerable,Qe=Me.splice,Xe=We?We.isConcatSpreadable:n,et=We?We.iterator:n,nt=We?We.toStringTag:n,ct=function(){try{var e=hs(Ie,"defineProperty");return e({},"",{}),e}catch(e){}}(),dt=t.clearTimeout!==pt.clearTimeout&&t.clearTimeout,ht=Se&&Se.now!==pt.Date.now&&Se.now,ft=t.setTimeout!==pt.setTimeout&&t.setTimeout,mt=Te.ceil,yt=Te.floor,vt=Ie.getOwnPropertySymbols,Lt=ze?ze.isBuffer:n,Ht=t.isFinite,yn=Me.join,vn=cn(Ie.keys,Ie),bn=Te.max,_n=Te.min,wn=Se.now,xn=t.parseInt,Sn=Te.random,kn=Me.reverse,En=hs(t,"DataView"),Tn=hs(t,"Map"),In=hs(t,"Promise"),Cn=hs(t,"Set"),Rn=hs(t,"WeakMap"),Pn=hs(Ie,"create"),Mn=Rn&&new Rn,On={},An=Ls(En),jn=Ls(Tn),$n=Ls(In),Nn=Ls(Cn),Un=Ls(Rn),Ln=We?We.prototype:n,Fn=Ln?Ln.valueOf:n,qn=Ln?Ln.toString:n;function Dn(e){if(to(e)&&!Wa(e)&&!(e instanceof Kn)){if(e instanceof Wn)return e;if(Ne.call(e,"__wrapped__"))return Fs(e)}return new Wn(e)}var Bn=function(){function e(){}return function(t){if(!eo(t))return{};if(Je)return Je(t);e.prototype=t;var i=new e;return e.prototype=n,i}}();function zn(){}function Wn(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=n}function Kn(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=f,this.__views__=[]}function Hn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Vn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Jn(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var i=e[t];this.set(i[0],i[1])}}function Gn(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new Jn;++t<n;)this.add(e[t])}function Qn(e){var t=this.__data__=new Vn(e);this.size=t.size}function Xn(e,t){var n=Wa(e),i=!n&&za(e),r=!n&&!i&&Ja(e),s=!n&&!i&&!r&&uo(e),a=n||i||r||s,o=a?Gt(e.length,Re):[],c=o.length;for(var u in e)!t&&!Ne.call(e,u)||a&&("length"==u||r&&("offset"==u||"parent"==u)||s&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||bs(u,c))||o.push(u);return o}function Zn(e){var t=e.length;return t?e[Gi(0,t-1)]:n}function Yn(e,t){return $s(Pr(e),ci(t,0,e.length))}function ei(e){return $s(Pr(e))}function ti(e,t,i){(i!==n&&!qa(e[t],i)||i===n&&!(t in e))&&ai(e,t,i)}function ni(e,t,i){var r=e[t];Ne.call(e,t)&&qa(r,i)&&(i!==n||t in e)||ai(e,t,i)}function ii(e,t){for(var n=e.length;n--;)if(qa(e[n][0],t))return n;return-1}function ri(e,t,n,i){return pi(e,(function(e,r,s){t(i,e,n(e),s)})),i}function si(e,t){return e&&Mr(t,Oo(t),e)}function ai(e,t,n){"__proto__"==t&&ct?ct(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}function oi(e,t){for(var i=-1,r=t.length,s=xe(r),a=null==e;++i<r;)s[i]=a?n:Io(e,t[i]);return s}function ci(e,t,i){return e==e&&(i!==n&&(e=e<=i?e:i),t!==n&&(e=e>=t?e:t)),e}function ui(e,t,i,r,s,a){var o,c=1&t,u=2&t,l=4&t;if(i&&(o=s?i(e,r,s,a):i(e)),o!==n)return o;if(!eo(e))return e;var d=Wa(e);if(d){if(o=function(e){var t=e.length,n=new e.constructor(t);t&&"string"==typeof e[0]&&Ne.call(e,"index")&&(n.index=e.index,n.input=e.input);return n}(e),!c)return Pr(e,o)}else{var h=ms(e),p=h==w||h==x;if(Ja(e))return kr(e,c);if(h==E||h==g||p&&!s){if(o=u||p?{}:ys(e),!c)return u?function(e,t){return Mr(e,fs(e),t)}(e,function(e,t){return e&&Mr(t,Ao(t),e)}(o,e)):function(e,t){return Mr(e,ps(e),t)}(e,si(o,e))}else{if(!ot[h])return s?e:{};o=function(e,t,n){var i=e.constructor;switch(t){case O:return Er(e);case v:case b:return new i(+e);case A:return function(e,t){var n=t?Er(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}(e,n);case j:case $:case N:case U:case L:case F:case q:case D:case B:return Tr(e,n);case S:return new i;case k:case R:return new i(e);case I:return function(e){var t=new e.constructor(e.source,pe.exec(e));return t.lastIndex=e.lastIndex,t}(e);case C:return new i;case P:return r=e,Fn?Ie(Fn.call(r)):{}}var r}(e,h,c)}}a||(a=new Qn);var f=a.get(e);if(f)return f;a.set(e,o),ao(e)?e.forEach((function(n){o.add(ui(n,t,i,n,e,a))})):no(e)&&e.forEach((function(n,r){o.set(r,ui(n,t,i,r,e,a))}));var m=d?n:(l?u?ss:rs:u?Ao:Oo)(e);return It(m||e,(function(n,r){m&&(n=e[r=n]),ni(o,r,ui(n,t,i,r,e,a))})),o}function li(e,t,i){var r=i.length;if(null==e)return!r;for(e=Ie(e);r--;){var s=i[r],a=t[s],o=e[s];if(o===n&&!(s in e)||!a(o))return!1}return!0}function di(e,t,r){if("function"!=typeof e)throw new Pe(i);return Ms((function(){e.apply(n,r)}),t)}function hi(e,t,n,i){var r=-1,s=Mt,a=!0,o=e.length,c=[],u=t.length;if(!o)return c;n&&(t=At(t,Xt(n))),i?(s=Ot,a=!1):t.length>=200&&(s=Yt,a=!1,t=new Gn(t));e:for(;++r<o;){var l=e[r],d=null==n?l:n(l);if(l=i||0!==l?l:0,a&&d==d){for(var h=u;h--;)if(t[h]===d)continue e;c.push(l)}else s(t,d,i)||c.push(l)}return c}Dn.templateSettings={escape:Q,evaluate:X,interpolate:Z,variable:"",imports:{_:Dn}},Dn.prototype=zn.prototype,Dn.prototype.constructor=Dn,Wn.prototype=Bn(zn.prototype),Wn.prototype.constructor=Wn,Kn.prototype=Bn(zn.prototype),Kn.prototype.constructor=Kn,Hn.prototype.clear=function(){this.__data__=Pn?Pn(null):{},this.size=0},Hn.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Hn.prototype.get=function(e){var t=this.__data__;if(Pn){var i=t[e];return i===r?n:i}return Ne.call(t,e)?t[e]:n},Hn.prototype.has=function(e){var t=this.__data__;return Pn?t[e]!==n:Ne.call(t,e)},Hn.prototype.set=function(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=Pn&&t===n?r:t,this},Vn.prototype.clear=function(){this.__data__=[],this.size=0},Vn.prototype.delete=function(e){var t=this.__data__,n=ii(t,e);return!(n<0)&&(n==t.length-1?t.pop():Qe.call(t,n,1),--this.size,!0)},Vn.prototype.get=function(e){var t=this.__data__,i=ii(t,e);return i<0?n:t[i][1]},Vn.prototype.has=function(e){return ii(this.__data__,e)>-1},Vn.prototype.set=function(e,t){var n=this.__data__,i=ii(n,e);return i<0?(++this.size,n.push([e,t])):n[i][1]=t,this},Jn.prototype.clear=function(){this.size=0,this.__data__={hash:new Hn,map:new(Tn||Vn),string:new Hn}},Jn.prototype.delete=function(e){var t=ls(this,e).delete(e);return this.size-=t?1:0,t},Jn.prototype.get=function(e){return ls(this,e).get(e)},Jn.prototype.has=function(e){return ls(this,e).has(e)},Jn.prototype.set=function(e,t){var n=ls(this,e),i=n.size;return n.set(e,t),this.size+=n.size==i?0:1,this},Gn.prototype.add=Gn.prototype.push=function(e){return this.__data__.set(e,r),this},Gn.prototype.has=function(e){return this.__data__.has(e)},Qn.prototype.clear=function(){this.__data__=new Vn,this.size=0},Qn.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},Qn.prototype.get=function(e){return this.__data__.get(e)},Qn.prototype.has=function(e){return this.__data__.has(e)},Qn.prototype.set=function(e,t){var n=this.__data__;if(n instanceof Vn){var i=n.__data__;if(!Tn||i.length<199)return i.push([e,t]),this.size=++n.size,this;n=this.__data__=new Jn(i)}return n.set(e,t),this.size=n.size,this};var pi=jr(wi),fi=jr(xi,!0);function mi(e,t){var n=!0;return pi(e,(function(e,i,r){return n=!!t(e,i,r)})),n}function gi(e,t,i){for(var r=-1,s=e.length;++r<s;){var a=e[r],o=t(a);if(null!=o&&(c===n?o==o&&!co(o):i(o,c)))var c=o,u=a}return u}function yi(e,t){var n=[];return pi(e,(function(e,i,r){t(e,i,r)&&n.push(e)})),n}function vi(e,t,n,i,r){var s=-1,a=e.length;for(n||(n=vs),r||(r=[]);++s<a;){var o=e[s];t>0&&n(o)?t>1?vi(o,t-1,n,i,r):jt(r,o):i||(r[r.length]=o)}return r}var bi=$r(),_i=$r(!0);function wi(e,t){return e&&bi(e,t,Oo)}function xi(e,t){return e&&_i(e,t,Oo)}function Si(e,t){return Pt(t,(function(t){return Xa(e[t])}))}function ki(e,t){for(var i=0,r=(t=_r(t,e)).length;null!=e&&i<r;)e=e[Us(t[i++])];return i&&i==r?e:n}function Ei(e,t,n){var i=t(e);return Wa(e)?i:jt(i,n(e))}function Ti(e){return null==e?e===n?"[object Undefined]":"[object Null]":nt&&nt in Ie(e)?function(e){var t=Ne.call(e,nt),i=e[nt];try{e[nt]=n;var r=!0}catch(e){}var s=Fe.call(e);r&&(t?e[nt]=i:delete e[nt]);return s}(e):function(e){return Fe.call(e)}(e)}function Ii(e,t){return e>t}function Ci(e,t){return null!=e&&Ne.call(e,t)}function Ri(e,t){return null!=e&&t in Ie(e)}function Pi(e,t,i){for(var r=i?Ot:Mt,s=e[0].length,a=e.length,o=a,c=xe(a),u=1/0,l=[];o--;){var d=e[o];o&&t&&(d=At(d,Xt(t))),u=_n(d.length,u),c[o]=!i&&(t||s>=120&&d.length>=120)?new Gn(o&&d):n}d=e[0];var h=-1,p=c[0];e:for(;++h<s&&l.length<u;){var f=d[h],m=t?t(f):f;if(f=i||0!==f?f:0,!(p?Yt(p,m):r(l,m,i))){for(o=a;--o;){var g=c[o];if(!(g?Yt(g,m):r(e[o],m,i)))continue e}p&&p.push(m),l.push(f)}}return l}function Mi(e,t,i){var r=null==(e=Cs(e,t=_r(t,e)))?e:e[Us(Qs(t))];return null==r?n:Et(r,e,i)}function Oi(e){return to(e)&&Ti(e)==g}function Ai(e,t,i,r,s){return e===t||(null==e||null==t||!to(e)&&!to(t)?e!=e&&t!=t:function(e,t,i,r,s,a){var o=Wa(e),c=Wa(t),u=o?y:ms(e),l=c?y:ms(t),d=(u=u==g?E:u)==E,h=(l=l==g?E:l)==E,p=u==l;if(p&&Ja(e)){if(!Ja(t))return!1;o=!0,d=!1}if(p&&!d)return a||(a=new Qn),o||uo(e)?ns(e,t,i,r,s,a):function(e,t,n,i,r,s,a){switch(n){case A:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case O:return!(e.byteLength!=t.byteLength||!s(new Ke(e),new Ke(t)));case v:case b:case k:return qa(+e,+t);case _:return e.name==t.name&&e.message==t.message;case I:case R:return e==t+"";case S:var o=on;case C:var c=1&i;if(o||(o=ln),e.size!=t.size&&!c)return!1;var u=a.get(e);if(u)return u==t;i|=2,a.set(e,t);var l=ns(o(e),o(t),i,r,s,a);return a.delete(e),l;case P:if(Fn)return Fn.call(e)==Fn.call(t)}return!1}(e,t,u,i,r,s,a);if(!(1&i)){var f=d&&Ne.call(e,"__wrapped__"),m=h&&Ne.call(t,"__wrapped__");if(f||m){var w=f?e.value():e,x=m?t.value():t;return a||(a=new Qn),s(w,x,i,r,a)}}if(!p)return!1;return a||(a=new Qn),function(e,t,i,r,s,a){var o=1&i,c=rs(e),u=c.length,l=rs(t),d=l.length;if(u!=d&&!o)return!1;var h=u;for(;h--;){var p=c[h];if(!(o?p in t:Ne.call(t,p)))return!1}var f=a.get(e),m=a.get(t);if(f&&m)return f==t&&m==e;var g=!0;a.set(e,t),a.set(t,e);var y=o;for(;++h<u;){var v=e[p=c[h]],b=t[p];if(r)var _=o?r(b,v,p,t,e,a):r(v,b,p,e,t,a);if(!(_===n?v===b||s(v,b,i,r,a):_)){g=!1;break}y||(y="constructor"==p)}if(g&&!y){var w=e.constructor,x=t.constructor;w==x||!("constructor"in e)||!("constructor"in t)||"function"==typeof w&&w instanceof w&&"function"==typeof x&&x instanceof x||(g=!1)}return a.delete(e),a.delete(t),g}(e,t,i,r,s,a)}(e,t,i,r,Ai,s))}function ji(e,t,i,r){var s=i.length,a=s,o=!r;if(null==e)return!a;for(e=Ie(e);s--;){var c=i[s];if(o&&c[2]?c[1]!==e[c[0]]:!(c[0]in e))return!1}for(;++s<a;){var u=(c=i[s])[0],l=e[u],d=c[1];if(o&&c[2]){if(l===n&&!(u in e))return!1}else{var h=new Qn;if(r)var p=r(l,d,u,e,t,h);if(!(p===n?Ai(d,l,3,r,h):p))return!1}}return!0}function $i(e){return!(!eo(e)||(t=e,Le&&Le in t))&&(Xa(e)?Be:ge).test(Ls(e));var t}function Ni(e){return"function"==typeof e?e:null==e?rc:"object"==typeof e?Wa(e)?Bi(e[0],e[1]):Di(e):pc(e)}function Ui(e){if(!ks(e))return vn(e);var t=[];for(var n in Ie(e))Ne.call(e,n)&&"constructor"!=n&&t.push(n);return t}function Li(e){if(!eo(e))return function(e){var t=[];if(null!=e)for(var n in Ie(e))t.push(n);return t}(e);var t=ks(e),n=[];for(var i in e)("constructor"!=i||!t&&Ne.call(e,i))&&n.push(i);return n}function Fi(e,t){return e<t}function qi(e,t){var n=-1,i=Ha(e)?xe(e.length):[];return pi(e,(function(e,r,s){i[++n]=t(e,r,s)})),i}function Di(e){var t=ds(e);return 1==t.length&&t[0][2]?Ts(t[0][0],t[0][1]):function(n){return n===e||ji(n,e,t)}}function Bi(e,t){return ws(e)&&Es(t)?Ts(Us(e),t):function(i){var r=Io(i,e);return r===n&&r===t?Co(i,e):Ai(t,r,3)}}function zi(e,t,i,r,s){e!==t&&bi(t,(function(a,o){if(s||(s=new Qn),eo(a))!function(e,t,i,r,s,a,o){var c=Rs(e,i),u=Rs(t,i),l=o.get(u);if(l)return void ti(e,i,l);var d=a?a(c,u,i+"",e,t,o):n,h=d===n;if(h){var p=Wa(u),f=!p&&Ja(u),m=!p&&!f&&uo(u);d=u,p||f||m?Wa(c)?d=c:Va(c)?d=Pr(c):f?(h=!1,d=kr(u,!0)):m?(h=!1,d=Tr(u,!0)):d=[]:ro(u)||za(u)?(d=c,za(c)?d=vo(c):eo(c)&&!Xa(c)||(d=ys(u))):h=!1}h&&(o.set(u,d),s(d,u,r,a,o),o.delete(u));ti(e,i,d)}(e,t,o,i,zi,r,s);else{var c=r?r(Rs(e,o),a,o+"",e,t,s):n;c===n&&(c=a),ti(e,o,c)}}),Ao)}function Wi(e,t){var i=e.length;if(i)return bs(t+=t<0?i:0,i)?e[t]:n}function Ki(e,t,n){t=t.length?At(t,(function(e){return Wa(e)?function(t){return ki(t,1===e.length?e[0]:e)}:e})):[rc];var i=-1;t=At(t,Xt(us()));var r=qi(e,(function(e,n,r){var s=At(t,(function(t){return t(e)}));return{criteria:s,index:++i,value:e}}));return function(e,t){var n=e.length;for(e.sort(t);n--;)e[n]=e[n].value;return e}(r,(function(e,t){return function(e,t,n){var i=-1,r=e.criteria,s=t.criteria,a=r.length,o=n.length;for(;++i<a;){var c=Ir(r[i],s[i]);if(c)return i>=o?c:c*("desc"==n[i]?-1:1)}return e.index-t.index}(e,t,n)}))}function Hi(e,t,n){for(var i=-1,r=t.length,s={};++i<r;){var a=t[i],o=ki(e,a);n(o,a)&&er(s,_r(a,e),o)}return s}function Vi(e,t,n,i){var r=i?Bt:Dt,s=-1,a=t.length,o=e;for(e===t&&(t=Pr(t)),n&&(o=At(e,Xt(n)));++s<a;)for(var c=0,u=t[s],l=n?n(u):u;(c=r(o,l,c,i))>-1;)o!==e&&Qe.call(o,c,1),Qe.call(e,c,1);return e}function Ji(e,t){for(var n=e?t.length:0,i=n-1;n--;){var r=t[n];if(n==i||r!==s){var s=r;bs(r)?Qe.call(e,r,1):hr(e,r)}}return e}function Gi(e,t){return e+yt(Sn()*(t-e+1))}function Qi(e,t){var n="";if(!e||t<1||t>h)return n;do{t%2&&(n+=e),(t=yt(t/2))&&(e+=e)}while(t);return n}function Xi(e,t){return Os(Is(e,t,rc),e+"")}function Zi(e){return Zn(Do(e))}function Yi(e,t){var n=Do(e);return $s(n,ci(t,0,n.length))}function er(e,t,i,r){if(!eo(e))return e;for(var s=-1,a=(t=_r(t,e)).length,o=a-1,c=e;null!=c&&++s<a;){var u=Us(t[s]),l=i;if("__proto__"===u||"constructor"===u||"prototype"===u)return e;if(s!=o){var d=c[u];(l=r?r(d,u,c):n)===n&&(l=eo(d)?d:bs(t[s+1])?[]:{})}ni(c,u,l),c=c[u]}return e}var tr=Mn?function(e,t){return Mn.set(e,t),e}:rc,nr=ct?function(e,t){return ct(e,"toString",{configurable:!0,enumerable:!1,value:tc(t),writable:!0})}:rc;function ir(e){return $s(Do(e))}function rr(e,t,n){var i=-1,r=e.length;t<0&&(t=-t>r?0:r+t),(n=n>r?r:n)<0&&(n+=r),r=t>n?0:n-t>>>0,t>>>=0;for(var s=xe(r);++i<r;)s[i]=e[i+t];return s}function sr(e,t){var n;return pi(e,(function(e,i,r){return!(n=t(e,i,r))})),!!n}function ar(e,t,n){var i=0,r=null==e?i:e.length;if("number"==typeof t&&t==t&&r<=2147483647){for(;i<r;){var s=i+r>>>1,a=e[s];null!==a&&!co(a)&&(n?a<=t:a<t)?i=s+1:r=s}return r}return or(e,t,rc,n)}function or(e,t,i,r){var s=0,a=null==e?0:e.length;if(0===a)return 0;for(var o=(t=i(t))!=t,c=null===t,u=co(t),l=t===n;s<a;){var d=yt((s+a)/2),h=i(e[d]),p=h!==n,f=null===h,m=h==h,g=co(h);if(o)var y=r||m;else y=l?m&&(r||p):c?m&&p&&(r||!f):u?m&&p&&!f&&(r||!g):!f&&!g&&(r?h<=t:h<t);y?s=d+1:a=d}return _n(a,4294967294)}function cr(e,t){for(var n=-1,i=e.length,r=0,s=[];++n<i;){var a=e[n],o=t?t(a):a;if(!n||!qa(o,c)){var c=o;s[r++]=0===a?0:a}}return s}function ur(e){return"number"==typeof e?e:co(e)?p:+e}function lr(e){if("string"==typeof e)return e;if(Wa(e))return At(e,lr)+"";if(co(e))return qn?qn.call(e):"";var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function dr(e,t,n){var i=-1,r=Mt,s=e.length,a=!0,o=[],c=o;if(n)a=!1,r=Ot;else if(s>=200){var u=t?null:Qr(e);if(u)return ln(u);a=!1,r=Yt,c=new Gn}else c=t?[]:o;e:for(;++i<s;){var l=e[i],d=t?t(l):l;if(l=n||0!==l?l:0,a&&d==d){for(var h=c.length;h--;)if(c[h]===d)continue e;t&&c.push(d),o.push(l)}else r(c,d,n)||(c!==o&&c.push(d),o.push(l))}return o}function hr(e,t){return null==(e=Cs(e,t=_r(t,e)))||delete e[Us(Qs(t))]}function pr(e,t,n,i){return er(e,t,n(ki(e,t)),i)}function fr(e,t,n,i){for(var r=e.length,s=i?r:-1;(i?s--:++s<r)&&t(e[s],s,e););return n?rr(e,i?0:s,i?s+1:r):rr(e,i?s+1:0,i?r:s)}function mr(e,t){var n=e;return n instanceof Kn&&(n=n.value()),$t(t,(function(e,t){return t.func.apply(t.thisArg,jt([e],t.args))}),n)}function gr(e,t,n){var i=e.length;if(i<2)return i?dr(e[0]):[];for(var r=-1,s=xe(i);++r<i;)for(var a=e[r],o=-1;++o<i;)o!=r&&(s[r]=hi(s[r]||a,e[o],t,n));return dr(vi(s,1),t,n)}function yr(e,t,i){for(var r=-1,s=e.length,a=t.length,o={};++r<s;){var c=r<a?t[r]:n;i(o,e[r],c)}return o}function vr(e){return Va(e)?e:[]}function br(e){return"function"==typeof e?e:rc}function _r(e,t){return Wa(e)?e:ws(e,t)?[e]:Ns(bo(e))}var wr=Xi;function xr(e,t,i){var r=e.length;return i=i===n?r:i,!t&&i>=r?e:rr(e,t,i)}var Sr=dt||function(e){return pt.clearTimeout(e)};function kr(e,t){if(t)return e.slice();var n=e.length,i=He?He(n):new e.constructor(n);return e.copy(i),i}function Er(e){var t=new e.constructor(e.byteLength);return new Ke(t).set(new Ke(e)),t}function Tr(e,t){var n=t?Er(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function Ir(e,t){if(e!==t){var i=e!==n,r=null===e,s=e==e,a=co(e),o=t!==n,c=null===t,u=t==t,l=co(t);if(!c&&!l&&!a&&e>t||a&&o&&u&&!c&&!l||r&&o&&u||!i&&u||!s)return 1;if(!r&&!a&&!l&&e<t||l&&i&&s&&!r&&!a||c&&i&&s||!o&&s||!u)return-1}return 0}function Cr(e,t,n,i){for(var r=-1,s=e.length,a=n.length,o=-1,c=t.length,u=bn(s-a,0),l=xe(c+u),d=!i;++o<c;)l[o]=t[o];for(;++r<a;)(d||r<s)&&(l[n[r]]=e[r]);for(;u--;)l[o++]=e[r++];return l}function Rr(e,t,n,i){for(var r=-1,s=e.length,a=-1,o=n.length,c=-1,u=t.length,l=bn(s-o,0),d=xe(l+u),h=!i;++r<l;)d[r]=e[r];for(var p=r;++c<u;)d[p+c]=t[c];for(;++a<o;)(h||r<s)&&(d[p+n[a]]=e[r++]);return d}function Pr(e,t){var n=-1,i=e.length;for(t||(t=xe(i));++n<i;)t[n]=e[n];return t}function Mr(e,t,i,r){var s=!i;i||(i={});for(var a=-1,o=t.length;++a<o;){var c=t[a],u=r?r(i[c],e[c],c,i,e):n;u===n&&(u=e[c]),s?ai(i,c,u):ni(i,c,u)}return i}function Or(e,t){return function(n,i){var r=Wa(n)?Tt:ri,s=t?t():{};return r(n,e,us(i,2),s)}}function Ar(e){return Xi((function(t,i){var r=-1,s=i.length,a=s>1?i[s-1]:n,o=s>2?i[2]:n;for(a=e.length>3&&"function"==typeof a?(s--,a):n,o&&_s(i[0],i[1],o)&&(a=s<3?n:a,s=1),t=Ie(t);++r<s;){var c=i[r];c&&e(t,c,r,a)}return t}))}function jr(e,t){return function(n,i){if(null==n)return n;if(!Ha(n))return e(n,i);for(var r=n.length,s=t?r:-1,a=Ie(n);(t?s--:++s<r)&&!1!==i(a[s],s,a););return n}}function $r(e){return function(t,n,i){for(var r=-1,s=Ie(t),a=i(t),o=a.length;o--;){var c=a[e?o:++r];if(!1===n(s[c],c,s))break}return t}}function Nr(e){return function(t){var i=an(t=bo(t))?pn(t):n,r=i?i[0]:t.charAt(0),s=i?xr(i,1).join(""):t.slice(1);return r[e]()+s}}function Ur(e){return function(t){return $t(Zo(Wo(t).replace(Ze,"")),e,"")}}function Lr(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var n=Bn(e.prototype),i=e.apply(n,t);return eo(i)?i:n}}function Fr(e){return function(t,i,r){var s=Ie(t);if(!Ha(t)){var a=us(i,3);t=Oo(t),i=function(e){return a(s[e],e,s)}}var o=e(t,i,r);return o>-1?s[a?t[o]:o]:n}}function qr(e){return is((function(t){var r=t.length,s=r,a=Wn.prototype.thru;for(e&&t.reverse();s--;){var o=t[s];if("function"!=typeof o)throw new Pe(i);if(a&&!c&&"wrapper"==os(o))var c=new Wn([],!0)}for(s=c?s:r;++s<r;){var u=os(o=t[s]),l="wrapper"==u?as(o):n;c=l&&xs(l[0])&&424==l[1]&&!l[4].length&&1==l[9]?c[os(l[0])].apply(c,l[3]):1==o.length&&xs(o)?c[u]():c.thru(o)}return function(){var e=arguments,n=e[0];if(c&&1==e.length&&Wa(n))return c.plant(n).value();for(var i=0,s=r?t[i].apply(this,e):n;++i<r;)s=t[i].call(this,s);return s}}))}function Dr(e,t,i,r,s,a,o,c,l,d){var h=t&u,p=1&t,f=2&t,m=24&t,g=512&t,y=f?n:Lr(e);return function u(){for(var v=arguments.length,b=xe(v),_=v;_--;)b[_]=arguments[_];if(m)var w=cs(u),x=function(e,t){for(var n=e.length,i=0;n--;)e[n]===t&&++i;return i}(b,w);if(r&&(b=Cr(b,r,s,m)),a&&(b=Rr(b,a,o,m)),v-=x,m&&v<d){var S=un(b,w);return Jr(e,t,Dr,u.placeholder,i,b,S,c,l,d-v)}var k=p?i:this,E=f?k[e]:e;return v=b.length,c?b=function(e,t){var i=e.length,r=_n(t.length,i),s=Pr(e);for(;r--;){var a=t[r];e[r]=bs(a,i)?s[a]:n}return e}(b,c):g&&v>1&&b.reverse(),h&&l<v&&(b.length=l),this&&this!==pt&&this instanceof u&&(E=y||Lr(E)),E.apply(k,b)}}function Br(e,t){return function(n,i){return function(e,t,n,i){return wi(e,(function(e,r,s){t(i,n(e),r,s)})),i}(n,e,t(i),{})}}function zr(e,t){return function(i,r){var s;if(i===n&&r===n)return t;if(i!==n&&(s=i),r!==n){if(s===n)return r;"string"==typeof i||"string"==typeof r?(i=lr(i),r=lr(r)):(i=ur(i),r=ur(r)),s=e(i,r)}return s}}function Wr(e){return is((function(t){return t=At(t,Xt(us())),Xi((function(n){var i=this;return e(t,(function(e){return Et(e,i,n)}))}))}))}function Kr(e,t){var i=(t=t===n?" ":lr(t)).length;if(i<2)return i?Qi(t,e):t;var r=Qi(t,mt(e/hn(t)));return an(t)?xr(pn(r),0,e).join(""):r.slice(0,e)}function Hr(e){return function(t,i,r){return r&&"number"!=typeof r&&_s(t,i,r)&&(i=r=n),t=fo(t),i===n?(i=t,t=0):i=fo(i),function(e,t,n,i){for(var r=-1,s=bn(mt((t-e)/(n||1)),0),a=xe(s);s--;)a[i?s:++r]=e,e+=n;return a}(t,i,r=r===n?t<i?1:-1:fo(r),e)}}function Vr(e){return function(t,n){return"string"==typeof t&&"string"==typeof n||(t=yo(t),n=yo(n)),e(t,n)}}function Jr(e,t,i,r,s,a,u,l,d,h){var p=8&t;t|=p?o:c,4&(t&=~(p?c:o))||(t&=-4);var f=[e,t,s,p?a:n,p?u:n,p?n:a,p?n:u,l,d,h],m=i.apply(n,f);return xs(e)&&Ps(m,f),m.placeholder=r,As(m,e,t)}function Gr(e){var t=Te[e];return function(e,n){if(e=yo(e),(n=null==n?0:_n(mo(n),292))&&Ht(e)){var i=(bo(e)+"e").split("e");return+((i=(bo(t(i[0]+"e"+(+i[1]+n)))+"e").split("e"))[0]+"e"+(+i[1]-n))}return t(e)}}var Qr=Cn&&1/ln(new Cn([,-0]))[1]==d?function(e){return new Cn(e)}:uc;function Xr(e){return function(t){var n=ms(t);return n==S?on(t):n==C?dn(t):function(e,t){return At(t,(function(t){return[t,e[t]]}))}(t,e(t))}}function Zr(e,t,r,d,h,p,f,m){var g=2&t;if(!g&&"function"!=typeof e)throw new Pe(i);var y=d?d.length:0;if(y||(t&=-97,d=h=n),f=f===n?f:bn(mo(f),0),m=m===n?m:mo(m),y-=h?h.length:0,t&c){var v=d,b=h;d=h=n}var _=g?n:as(e),w=[e,t,r,d,h,v,b,p,f,m];if(_&&function(e,t){var n=e[1],i=t[1],r=n|i,a=r<131,o=i==u&&8==n||i==u&&n==l&&e[7].length<=t[8]||384==i&&t[7].length<=t[8]&&8==n;if(!a&&!o)return e;1&i&&(e[2]=t[2],r|=1&n?0:4);var c=t[3];if(c){var d=e[3];e[3]=d?Cr(d,c,t[4]):c,e[4]=d?un(e[3],s):t[4]}(c=t[5])&&(d=e[5],e[5]=d?Rr(d,c,t[6]):c,e[6]=d?un(e[5],s):t[6]);(c=t[7])&&(e[7]=c);i&u&&(e[8]=null==e[8]?t[8]:_n(e[8],t[8]));null==e[9]&&(e[9]=t[9]);e[0]=t[0],e[1]=r}(w,_),e=w[0],t=w[1],r=w[2],d=w[3],h=w[4],!(m=w[9]=w[9]===n?g?0:e.length:bn(w[9]-y,0))&&24&t&&(t&=-25),t&&1!=t)x=8==t||t==a?function(e,t,i){var r=Lr(e);return function s(){for(var a=arguments.length,o=xe(a),c=a,u=cs(s);c--;)o[c]=arguments[c];var l=a<3&&o[0]!==u&&o[a-1]!==u?[]:un(o,u);return(a-=l.length)<i?Jr(e,t,Dr,s.placeholder,n,o,l,n,n,i-a):Et(this&&this!==pt&&this instanceof s?r:e,this,o)}}(e,t,m):t!=o&&33!=t||h.length?Dr.apply(n,w):function(e,t,n,i){var r=1&t,s=Lr(e);return function t(){for(var a=-1,o=arguments.length,c=-1,u=i.length,l=xe(u+o),d=this&&this!==pt&&this instanceof t?s:e;++c<u;)l[c]=i[c];for(;o--;)l[c++]=arguments[++a];return Et(d,r?n:this,l)}}(e,t,r,d);else var x=function(e,t,n){var i=1&t,r=Lr(e);return function t(){return(this&&this!==pt&&this instanceof t?r:e).apply(i?n:this,arguments)}}(e,t,r);return As((_?tr:Ps)(x,w),e,t)}function Yr(e,t,i,r){return e===n||qa(e,Ae[i])&&!Ne.call(r,i)?t:e}function es(e,t,i,r,s,a){return eo(e)&&eo(t)&&(a.set(t,e),zi(e,t,n,es,a),a.delete(t)),e}function ts(e){return ro(e)?n:e}function ns(e,t,i,r,s,a){var o=1&i,c=e.length,u=t.length;if(c!=u&&!(o&&u>c))return!1;var l=a.get(e),d=a.get(t);if(l&&d)return l==t&&d==e;var h=-1,p=!0,f=2&i?new Gn:n;for(a.set(e,t),a.set(t,e);++h<c;){var m=e[h],g=t[h];if(r)var y=o?r(g,m,h,t,e,a):r(m,g,h,e,t,a);if(y!==n){if(y)continue;p=!1;break}if(f){if(!Ut(t,(function(e,t){if(!Yt(f,t)&&(m===e||s(m,e,i,r,a)))return f.push(t)}))){p=!1;break}}else if(m!==g&&!s(m,g,i,r,a)){p=!1;break}}return a.delete(e),a.delete(t),p}function is(e){return Os(Is(e,n,Ks),e+"")}function rs(e){return Ei(e,Oo,ps)}function ss(e){return Ei(e,Ao,fs)}var as=Mn?function(e){return Mn.get(e)}:uc;function os(e){for(var t=e.name+"",n=On[t],i=Ne.call(On,t)?n.length:0;i--;){var r=n[i],s=r.func;if(null==s||s==e)return r.name}return t}function cs(e){return(Ne.call(Dn,"placeholder")?Dn:e).placeholder}function us(){var e=Dn.iteratee||sc;return e=e===sc?Ni:e,arguments.length?e(arguments[0],arguments[1]):e}function ls(e,t){var n=e.__data__;return function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?n["string"==typeof t?"string":"hash"]:n.map}function ds(e){for(var t=Oo(e),n=t.length;n--;){var i=t[n],r=e[i];t[n]=[i,r,Es(r)]}return t}function hs(e,t){var i=function(e,t){return null==e?n:e[t]}(e,t);return $i(i)?i:n}var ps=vt?function(e){return null==e?[]:(e=Ie(e),Pt(vt(e),(function(t){return Ge.call(e,t)})))}:gc,fs=vt?function(e){for(var t=[];e;)jt(t,ps(e)),e=Ve(e);return t}:gc,ms=Ti;function gs(e,t,n){for(var i=-1,r=(t=_r(t,e)).length,s=!1;++i<r;){var a=Us(t[i]);if(!(s=null!=e&&n(e,a)))break;e=e[a]}return s||++i!=r?s:!!(r=null==e?0:e.length)&&Ya(r)&&bs(a,r)&&(Wa(e)||za(e))}function ys(e){return"function"!=typeof e.constructor||ks(e)?{}:Bn(Ve(e))}function vs(e){return Wa(e)||za(e)||!!(Xe&&e&&e[Xe])}function bs(e,t){var n=typeof e;return!!(t=null==t?h:t)&&("number"==n||"symbol"!=n&&ve.test(e))&&e>-1&&e%1==0&&e<t}function _s(e,t,n){if(!eo(n))return!1;var i=typeof t;return!!("number"==i?Ha(n)&&bs(t,n.length):"string"==i&&t in n)&&qa(n[t],e)}function ws(e,t){if(Wa(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!co(e))||(ee.test(e)||!Y.test(e)||null!=t&&e in Ie(t))}function xs(e){var t=os(e),n=Dn[t];if("function"!=typeof n||!(t in Kn.prototype))return!1;if(e===n)return!0;var i=as(n);return!!i&&e===i[0]}(En&&ms(new En(new ArrayBuffer(1)))!=A||Tn&&ms(new Tn)!=S||In&&ms(In.resolve())!=T||Cn&&ms(new Cn)!=C||Rn&&ms(new Rn)!=M)&&(ms=function(e){var t=Ti(e),i=t==E?e.constructor:n,r=i?Ls(i):"";if(r)switch(r){case An:return A;case jn:return S;case $n:return T;case Nn:return C;case Un:return M}return t});var Ss=je?Xa:yc;function ks(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Ae)}function Es(e){return e==e&&!eo(e)}function Ts(e,t){return function(i){return null!=i&&(i[e]===t&&(t!==n||e in Ie(i)))}}function Is(e,t,i){return t=bn(t===n?e.length-1:t,0),function(){for(var n=arguments,r=-1,s=bn(n.length-t,0),a=xe(s);++r<s;)a[r]=n[t+r];r=-1;for(var o=xe(t+1);++r<t;)o[r]=n[r];return o[t]=i(a),Et(e,this,o)}}function Cs(e,t){return t.length<2?e:ki(e,rr(t,0,-1))}function Rs(e,t){if(("constructor"!==t||"function"!=typeof e[t])&&"__proto__"!=t)return e[t]}var Ps=js(tr),Ms=ft||function(e,t){return pt.setTimeout(e,t)},Os=js(nr);function As(e,t,n){var i=t+"";return Os(e,function(e,t){var n=t.length;if(!n)return e;var i=n-1;return t[i]=(n>1?"& ":"")+t[i],t=t.join(n>2?", ":" "),e.replace(ae,"{\n/* [wrapped with "+t+"] */\n")}(i,function(e,t){return It(m,(function(n){var i="_."+n[0];t&n[1]&&!Mt(e,i)&&e.push(i)})),e.sort()}(function(e){var t=e.match(oe);return t?t[1].split(ce):[]}(i),n)))}function js(e){var t=0,i=0;return function(){var r=wn(),s=16-(r-i);if(i=r,s>0){if(++t>=800)return arguments[0]}else t=0;return e.apply(n,arguments)}}function $s(e,t){var i=-1,r=e.length,s=r-1;for(t=t===n?r:t;++i<t;){var a=Gi(i,s),o=e[a];e[a]=e[i],e[i]=o}return e.length=t,e}var Ns=function(e){var t=ja(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(te,(function(e,n,i,r){t.push(i?r.replace(de,"$1"):n||e)})),t}));function Us(e){if("string"==typeof e||co(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t}function Ls(e){if(null!=e){try{return $e.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Fs(e){if(e instanceof Kn)return e.clone();var t=new Wn(e.__wrapped__,e.__chain__);return t.__actions__=Pr(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t}var qs=Xi((function(e,t){return Va(e)?hi(e,vi(t,1,Va,!0)):[]})),Ds=Xi((function(e,t){var i=Qs(t);return Va(i)&&(i=n),Va(e)?hi(e,vi(t,1,Va,!0),us(i,2)):[]})),Bs=Xi((function(e,t){var i=Qs(t);return Va(i)&&(i=n),Va(e)?hi(e,vi(t,1,Va,!0),n,i):[]}));function zs(e,t,n){var i=null==e?0:e.length;if(!i)return-1;var r=null==n?0:mo(n);return r<0&&(r=bn(i+r,0)),qt(e,us(t,3),r)}function Ws(e,t,i){var r=null==e?0:e.length;if(!r)return-1;var s=r-1;return i!==n&&(s=mo(i),s=i<0?bn(r+s,0):_n(s,r-1)),qt(e,us(t,3),s,!0)}function Ks(e){return(null==e?0:e.length)?vi(e,1):[]}function Hs(e){return e&&e.length?e[0]:n}var Vs=Xi((function(e){var t=At(e,vr);return t.length&&t[0]===e[0]?Pi(t):[]})),Js=Xi((function(e){var t=Qs(e),i=At(e,vr);return t===Qs(i)?t=n:i.pop(),i.length&&i[0]===e[0]?Pi(i,us(t,2)):[]})),Gs=Xi((function(e){var t=Qs(e),i=At(e,vr);return(t="function"==typeof t?t:n)&&i.pop(),i.length&&i[0]===e[0]?Pi(i,n,t):[]}));function Qs(e){var t=null==e?0:e.length;return t?e[t-1]:n}var Xs=Xi(Zs);function Zs(e,t){return e&&e.length&&t&&t.length?Vi(e,t):e}var Ys=is((function(e,t){var n=null==e?0:e.length,i=oi(e,t);return Ji(e,At(t,(function(e){return bs(e,n)?+e:e})).sort(Ir)),i}));function ea(e){return null==e?e:kn.call(e)}var ta=Xi((function(e){return dr(vi(e,1,Va,!0))})),na=Xi((function(e){var t=Qs(e);return Va(t)&&(t=n),dr(vi(e,1,Va,!0),us(t,2))})),ia=Xi((function(e){var t=Qs(e);return t="function"==typeof t?t:n,dr(vi(e,1,Va,!0),n,t)}));function ra(e){if(!e||!e.length)return[];var t=0;return e=Pt(e,(function(e){if(Va(e))return t=bn(e.length,t),!0})),Gt(t,(function(t){return At(e,Kt(t))}))}function sa(e,t){if(!e||!e.length)return[];var i=ra(e);return null==t?i:At(i,(function(e){return Et(t,n,e)}))}var aa=Xi((function(e,t){return Va(e)?hi(e,t):[]})),oa=Xi((function(e){return gr(Pt(e,Va))})),ca=Xi((function(e){var t=Qs(e);return Va(t)&&(t=n),gr(Pt(e,Va),us(t,2))})),ua=Xi((function(e){var t=Qs(e);return t="function"==typeof t?t:n,gr(Pt(e,Va),n,t)})),la=Xi(ra);var da=Xi((function(e){var t=e.length,i=t>1?e[t-1]:n;return i="function"==typeof i?(e.pop(),i):n,sa(e,i)}));function ha(e){var t=Dn(e);return t.__chain__=!0,t}function pa(e,t){return t(e)}var fa=is((function(e){var t=e.length,i=t?e[0]:0,r=this.__wrapped__,s=function(t){return oi(t,e)};return!(t>1||this.__actions__.length)&&r instanceof Kn&&bs(i)?((r=r.slice(i,+i+(t?1:0))).__actions__.push({func:pa,args:[s],thisArg:n}),new Wn(r,this.__chain__).thru((function(e){return t&&!e.length&&e.push(n),e}))):this.thru(s)}));var ma=Or((function(e,t,n){Ne.call(e,n)?++e[n]:ai(e,n,1)}));var ga=Fr(zs),ya=Fr(Ws);function va(e,t){return(Wa(e)?It:pi)(e,us(t,3))}function ba(e,t){return(Wa(e)?Ct:fi)(e,us(t,3))}var _a=Or((function(e,t,n){Ne.call(e,n)?e[n].push(t):ai(e,n,[t])}));var wa=Xi((function(e,t,n){var i=-1,r="function"==typeof t,s=Ha(e)?xe(e.length):[];return pi(e,(function(e){s[++i]=r?Et(t,e,n):Mi(e,t,n)})),s})),xa=Or((function(e,t,n){ai(e,n,t)}));function Sa(e,t){return(Wa(e)?At:qi)(e,us(t,3))}var ka=Or((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]}));var Ea=Xi((function(e,t){if(null==e)return[];var n=t.length;return n>1&&_s(e,t[0],t[1])?t=[]:n>2&&_s(t[0],t[1],t[2])&&(t=[t[0]]),Ki(e,vi(t,1),[])})),Ta=ht||function(){return pt.Date.now()};function Ia(e,t,i){return t=i?n:t,t=e&&null==t?e.length:t,Zr(e,u,n,n,n,n,t)}function Ca(e,t){var r;if("function"!=typeof t)throw new Pe(i);return e=mo(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=n),r}}var Ra=Xi((function(e,t,n){var i=1;if(n.length){var r=un(n,cs(Ra));i|=o}return Zr(e,i,t,n,r)})),Pa=Xi((function(e,t,n){var i=3;if(n.length){var r=un(n,cs(Pa));i|=o}return Zr(t,i,e,n,r)}));function Ma(e,t,r){var s,a,o,c,u,l,d=0,h=!1,p=!1,f=!0;if("function"!=typeof e)throw new Pe(i);function m(t){var i=s,r=a;return s=a=n,d=t,c=e.apply(r,i)}function g(e){var i=e-l;return l===n||i>=t||i<0||p&&e-d>=o}function y(){var e=Ta();if(g(e))return v(e);u=Ms(y,function(e){var n=t-(e-l);return p?_n(n,o-(e-d)):n}(e))}function v(e){return u=n,f&&s?m(e):(s=a=n,c)}function b(){var e=Ta(),i=g(e);if(s=arguments,a=this,l=e,i){if(u===n)return function(e){return d=e,u=Ms(y,t),h?m(e):c}(l);if(p)return Sr(u),u=Ms(y,t),m(l)}return u===n&&(u=Ms(y,t)),c}return t=yo(t)||0,eo(r)&&(h=!!r.leading,o=(p="maxWait"in r)?bn(yo(r.maxWait)||0,t):o,f="trailing"in r?!!r.trailing:f),b.cancel=function(){u!==n&&Sr(u),d=0,s=l=a=u=n},b.flush=function(){return u===n?c:v(Ta())},b}var Oa=Xi((function(e,t){return di(e,1,t)})),Aa=Xi((function(e,t,n){return di(e,yo(t)||0,n)}));function ja(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new Pe(i);var n=function(){var i=arguments,r=t?t.apply(this,i):i[0],s=n.cache;if(s.has(r))return s.get(r);var a=e.apply(this,i);return n.cache=s.set(r,a)||s,a};return n.cache=new(ja.Cache||Jn),n}function $a(e){if("function"!=typeof e)throw new Pe(i);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}ja.Cache=Jn;var Na=wr((function(e,t){var n=(t=1==t.length&&Wa(t[0])?At(t[0],Xt(us())):At(vi(t,1),Xt(us()))).length;return Xi((function(i){for(var r=-1,s=_n(i.length,n);++r<s;)i[r]=t[r].call(this,i[r]);return Et(e,this,i)}))})),Ua=Xi((function(e,t){var i=un(t,cs(Ua));return Zr(e,o,n,t,i)})),La=Xi((function(e,t){var i=un(t,cs(La));return Zr(e,c,n,t,i)})),Fa=is((function(e,t){return Zr(e,l,n,n,n,t)}));function qa(e,t){return e===t||e!=e&&t!=t}var Da=Vr(Ii),Ba=Vr((function(e,t){return e>=t})),za=Oi(function(){return arguments}())?Oi:function(e){return to(e)&&Ne.call(e,"callee")&&!Ge.call(e,"callee")},Wa=xe.isArray,Ka=bt?Xt(bt):function(e){return to(e)&&Ti(e)==O};function Ha(e){return null!=e&&Ya(e.length)&&!Xa(e)}function Va(e){return to(e)&&Ha(e)}var Ja=Lt||yc,Ga=_t?Xt(_t):function(e){return to(e)&&Ti(e)==b};function Qa(e){if(!to(e))return!1;var t=Ti(e);return t==_||"[object DOMException]"==t||"string"==typeof e.message&&"string"==typeof e.name&&!ro(e)}function Xa(e){if(!eo(e))return!1;var t=Ti(e);return t==w||t==x||"[object AsyncFunction]"==t||"[object Proxy]"==t}function Za(e){return"number"==typeof e&&e==mo(e)}function Ya(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=h}function eo(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}function to(e){return null!=e&&"object"==typeof e}var no=wt?Xt(wt):function(e){return to(e)&&ms(e)==S};function io(e){return"number"==typeof e||to(e)&&Ti(e)==k}function ro(e){if(!to(e)||Ti(e)!=E)return!1;var t=Ve(e);if(null===t)return!0;var n=Ne.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&$e.call(n)==qe}var so=xt?Xt(xt):function(e){return to(e)&&Ti(e)==I};var ao=St?Xt(St):function(e){return to(e)&&ms(e)==C};function oo(e){return"string"==typeof e||!Wa(e)&&to(e)&&Ti(e)==R}function co(e){return"symbol"==typeof e||to(e)&&Ti(e)==P}var uo=kt?Xt(kt):function(e){return to(e)&&Ya(e.length)&&!!at[Ti(e)]};var lo=Vr(Fi),ho=Vr((function(e,t){return e<=t}));function po(e){if(!e)return[];if(Ha(e))return oo(e)?pn(e):Pr(e);if(et&&e[et])return function(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}(e[et]());var t=ms(e);return(t==S?on:t==C?ln:Do)(e)}function fo(e){return e?(e=yo(e))===d||e===-1/0?17976931348623157e292*(e<0?-1:1):e==e?e:0:0===e?e:0}function mo(e){var t=fo(e),n=t%1;return t==t?n?t-n:t:0}function go(e){return e?ci(mo(e),0,f):0}function yo(e){if("number"==typeof e)return e;if(co(e))return p;if(eo(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=eo(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Qt(e);var n=me.test(e);return n||ye.test(e)?lt(e.slice(2),n?2:8):fe.test(e)?p:+e}function vo(e){return Mr(e,Ao(e))}function bo(e){return null==e?"":lr(e)}var _o=Ar((function(e,t){if(ks(t)||Ha(t))Mr(t,Oo(t),e);else for(var n in t)Ne.call(t,n)&&ni(e,n,t[n])})),wo=Ar((function(e,t){Mr(t,Ao(t),e)})),xo=Ar((function(e,t,n,i){Mr(t,Ao(t),e,i)})),So=Ar((function(e,t,n,i){Mr(t,Oo(t),e,i)})),ko=is(oi);var Eo=Xi((function(e,t){e=Ie(e);var i=-1,r=t.length,s=r>2?t[2]:n;for(s&&_s(t[0],t[1],s)&&(r=1);++i<r;)for(var a=t[i],o=Ao(a),c=-1,u=o.length;++c<u;){var l=o[c],d=e[l];(d===n||qa(d,Ae[l])&&!Ne.call(e,l))&&(e[l]=a[l])}return e})),To=Xi((function(e){return e.push(n,es),Et($o,n,e)}));function Io(e,t,i){var r=null==e?n:ki(e,t);return r===n?i:r}function Co(e,t){return null!=e&&gs(e,t,Ri)}var Ro=Br((function(e,t,n){null!=t&&"function"!=typeof t.toString&&(t=Fe.call(t)),e[t]=n}),tc(rc)),Po=Br((function(e,t,n){null!=t&&"function"!=typeof t.toString&&(t=Fe.call(t)),Ne.call(e,t)?e[t].push(n):e[t]=[n]}),us),Mo=Xi(Mi);function Oo(e){return Ha(e)?Xn(e):Ui(e)}function Ao(e){return Ha(e)?Xn(e,!0):Li(e)}var jo=Ar((function(e,t,n){zi(e,t,n)})),$o=Ar((function(e,t,n,i){zi(e,t,n,i)})),No=is((function(e,t){var n={};if(null==e)return n;var i=!1;t=At(t,(function(t){return t=_r(t,e),i||(i=t.length>1),t})),Mr(e,ss(e),n),i&&(n=ui(n,7,ts));for(var r=t.length;r--;)hr(n,t[r]);return n}));var Uo=is((function(e,t){return null==e?{}:function(e,t){return Hi(e,t,(function(t,n){return Co(e,n)}))}(e,t)}));function Lo(e,t){if(null==e)return{};var n=At(ss(e),(function(e){return[e]}));return t=us(t),Hi(e,n,(function(e,n){return t(e,n[0])}))}var Fo=Xr(Oo),qo=Xr(Ao);function Do(e){return null==e?[]:Zt(e,Oo(e))}var Bo=Ur((function(e,t,n){return t=t.toLowerCase(),e+(n?zo(t):t)}));function zo(e){return Xo(bo(e).toLowerCase())}function Wo(e){return(e=bo(e))&&e.replace(be,nn).replace(Ye,"")}var Ko=Ur((function(e,t,n){return e+(n?"-":"")+t.toLowerCase()})),Ho=Ur((function(e,t,n){return e+(n?" ":"")+t.toLowerCase()})),Vo=Nr("toLowerCase");var Jo=Ur((function(e,t,n){return e+(n?"_":"")+t.toLowerCase()}));var Go=Ur((function(e,t,n){return e+(n?" ":"")+Xo(t)}));var Qo=Ur((function(e,t,n){return e+(n?" ":"")+t.toUpperCase()})),Xo=Nr("toUpperCase");function Zo(e,t,i){return e=bo(e),(t=i?n:t)===n?function(e){return it.test(e)}(e)?function(e){return e.match(tt)||[]}(e):function(e){return e.match(ue)||[]}(e):e.match(t)||[]}var Yo=Xi((function(e,t){try{return Et(e,n,t)}catch(e){return Qa(e)?e:new ke(e)}})),ec=is((function(e,t){return It(t,(function(t){t=Us(t),ai(e,t,Ra(e[t],e))})),e}));function tc(e){return function(){return e}}var nc=qr(),ic=qr(!0);function rc(e){return e}function sc(e){return Ni("function"==typeof e?e:ui(e,1))}var ac=Xi((function(e,t){return function(n){return Mi(n,e,t)}})),oc=Xi((function(e,t){return function(n){return Mi(e,n,t)}}));function cc(e,t,n){var i=Oo(t),r=Si(t,i);null!=n||eo(t)&&(r.length||!i.length)||(n=t,t=e,e=this,r=Si(t,Oo(t)));var s=!(eo(n)&&"chain"in n&&!n.chain),a=Xa(e);return It(r,(function(n){var i=t[n];e[n]=i,a&&(e.prototype[n]=function(){var t=this.__chain__;if(s||t){var n=e(this.__wrapped__);return(n.__actions__=Pr(this.__actions__)).push({func:i,args:arguments,thisArg:e}),n.__chain__=t,n}return i.apply(e,jt([this.value()],arguments))})})),e}function uc(){}var lc=Wr(At),dc=Wr(Rt),hc=Wr(Ut);function pc(e){return ws(e)?Kt(Us(e)):function(e){return function(t){return ki(t,e)}}(e)}var fc=Hr(),mc=Hr(!0);function gc(){return[]}function yc(){return!1}var vc=zr((function(e,t){return e+t}),0),bc=Gr("ceil"),_c=zr((function(e,t){return e/t}),1),wc=Gr("floor");var xc,Sc=zr((function(e,t){return e*t}),1),kc=Gr("round"),Ec=zr((function(e,t){return e-t}),0);return Dn.after=function(e,t){if("function"!=typeof t)throw new Pe(i);return e=mo(e),function(){if(--e<1)return t.apply(this,arguments)}},Dn.ary=Ia,Dn.assign=_o,Dn.assignIn=wo,Dn.assignInWith=xo,Dn.assignWith=So,Dn.at=ko,Dn.before=Ca,Dn.bind=Ra,Dn.bindAll=ec,Dn.bindKey=Pa,Dn.castArray=function(){if(!arguments.length)return[];var e=arguments[0];return Wa(e)?e:[e]},Dn.chain=ha,Dn.chunk=function(e,t,i){t=(i?_s(e,t,i):t===n)?1:bn(mo(t),0);var r=null==e?0:e.length;if(!r||t<1)return[];for(var s=0,a=0,o=xe(mt(r/t));s<r;)o[a++]=rr(e,s,s+=t);return o},Dn.compact=function(e){for(var t=-1,n=null==e?0:e.length,i=0,r=[];++t<n;){var s=e[t];s&&(r[i++]=s)}return r},Dn.concat=function(){var e=arguments.length;if(!e)return[];for(var t=xe(e-1),n=arguments[0],i=e;i--;)t[i-1]=arguments[i];return jt(Wa(n)?Pr(n):[n],vi(t,1))},Dn.cond=function(e){var t=null==e?0:e.length,n=us();return e=t?At(e,(function(e){if("function"!=typeof e[1])throw new Pe(i);return[n(e[0]),e[1]]})):[],Xi((function(n){for(var i=-1;++i<t;){var r=e[i];if(Et(r[0],this,n))return Et(r[1],this,n)}}))},Dn.conforms=function(e){return function(e){var t=Oo(e);return function(n){return li(n,e,t)}}(ui(e,1))},Dn.constant=tc,Dn.countBy=ma,Dn.create=function(e,t){var n=Bn(e);return null==t?n:si(n,t)},Dn.curry=function e(t,i,r){var s=Zr(t,8,n,n,n,n,n,i=r?n:i);return s.placeholder=e.placeholder,s},Dn.curryRight=function e(t,i,r){var s=Zr(t,a,n,n,n,n,n,i=r?n:i);return s.placeholder=e.placeholder,s},Dn.debounce=Ma,Dn.defaults=Eo,Dn.defaultsDeep=To,Dn.defer=Oa,Dn.delay=Aa,Dn.difference=qs,Dn.differenceBy=Ds,Dn.differenceWith=Bs,Dn.drop=function(e,t,i){var r=null==e?0:e.length;return r?rr(e,(t=i||t===n?1:mo(t))<0?0:t,r):[]},Dn.dropRight=function(e,t,i){var r=null==e?0:e.length;return r?rr(e,0,(t=r-(t=i||t===n?1:mo(t)))<0?0:t):[]},Dn.dropRightWhile=function(e,t){return e&&e.length?fr(e,us(t,3),!0,!0):[]},Dn.dropWhile=function(e,t){return e&&e.length?fr(e,us(t,3),!0):[]},Dn.fill=function(e,t,i,r){var s=null==e?0:e.length;return s?(i&&"number"!=typeof i&&_s(e,t,i)&&(i=0,r=s),function(e,t,i,r){var s=e.length;for((i=mo(i))<0&&(i=-i>s?0:s+i),(r=r===n||r>s?s:mo(r))<0&&(r+=s),r=i>r?0:go(r);i<r;)e[i++]=t;return e}(e,t,i,r)):[]},Dn.filter=function(e,t){return(Wa(e)?Pt:yi)(e,us(t,3))},Dn.flatMap=function(e,t){return vi(Sa(e,t),1)},Dn.flatMapDeep=function(e,t){return vi(Sa(e,t),d)},Dn.flatMapDepth=function(e,t,i){return i=i===n?1:mo(i),vi(Sa(e,t),i)},Dn.flatten=Ks,Dn.flattenDeep=function(e){return(null==e?0:e.length)?vi(e,d):[]},Dn.flattenDepth=function(e,t){return(null==e?0:e.length)?vi(e,t=t===n?1:mo(t)):[]},Dn.flip=function(e){return Zr(e,512)},Dn.flow=nc,Dn.flowRight=ic,Dn.fromPairs=function(e){for(var t=-1,n=null==e?0:e.length,i={};++t<n;){var r=e[t];i[r[0]]=r[1]}return i},Dn.functions=function(e){return null==e?[]:Si(e,Oo(e))},Dn.functionsIn=function(e){return null==e?[]:Si(e,Ao(e))},Dn.groupBy=_a,Dn.initial=function(e){return(null==e?0:e.length)?rr(e,0,-1):[]},Dn.intersection=Vs,Dn.intersectionBy=Js,Dn.intersectionWith=Gs,Dn.invert=Ro,Dn.invertBy=Po,Dn.invokeMap=wa,Dn.iteratee=sc,Dn.keyBy=xa,Dn.keys=Oo,Dn.keysIn=Ao,Dn.map=Sa,Dn.mapKeys=function(e,t){var n={};return t=us(t,3),wi(e,(function(e,i,r){ai(n,t(e,i,r),e)})),n},Dn.mapValues=function(e,t){var n={};return t=us(t,3),wi(e,(function(e,i,r){ai(n,i,t(e,i,r))})),n},Dn.matches=function(e){return Di(ui(e,1))},Dn.matchesProperty=function(e,t){return Bi(e,ui(t,1))},Dn.memoize=ja,Dn.merge=jo,Dn.mergeWith=$o,Dn.method=ac,Dn.methodOf=oc,Dn.mixin=cc,Dn.negate=$a,Dn.nthArg=function(e){return e=mo(e),Xi((function(t){return Wi(t,e)}))},Dn.omit=No,Dn.omitBy=function(e,t){return Lo(e,$a(us(t)))},Dn.once=function(e){return Ca(2,e)},Dn.orderBy=function(e,t,i,r){return null==e?[]:(Wa(t)||(t=null==t?[]:[t]),Wa(i=r?n:i)||(i=null==i?[]:[i]),Ki(e,t,i))},Dn.over=lc,Dn.overArgs=Na,Dn.overEvery=dc,Dn.overSome=hc,Dn.partial=Ua,Dn.partialRight=La,Dn.partition=ka,Dn.pick=Uo,Dn.pickBy=Lo,Dn.property=pc,Dn.propertyOf=function(e){return function(t){return null==e?n:ki(e,t)}},Dn.pull=Xs,Dn.pullAll=Zs,Dn.pullAllBy=function(e,t,n){return e&&e.length&&t&&t.length?Vi(e,t,us(n,2)):e},Dn.pullAllWith=function(e,t,i){return e&&e.length&&t&&t.length?Vi(e,t,n,i):e},Dn.pullAt=Ys,Dn.range=fc,Dn.rangeRight=mc,Dn.rearg=Fa,Dn.reject=function(e,t){return(Wa(e)?Pt:yi)(e,$a(us(t,3)))},Dn.remove=function(e,t){var n=[];if(!e||!e.length)return n;var i=-1,r=[],s=e.length;for(t=us(t,3);++i<s;){var a=e[i];t(a,i,e)&&(n.push(a),r.push(i))}return Ji(e,r),n},Dn.rest=function(e,t){if("function"!=typeof e)throw new Pe(i);return Xi(e,t=t===n?t:mo(t))},Dn.reverse=ea,Dn.sampleSize=function(e,t,i){return t=(i?_s(e,t,i):t===n)?1:mo(t),(Wa(e)?Yn:Yi)(e,t)},Dn.set=function(e,t,n){return null==e?e:er(e,t,n)},Dn.setWith=function(e,t,i,r){return r="function"==typeof r?r:n,null==e?e:er(e,t,i,r)},Dn.shuffle=function(e){return(Wa(e)?ei:ir)(e)},Dn.slice=function(e,t,i){var r=null==e?0:e.length;return r?(i&&"number"!=typeof i&&_s(e,t,i)?(t=0,i=r):(t=null==t?0:mo(t),i=i===n?r:mo(i)),rr(e,t,i)):[]},Dn.sortBy=Ea,Dn.sortedUniq=function(e){return e&&e.length?cr(e):[]},Dn.sortedUniqBy=function(e,t){return e&&e.length?cr(e,us(t,2)):[]},Dn.split=function(e,t,i){return i&&"number"!=typeof i&&_s(e,t,i)&&(t=i=n),(i=i===n?f:i>>>0)?(e=bo(e))&&("string"==typeof t||null!=t&&!so(t))&&!(t=lr(t))&&an(e)?xr(pn(e),0,i):e.split(t,i):[]},Dn.spread=function(e,t){if("function"!=typeof e)throw new Pe(i);return t=null==t?0:bn(mo(t),0),Xi((function(n){var i=n[t],r=xr(n,0,t);return i&&jt(r,i),Et(e,this,r)}))},Dn.tail=function(e){var t=null==e?0:e.length;return t?rr(e,1,t):[]},Dn.take=function(e,t,i){return e&&e.length?rr(e,0,(t=i||t===n?1:mo(t))<0?0:t):[]},Dn.takeRight=function(e,t,i){var r=null==e?0:e.length;return r?rr(e,(t=r-(t=i||t===n?1:mo(t)))<0?0:t,r):[]},Dn.takeRightWhile=function(e,t){return e&&e.length?fr(e,us(t,3),!1,!0):[]},Dn.takeWhile=function(e,t){return e&&e.length?fr(e,us(t,3)):[]},Dn.tap=function(e,t){return t(e),e},Dn.throttle=function(e,t,n){var r=!0,s=!0;if("function"!=typeof e)throw new Pe(i);return eo(n)&&(r="leading"in n?!!n.leading:r,s="trailing"in n?!!n.trailing:s),Ma(e,t,{leading:r,maxWait:t,trailing:s})},Dn.thru=pa,Dn.toArray=po,Dn.toPairs=Fo,Dn.toPairsIn=qo,Dn.toPath=function(e){return Wa(e)?At(e,Us):co(e)?[e]:Pr(Ns(bo(e)))},Dn.toPlainObject=vo,Dn.transform=function(e,t,n){var i=Wa(e),r=i||Ja(e)||uo(e);if(t=us(t,4),null==n){var s=e&&e.constructor;n=r?i?new s:[]:eo(e)&&Xa(s)?Bn(Ve(e)):{}}return(r?It:wi)(e,(function(e,i,r){return t(n,e,i,r)})),n},Dn.unary=function(e){return Ia(e,1)},Dn.union=ta,Dn.unionBy=na,Dn.unionWith=ia,Dn.uniq=function(e){return e&&e.length?dr(e):[]},Dn.uniqBy=function(e,t){return e&&e.length?dr(e,us(t,2)):[]},Dn.uniqWith=function(e,t){return t="function"==typeof t?t:n,e&&e.length?dr(e,n,t):[]},Dn.unset=function(e,t){return null==e||hr(e,t)},Dn.unzip=ra,Dn.unzipWith=sa,Dn.update=function(e,t,n){return null==e?e:pr(e,t,br(n))},Dn.updateWith=function(e,t,i,r){return r="function"==typeof r?r:n,null==e?e:pr(e,t,br(i),r)},Dn.values=Do,Dn.valuesIn=function(e){return null==e?[]:Zt(e,Ao(e))},Dn.without=aa,Dn.words=Zo,Dn.wrap=function(e,t){return Ua(br(t),e)},Dn.xor=oa,Dn.xorBy=ca,Dn.xorWith=ua,Dn.zip=la,Dn.zipObject=function(e,t){return yr(e||[],t||[],ni)},Dn.zipObjectDeep=function(e,t){return yr(e||[],t||[],er)},Dn.zipWith=da,Dn.entries=Fo,Dn.entriesIn=qo,Dn.extend=wo,Dn.extendWith=xo,cc(Dn,Dn),Dn.add=vc,Dn.attempt=Yo,Dn.camelCase=Bo,Dn.capitalize=zo,Dn.ceil=bc,Dn.clamp=function(e,t,i){return i===n&&(i=t,t=n),i!==n&&(i=(i=yo(i))==i?i:0),t!==n&&(t=(t=yo(t))==t?t:0),ci(yo(e),t,i)},Dn.clone=function(e){return ui(e,4)},Dn.cloneDeep=function(e){return ui(e,5)},Dn.cloneDeepWith=function(e,t){return ui(e,5,t="function"==typeof t?t:n)},Dn.cloneWith=function(e,t){return ui(e,4,t="function"==typeof t?t:n)},Dn.conformsTo=function(e,t){return null==t||li(e,t,Oo(t))},Dn.deburr=Wo,Dn.defaultTo=function(e,t){return null==e||e!=e?t:e},Dn.divide=_c,Dn.endsWith=function(e,t,i){e=bo(e),t=lr(t);var r=e.length,s=i=i===n?r:ci(mo(i),0,r);return(i-=t.length)>=0&&e.slice(i,s)==t},Dn.eq=qa,Dn.escape=function(e){return(e=bo(e))&&G.test(e)?e.replace(V,rn):e},Dn.escapeRegExp=function(e){return(e=bo(e))&&ie.test(e)?e.replace(ne,"\\$&"):e},Dn.every=function(e,t,i){var r=Wa(e)?Rt:mi;return i&&_s(e,t,i)&&(t=n),r(e,us(t,3))},Dn.find=ga,Dn.findIndex=zs,Dn.findKey=function(e,t){return Ft(e,us(t,3),wi)},Dn.findLast=ya,Dn.findLastIndex=Ws,Dn.findLastKey=function(e,t){return Ft(e,us(t,3),xi)},Dn.floor=wc,Dn.forEach=va,Dn.forEachRight=ba,Dn.forIn=function(e,t){return null==e?e:bi(e,us(t,3),Ao)},Dn.forInRight=function(e,t){return null==e?e:_i(e,us(t,3),Ao)},Dn.forOwn=function(e,t){return e&&wi(e,us(t,3))},Dn.forOwnRight=function(e,t){return e&&xi(e,us(t,3))},Dn.get=Io,Dn.gt=Da,Dn.gte=Ba,Dn.has=function(e,t){return null!=e&&gs(e,t,Ci)},Dn.hasIn=Co,Dn.head=Hs,Dn.identity=rc,Dn.includes=function(e,t,n,i){e=Ha(e)?e:Do(e),n=n&&!i?mo(n):0;var r=e.length;return n<0&&(n=bn(r+n,0)),oo(e)?n<=r&&e.indexOf(t,n)>-1:!!r&&Dt(e,t,n)>-1},Dn.indexOf=function(e,t,n){var i=null==e?0:e.length;if(!i)return-1;var r=null==n?0:mo(n);return r<0&&(r=bn(i+r,0)),Dt(e,t,r)},Dn.inRange=function(e,t,i){return t=fo(t),i===n?(i=t,t=0):i=fo(i),function(e,t,n){return e>=_n(t,n)&&e<bn(t,n)}(e=yo(e),t,i)},Dn.invoke=Mo,Dn.isArguments=za,Dn.isArray=Wa,Dn.isArrayBuffer=Ka,Dn.isArrayLike=Ha,Dn.isArrayLikeObject=Va,Dn.isBoolean=function(e){return!0===e||!1===e||to(e)&&Ti(e)==v},Dn.isBuffer=Ja,Dn.isDate=Ga,Dn.isElement=function(e){return to(e)&&1===e.nodeType&&!ro(e)},Dn.isEmpty=function(e){if(null==e)return!0;if(Ha(e)&&(Wa(e)||"string"==typeof e||"function"==typeof e.splice||Ja(e)||uo(e)||za(e)))return!e.length;var t=ms(e);if(t==S||t==C)return!e.size;if(ks(e))return!Ui(e).length;for(var n in e)if(Ne.call(e,n))return!1;return!0},Dn.isEqual=function(e,t){return Ai(e,t)},Dn.isEqualWith=function(e,t,i){var r=(i="function"==typeof i?i:n)?i(e,t):n;return r===n?Ai(e,t,n,i):!!r},Dn.isError=Qa,Dn.isFinite=function(e){return"number"==typeof e&&Ht(e)},Dn.isFunction=Xa,Dn.isInteger=Za,Dn.isLength=Ya,Dn.isMap=no,Dn.isMatch=function(e,t){return e===t||ji(e,t,ds(t))},Dn.isMatchWith=function(e,t,i){return i="function"==typeof i?i:n,ji(e,t,ds(t),i)},Dn.isNaN=function(e){return io(e)&&e!=+e},Dn.isNative=function(e){if(Ss(e))throw new ke("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return $i(e)},Dn.isNil=function(e){return null==e},Dn.isNull=function(e){return null===e},Dn.isNumber=io,Dn.isObject=eo,Dn.isObjectLike=to,Dn.isPlainObject=ro,Dn.isRegExp=so,Dn.isSafeInteger=function(e){return Za(e)&&e>=-9007199254740991&&e<=h},Dn.isSet=ao,Dn.isString=oo,Dn.isSymbol=co,Dn.isTypedArray=uo,Dn.isUndefined=function(e){return e===n},Dn.isWeakMap=function(e){return to(e)&&ms(e)==M},Dn.isWeakSet=function(e){return to(e)&&"[object WeakSet]"==Ti(e)},Dn.join=function(e,t){return null==e?"":yn.call(e,t)},Dn.kebabCase=Ko,Dn.last=Qs,Dn.lastIndexOf=function(e,t,i){var r=null==e?0:e.length;if(!r)return-1;var s=r;return i!==n&&(s=(s=mo(i))<0?bn(r+s,0):_n(s,r-1)),t==t?function(e,t,n){for(var i=n+1;i--;)if(e[i]===t)return i;return i}(e,t,s):qt(e,zt,s,!0)},Dn.lowerCase=Ho,Dn.lowerFirst=Vo,Dn.lt=lo,Dn.lte=ho,Dn.max=function(e){return e&&e.length?gi(e,rc,Ii):n},Dn.maxBy=function(e,t){return e&&e.length?gi(e,us(t,2),Ii):n},Dn.mean=function(e){return Wt(e,rc)},Dn.meanBy=function(e,t){return Wt(e,us(t,2))},Dn.min=function(e){return e&&e.length?gi(e,rc,Fi):n},Dn.minBy=function(e,t){return e&&e.length?gi(e,us(t,2),Fi):n},Dn.stubArray=gc,Dn.stubFalse=yc,Dn.stubObject=function(){return{}},Dn.stubString=function(){return""},Dn.stubTrue=function(){return!0},Dn.multiply=Sc,Dn.nth=function(e,t){return e&&e.length?Wi(e,mo(t)):n},Dn.noConflict=function(){return pt._===this&&(pt._=De),this},Dn.noop=uc,Dn.now=Ta,Dn.pad=function(e,t,n){e=bo(e);var i=(t=mo(t))?hn(e):0;if(!t||i>=t)return e;var r=(t-i)/2;return Kr(yt(r),n)+e+Kr(mt(r),n)},Dn.padEnd=function(e,t,n){e=bo(e);var i=(t=mo(t))?hn(e):0;return t&&i<t?e+Kr(t-i,n):e},Dn.padStart=function(e,t,n){e=bo(e);var i=(t=mo(t))?hn(e):0;return t&&i<t?Kr(t-i,n)+e:e},Dn.parseInt=function(e,t,n){return n||null==t?t=0:t&&(t=+t),xn(bo(e).replace(re,""),t||0)},Dn.random=function(e,t,i){if(i&&"boolean"!=typeof i&&_s(e,t,i)&&(t=i=n),i===n&&("boolean"==typeof t?(i=t,t=n):"boolean"==typeof e&&(i=e,e=n)),e===n&&t===n?(e=0,t=1):(e=fo(e),t===n?(t=e,e=0):t=fo(t)),e>t){var r=e;e=t,t=r}if(i||e%1||t%1){var s=Sn();return _n(e+s*(t-e+ut("1e-"+((s+"").length-1))),t)}return Gi(e,t)},Dn.reduce=function(e,t,n){var i=Wa(e)?$t:Vt,r=arguments.length<3;return i(e,us(t,4),n,r,pi)},Dn.reduceRight=function(e,t,n){var i=Wa(e)?Nt:Vt,r=arguments.length<3;return i(e,us(t,4),n,r,fi)},Dn.repeat=function(e,t,i){return t=(i?_s(e,t,i):t===n)?1:mo(t),Qi(bo(e),t)},Dn.replace=function(){var e=arguments,t=bo(e[0]);return e.length<3?t:t.replace(e[1],e[2])},Dn.result=function(e,t,i){var r=-1,s=(t=_r(t,e)).length;for(s||(s=1,e=n);++r<s;){var a=null==e?n:e[Us(t[r])];a===n&&(r=s,a=i),e=Xa(a)?a.call(e):a}return e},Dn.round=kc,Dn.runInContext=e,Dn.sample=function(e){return(Wa(e)?Zn:Zi)(e)},Dn.size=function(e){if(null==e)return 0;if(Ha(e))return oo(e)?hn(e):e.length;var t=ms(e);return t==S||t==C?e.size:Ui(e).length},Dn.snakeCase=Jo,Dn.some=function(e,t,i){var r=Wa(e)?Ut:sr;return i&&_s(e,t,i)&&(t=n),r(e,us(t,3))},Dn.sortedIndex=function(e,t){return ar(e,t)},Dn.sortedIndexBy=function(e,t,n){return or(e,t,us(n,2))},Dn.sortedIndexOf=function(e,t){var n=null==e?0:e.length;if(n){var i=ar(e,t);if(i<n&&qa(e[i],t))return i}return-1},Dn.sortedLastIndex=function(e,t){return ar(e,t,!0)},Dn.sortedLastIndexBy=function(e,t,n){return or(e,t,us(n,2),!0)},Dn.sortedLastIndexOf=function(e,t){if(null==e?0:e.length){var n=ar(e,t,!0)-1;if(qa(e[n],t))return n}return-1},Dn.startCase=Go,Dn.startsWith=function(e,t,n){return e=bo(e),n=null==n?0:ci(mo(n),0,e.length),t=lr(t),e.slice(n,n+t.length)==t},Dn.subtract=Ec,Dn.sum=function(e){return e&&e.length?Jt(e,rc):0},Dn.sumBy=function(e,t){return e&&e.length?Jt(e,us(t,2)):0},Dn.template=function(e,t,i){var r=Dn.templateSettings;i&&_s(e,t,i)&&(t=n),e=bo(e),t=xo({},t,r,Yr);var s,a,o=xo({},t.imports,r.imports,Yr),c=Oo(o),u=Zt(o,c),l=0,d=t.interpolate||_e,h="__p += '",p=Ce((t.escape||_e).source+"|"+d.source+"|"+(d===Z?he:_e).source+"|"+(t.evaluate||_e).source+"|$","g"),f="//# sourceURL="+(Ne.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++st+"]")+"\n";e.replace(p,(function(t,n,i,r,o,c){return i||(i=r),h+=e.slice(l,c).replace(we,sn),n&&(s=!0,h+="' +\n__e("+n+") +\n'"),o&&(a=!0,h+="';\n"+o+";\n__p += '"),i&&(h+="' +\n((__t = ("+i+")) == null ? '' : __t) +\n'"),l=c+t.length,t})),h+="';\n";var m=Ne.call(t,"variable")&&t.variable;if(m){if(le.test(m))throw new ke("Invalid `variable` option passed into `_.template`")}else h="with (obj) {\n"+h+"\n}\n";h=(a?h.replace(z,""):h).replace(W,"$1").replace(K,"$1;"),h="function("+(m||"obj")+") {\n"+(m?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(s?", __e = _.escape":"")+(a?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+h+"return __p\n}";var g=Yo((function(){return Ee(c,f+"return "+h).apply(n,u)}));if(g.source=h,Qa(g))throw g;return g},Dn.times=function(e,t){if((e=mo(e))<1||e>h)return[];var n=f,i=_n(e,f);t=us(t),e-=f;for(var r=Gt(i,t);++n<e;)t(n);return r},Dn.toFinite=fo,Dn.toInteger=mo,Dn.toLength=go,Dn.toLower=function(e){return bo(e).toLowerCase()},Dn.toNumber=yo,Dn.toSafeInteger=function(e){return e?ci(mo(e),-9007199254740991,h):0===e?e:0},Dn.toString=bo,Dn.toUpper=function(e){return bo(e).toUpperCase()},Dn.trim=function(e,t,i){if((e=bo(e))&&(i||t===n))return Qt(e);if(!e||!(t=lr(t)))return e;var r=pn(e),s=pn(t);return xr(r,en(r,s),tn(r,s)+1).join("")},Dn.trimEnd=function(e,t,i){if((e=bo(e))&&(i||t===n))return e.slice(0,fn(e)+1);if(!e||!(t=lr(t)))return e;var r=pn(e);return xr(r,0,tn(r,pn(t))+1).join("")},Dn.trimStart=function(e,t,i){if((e=bo(e))&&(i||t===n))return e.replace(re,"");if(!e||!(t=lr(t)))return e;var r=pn(e);return xr(r,en(r,pn(t))).join("")},Dn.truncate=function(e,t){var i=30,r="...";if(eo(t)){var s="separator"in t?t.separator:s;i="length"in t?mo(t.length):i,r="omission"in t?lr(t.omission):r}var a=(e=bo(e)).length;if(an(e)){var o=pn(e);a=o.length}if(i>=a)return e;var c=i-hn(r);if(c<1)return r;var u=o?xr(o,0,c).join(""):e.slice(0,c);if(s===n)return u+r;if(o&&(c+=u.length-c),so(s)){if(e.slice(c).search(s)){var l,d=u;for(s.global||(s=Ce(s.source,bo(pe.exec(s))+"g")),s.lastIndex=0;l=s.exec(d);)var h=l.index;u=u.slice(0,h===n?c:h)}}else if(e.indexOf(lr(s),c)!=c){var p=u.lastIndexOf(s);p>-1&&(u=u.slice(0,p))}return u+r},Dn.unescape=function(e){return(e=bo(e))&&J.test(e)?e.replace(H,mn):e},Dn.uniqueId=function(e){var t=++Ue;return bo(e)+t},Dn.upperCase=Qo,Dn.upperFirst=Xo,Dn.each=va,Dn.eachRight=ba,Dn.first=Hs,cc(Dn,(xc={},wi(Dn,(function(e,t){Ne.call(Dn.prototype,t)||(xc[t]=e)})),xc),{chain:!1}),Dn.VERSION="4.17.21",It(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(e){Dn[e].placeholder=Dn})),It(["drop","take"],(function(e,t){Kn.prototype[e]=function(i){i=i===n?1:bn(mo(i),0);var r=this.__filtered__&&!t?new Kn(this):this.clone();return r.__filtered__?r.__takeCount__=_n(i,r.__takeCount__):r.__views__.push({size:_n(i,f),type:e+(r.__dir__<0?"Right":"")}),r},Kn.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),It(["filter","map","takeWhile"],(function(e,t){var n=t+1,i=1==n||3==n;Kn.prototype[e]=function(e){var t=this.clone();return t.__iteratees__.push({iteratee:us(e,3),type:n}),t.__filtered__=t.__filtered__||i,t}})),It(["head","last"],(function(e,t){var n="take"+(t?"Right":"");Kn.prototype[e]=function(){return this[n](1).value()[0]}})),It(["initial","tail"],(function(e,t){var n="drop"+(t?"":"Right");Kn.prototype[e]=function(){return this.__filtered__?new Kn(this):this[n](1)}})),Kn.prototype.compact=function(){return this.filter(rc)},Kn.prototype.find=function(e){return this.filter(e).head()},Kn.prototype.findLast=function(e){return this.reverse().find(e)},Kn.prototype.invokeMap=Xi((function(e,t){return"function"==typeof e?new Kn(this):this.map((function(n){return Mi(n,e,t)}))})),Kn.prototype.reject=function(e){return this.filter($a(us(e)))},Kn.prototype.slice=function(e,t){e=mo(e);var i=this;return i.__filtered__&&(e>0||t<0)?new Kn(i):(e<0?i=i.takeRight(-e):e&&(i=i.drop(e)),t!==n&&(i=(t=mo(t))<0?i.dropRight(-t):i.take(t-e)),i)},Kn.prototype.takeRightWhile=function(e){return this.reverse().takeWhile(e).reverse()},Kn.prototype.toArray=function(){return this.take(f)},wi(Kn.prototype,(function(e,t){var i=/^(?:filter|find|map|reject)|While$/.test(t),r=/^(?:head|last)$/.test(t),s=Dn[r?"take"+("last"==t?"Right":""):t],a=r||/^find/.test(t);s&&(Dn.prototype[t]=function(){var t=this.__wrapped__,o=r?[1]:arguments,c=t instanceof Kn,u=o[0],l=c||Wa(t),d=function(e){var t=s.apply(Dn,jt([e],o));return r&&h?t[0]:t};l&&i&&"function"==typeof u&&1!=u.length&&(c=l=!1);var h=this.__chain__,p=!!this.__actions__.length,f=a&&!h,m=c&&!p;if(!a&&l){t=m?t:new Kn(this);var g=e.apply(t,o);return g.__actions__.push({func:pa,args:[d],thisArg:n}),new Wn(g,h)}return f&&m?e.apply(this,o):(g=this.thru(d),f?r?g.value()[0]:g.value():g)})})),It(["pop","push","shift","sort","splice","unshift"],(function(e){var t=Me[e],n=/^(?:push|sort|unshift)$/.test(e)?"tap":"thru",i=/^(?:pop|shift)$/.test(e);Dn.prototype[e]=function(){var e=arguments;if(i&&!this.__chain__){var r=this.value();return t.apply(Wa(r)?r:[],e)}return this[n]((function(n){return t.apply(Wa(n)?n:[],e)}))}})),wi(Kn.prototype,(function(e,t){var n=Dn[t];if(n){var i=n.name+"";Ne.call(On,i)||(On[i]=[]),On[i].push({name:t,func:n})}})),On[Dr(n,2).name]=[{name:"wrapper",func:n}],Kn.prototype.clone=function(){var e=new Kn(this.__wrapped__);return e.__actions__=Pr(this.__actions__),e.__dir__=this.__dir__,e.__filtered__=this.__filtered__,e.__iteratees__=Pr(this.__iteratees__),e.__takeCount__=this.__takeCount__,e.__views__=Pr(this.__views__),e},Kn.prototype.reverse=function(){if(this.__filtered__){var e=new Kn(this);e.__dir__=-1,e.__filtered__=!0}else(e=this.clone()).__dir__*=-1;return e},Kn.prototype.value=function(){var e=this.__wrapped__.value(),t=this.__dir__,n=Wa(e),i=t<0,r=n?e.length:0,s=function(e,t,n){var i=-1,r=n.length;for(;++i<r;){var s=n[i],a=s.size;switch(s.type){case"drop":e+=a;break;case"dropRight":t-=a;break;case"take":t=_n(t,e+a);break;case"takeRight":e=bn(e,t-a)}}return{start:e,end:t}}(0,r,this.__views__),a=s.start,o=s.end,c=o-a,u=i?o:a-1,l=this.__iteratees__,d=l.length,h=0,p=_n(c,this.__takeCount__);if(!n||!i&&r==c&&p==c)return mr(e,this.__actions__);var f=[];e:for(;c--&&h<p;){for(var m=-1,g=e[u+=t];++m<d;){var y=l[m],v=y.iteratee,b=y.type,_=v(g);if(2==b)g=_;else if(!_){if(1==b)continue e;break e}}f[h++]=g}return f},Dn.prototype.at=fa,Dn.prototype.chain=function(){return ha(this)},Dn.prototype.commit=function(){return new Wn(this.value(),this.__chain__)},Dn.prototype.next=function(){this.__values__===n&&(this.__values__=po(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?n:this.__values__[this.__index__++]}},Dn.prototype.plant=function(e){for(var t,i=this;i instanceof zn;){var r=Fs(i);r.__index__=0,r.__values__=n,t?s.__wrapped__=r:t=r;var s=r;i=i.__wrapped__}return s.__wrapped__=e,t},Dn.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof Kn){var t=e;return this.__actions__.length&&(t=new Kn(this)),(t=t.reverse()).__actions__.push({func:pa,args:[ea],thisArg:n}),new Wn(t,this.__chain__)}return this.thru(ea)},Dn.prototype.toJSON=Dn.prototype.valueOf=Dn.prototype.value=function(){return mr(this.__wrapped__,this.__actions__)},Dn.prototype.first=Dn.prototype.head,et&&(Dn.prototype[et]=function(){return this}),Dn}();mt?((mt.exports=gn)._=gn,ft._=gn):pt._=gn}).call(On)}(li,li.exports);class di extends Zn{descriptor;updateMergingQueue;cache;context;contextEventId;constructor(e,t,n){super(e,n);this.updateMergingQueue=new ei(((e,t)=>"number"==typeof t.ttl?{ttl:t.ttl}:e)),this.cache=new ui,this.descriptor=t,this.descriptor.date_updated=new Date(this.descriptor.date_updated)}get uri(){return this.descriptor.url}get revision(){return this.descriptor.revision}get lastEventId(){return this.descriptor.last_event_id}get links(){return this.descriptor.links}get dateExpires(){return this.descriptor.date_expires}static get type(){return"list"}get type(){return"list"}get indexName(){}get queryString(){}get sid(){return this.descriptor.sid}get uniqueName(){return this.descriptor.unique_name||null}get dateUpdated(){return this.descriptor.date_updated}async _addOrUpdateItemOnServer(e,t,n,i){const r={data:t};void 0!==i&&(r.ttl=i);const s=await this.services.network.post(e,r,n);return s.body.data=t,s.body.date_updated=new Date(s.body.date_updated),s.body}async push(e,t){let n=(t||{}).ttl,i=await this._addOrUpdateItemOnServer(this.links.items,e,void 0,n),r=Number(i.index);return this._handleItemMutated(r,i.url,i.last_event_id,i.revision,e,i.date_updated,i.date_expires,!0,!1),this.cache.getValue(r)}async set(e,t,n){const i=n||{};return this.updateMergingQueue.squashAndAdd(e,i,(n=>this._updateItemUnconditionally(e,t,n.ttl)))}async _updateItemUnconditionally(e,t,n){let i=await this.get(e);const r=await this._addOrUpdateItemOnServer(i.url,t,void 0,n);return this._handleItemMutated(e,r.url,r.last_event_id,r.revision,r.data,r.date_updated,r.date_expires,!1,!1),this.cache.getValue(e)}async _updateItemWithIfMatch(e,t,n){const i=await this.get(e),r=t(xn(i.data));if(!r)return i;{const s=i.revision;try{const t=await this._addOrUpdateItemOnServer(i.url,r,s,n);return this._handleItemMutated(e,t.url,t.last_event_id,t.revision,t.data,t.date_updated,t.date_expires,!1,!1),this.cache.getValue(e)}catch(i){if(412===i.status)return await this._getItemFromServer(e),this._updateItemWithIfMatch(e,t,n);throw i}}}async mutate(e,t,n){const i=n||{};return this.updateMergingQueue.add(e,i,(n=>this._updateItemWithIfMatch(e,t,n.ttl)))}async update(e,t,n){return this.mutate(e,(e=>Object.assign(e,t)),n)}async remove(e){const t=await this.get(e),n=xn(t.data),i=await this.services.network.delete(t.url);this._handleItemRemoved(e,i.body.last_event_id,n,new Date(i.body.date_updated),!1)}async get(e){let t=this.cache.get(e);return t?t.value:this._getItemFromServer(e)}async _getItemFromServer(e){let t=await this._queryItemsFromServer({index:e});if(t.items.length<1)throw new SyncError(`No item with index ${e} found`,404,54151);return t.items[0]}async queryItems(e){if("number"==typeof e.index){const t=this.cache.get(e.index);return t?this.makePaginator(t.isValid?[t.value]:[],e,!1,!1):this._querySingleItemFromServer(e.index)}const t=!!e.nextPageItemId||!!e.prevPageItemId,n={...e};t&&(e.from=e.nextPageItemId??e.prevPageItemId??e.from);const i=!!e.prevPageItemId;let r="desc"===e.order?i?this.cache.getIterator(e.prevPageItemId??e.from??null):this.cache.getReverseIterator(e.nextPageItemId??e.from??null):i?this.cache.getReverseIterator(e.prevPageItemId??e.from??null):this.cache.getIterator(e.nextPageItemId??e.from??null),s=[];const a=t?e.limit+1:e.limit;for(let n of r)if((!t||n.value.index!=e.from)&&(s.push(n.value),s.length>=e.limit))return i&&li.exports.reverse(s),this.makePaginator(s,e,this._prevPageAllowed(s,e.order),this._nextPageAllowed(s,e.order));s.length>0&&(e.from=li.exports.last(s).index);const o=Math.max(a-s.length,10);i&&(e.order="desc"===e.order?"asc":"desc");if(e.from!==("desc"===n.order?i?this.cache.collectionEnd:this.cache.collectionBegin:i?this.cache.collectionBegin:this.cache.collectionEnd)){const n=await this._queryItemsFromServer({...e,limit:o}),r=n.items;this.cache.populate(r,!n.hasPrevPage,!n.hasNextPage);for(let n of r)if((!(s.length>0||t)||n.index!=e.from)&&(i?s.unshift(n):s.push(n),s.length>=e.limit))break}else i&&li.exports.reverse(s);return this.makePaginator(s,n,this._prevPageAllowed(s,n.order),this._nextPageAllowed(s,n.order))}_prevPageAllowed(e,t){return e.length>0&&li.exports.head(e).index!==("desc"===t?this.cache.collectionEnd:this.cache.collectionBegin)}_nextPageAllowed(e,t){return e.length>0&&li.exports.last(e).index!==("desc"===t?this.cache.collectionBegin:this.cache.collectionEnd)}makePaginator(e,t,n,i){t.nextPageItemId=t.prevPageItemId=null;const r=n&&this._prevPageAllowed(e,t.order),s=i&&this._nextPageAllowed(e,t.order);return new Paginator(e,(e=>this.queryItems({...t,...e})),r?li.exports.head(e).index:null,s?li.exports.last(e).index:null)}async _querySingleItemFromServer(e){const t=await this._queryItemsFromServer({index:e});return 0===t.items.length&&this.cache.delete(e,null),t}async _queryItemsFromServer(e){const t=new _n(this.links.items).queryParam("HideExpired",!0).queryParam("Index",e.index).queryParam("PageToken",e.pageToken).queryParam("From",e.from).queryParam("PageSize",e.limit).queryParam("Order",e.order).build();let n=await this.services.network.get(t),i=(n.body?.items??[]).map((e=>(e.date_updated=new Date(e.date_updated),this._handleItemMutated(e.index,e.url,e.last_event_id,e.revision,e.data,e.date_updated,e.date_expires,!1,!0),this.cache.getValue(e.index))));const r=n.body.meta;return this.makePaginator(i,e,!!r.previous_token,!!r.next_token)}async getItems(e){return Sn((e=e||{}).pageSize),e.limit=e.pageSize||e.limit||50,e.order=e.order||"asc",this.queryItems(e)}async getContext(){if(!this.context){let e=await this.services.network.get(this.links.context);this._updateContextIfRequired(e.body.data,e.body.last_event_id)}return this.context}async setTtl(e){try{const t={ttl:e},n=await this.services.network.post(this.uri,t);this.descriptor.date_expires=n.body.date_expires}catch(e){throw 404===e.status&&this.onRemoved(!1),e}}async setItemTtl(e,t){let n=await this.get(e);const i={ttl:t},r=await this.services.network.post(n.url,i);n.updateDateExpires(r.body.date_expires)}async removeList(){await this.services.network.delete(this.uri),this.onRemoved(!0)}onRemoved(e){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e})}shouldIgnoreEvent(e,t){return this.cache.isKnown(e,t)}_update(e,t){const n=Number(e.item_index);switch(e.date_created=new Date(e.date_created),e.type){case"list_item_added":case"list_item_updated":this._handleItemMutated(n,e.item_url,e.id,e.item_revision,e.item_data,e.date_created,e.date_expires,"list_item_added"===e.type,!0);break;case"list_item_removed":this._handleItemRemoved(n,e.id,e.item_data,e.date_created,!0);break;case"list_context_updated":this._handleContextUpdate(e.context_data,e.id,e.date_created);break;case"list_removed":this.onRemoved(!1)}t&&this._advanceLastEventId(e.id,e.list_revision)}_advanceLastEventId(e,t){this.lastEventId<e&&(this.descriptor.last_event_id=e,t&&(this.descriptor.revision=t))}_updateRootDateUpdated(e){(!this.descriptor.date_updated||e.getTime()>this.descriptor.date_updated.getTime())&&(this.descriptor.date_updated=e,this.services.storage.update(this.type,this.sid,this.uniqueName,{date_updated:e}))}_handleItemMutated(e,t,n,i,r,s,a,o,c){if(this.shouldIgnoreEvent(e,n))return void Cn(`Item ${e} update skipped, current: ${this.lastEventId}, remote: ${n}`);this._updateRootDateUpdated(s);const u=this.cache.getValue(e);if(!u){const u=new ri({index:e,url:t,lastEventId:n,revision:i,data:r,dateUpdated:s,dateExpires:a});return this.cache.store(e,u,n),void this.emitItemMutationEvent(u,c,o)}const l=xn(u.data);u.update(n,i,r,s),this.cache.store(e,u,n),void 0!==a&&u.updateDateExpires(a),this.emitItemMutationEvent(u,c,!1,l)}emitItemMutationEvent(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;const r=n?"itemAdded":"itemUpdated",s={item:e,isLocal:!t};n||(s.previousItemData=i),this.broadcastEventToListeners(r,s)}_handleItemRemoved(e,t,n,i,r){this._updateRootDateUpdated(i),this.cache.delete(e,t),this.broadcastEventToListeners("itemRemoved",{index:e,isLocal:!r,previousItemData:n})}_handleContextUpdate(e,t,n){this._updateRootDateUpdated(n),this._updateContextIfRequired(e,t)&&this.broadcastEventToListeners("contextUpdated",{context:e,isLocal:!1})}_updateContextIfRequired(e,t){return!this.contextEventId||t>this.contextEventId?(this.context=e,this.contextEventId=t,!0):(Cn("Context update skipped, current:",this.lastEventId,", remote:",t),!1)}}class hi extends ti{syncListImpl;get uri(){return this.syncListImpl.uri}get revision(){return this.syncListImpl.revision}get lastEventId(){return this.syncListImpl.lastEventId}get links(){return this.syncListImpl.links}get dateExpires(){return this.syncListImpl.dateExpires}static get type(){return di.type}get type(){return di.type}get sid(){return this.syncListImpl.sid}get uniqueName(){return this.syncListImpl.uniqueName}get dateUpdated(){return this.syncListImpl.dateUpdated}constructor(e){super(),this.syncListImpl=e,this.syncListImpl.attach(this)}static itemAdded="itemAdded";static itemUpdated="itemUpdated";static itemRemoved="itemRemoved";static removed="removed";async push(e,t){return this.ensureNotClosed(),this.syncListImpl.push(e,t)}async set(e,t,n){return this.ensureNotClosed(),this.syncListImpl.set(e,t,n)}async mutate(e,t,n){return this.ensureNotClosed(),this.syncListImpl.mutate(e,t,n)}async update(e,t,n){return this.ensureNotClosed(),this.syncListImpl.update(e,t,n)}async remove(e){return this.ensureNotClosed(),this.syncListImpl.remove(e)}async get(e){return this.ensureNotClosed(),this.syncListImpl.get(e)}async getContext(){return this.ensureNotClosed(),this.syncListImpl.getContext()}async getItems(e){return this.ensureNotClosed(),this.syncListImpl.getItems(e)}async setTtl(e){return this.ensureNotClosed(),this.syncListImpl.setTtl(e)}async setItemTtl(e,t){return this.ensureNotClosed(),this.syncListImpl.setItemTtl(e,t)}async removeList(){return this.ensureNotClosed(),this.syncListImpl.removeList()}close(){super.close(),this.syncListImpl.detach(this.listenerUuid)}}vn([sn.validateTypesAsync(sn.pureObject,["undefined",sn.objectSchema("item metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Object,Object]),bn("design:returntype",Promise)],hi.prototype,"push",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger,sn.pureObject,["undefined",sn.objectSchema("item metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Number,Object,Object]),bn("design:returntype",Promise)],hi.prototype,"set",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger,"function",["undefined",sn.objectSchema("item metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Number,Function,Object]),bn("design:returntype",Promise)],hi.prototype,"mutate",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger,sn.pureObject,["undefined",sn.objectSchema("item metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Number,Object,Object]),bn("design:returntype",Promise)],hi.prototype,"update",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number]),bn("design:returntype",Promise)],hi.prototype,"remove",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number]),bn("design:returntype",Promise)],hi.prototype,"get",null),vn([sn.validateTypesAsync(["undefined",sn.objectSchema("query options",{from:[sn.nonNegativeInteger,"undefined"],pageSize:[sn.custom((e=>[kn(e),"a positive integer"])),"undefined"],order:[sn.custom((e=>["asc"===e||"desc"===e,"either 'asc' or 'desc'"])),"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],hi.prototype,"getItems",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number]),bn("design:returntype",Promise)],hi.prototype,"setTtl",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger,sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number,Number]),bn("design:returntype",Promise)],hi.prototype,"setItemTtl",null);class pi{descriptor;constructor(e){this.descriptor=e}get uri(){return this.descriptor.url}get revision(){return this.descriptor.revision}get lastEventId(){return this.descriptor.last_event_id}get dateExpires(){return this.descriptor.date_expires}get key(){return this.descriptor.key}get data(){return this.descriptor.data}get dateUpdated(){return this.descriptor.date_updated}get cacheKey(){return this.key}update(e,t,n,i){return this.descriptor.last_event_id=e,this.descriptor.revision=t,this.descriptor.data=n,this.descriptor.date_updated=i,this}updateDateExpires(e){this.descriptor.date_expires=e}}class fi extends Zn{descriptor;updateMergingQueue;cache;constructor(e,t,n){super(e,n);this.updateMergingQueue=new ei(((e,t)=>"number"==typeof t.ttl?{ttl:t.ttl}:e)),this.cache=new ui,this.descriptor=t,this.descriptor.date_updated=new Date(this.descriptor.date_updated),t.items&&t.items.forEach((e=>{e.date_updated=new Date(e.date_updated),this.cache.store(e.key,new pi(e),e.last_event_id)}))}get uri(){return this.descriptor.url}get links(){return this.descriptor.links}get revision(){return this.descriptor.revision}get lastEventId(){return this.descriptor.last_event_id}get dateExpires(){return this.descriptor.date_expires}static get type(){return"map"}get type(){return"map"}get indexName(){}get queryString(){}get sid(){return this.descriptor.sid}get uniqueName(){return this.descriptor.unique_name||null}get dateUpdated(){return this.descriptor.date_updated}async set(e,t,n){const i=n||{};return this.updateMergingQueue.squashAndAdd(e,i,(n=>this._putItemUnconditionally(e,t,n.ttl)))}async get(e){if(null==e)throw new SyncError("SyncMapItem key may not be empty",400,54209);return this.cache.has(e)?this.cache.getValue(e):this._getItemFromServer(e)}async _getItemFromServer(e){let t=await this._queryItemsFromServer({key:e});if(t.items.length<1)throw new SyncError("The specified Map Item does not exist",404,54201);return t.items[0]}async mutate(e,t,n){const i=n||{};return this.updateMergingQueue.add(e,i,(n=>this._putItemWithIfMatch(e,t,n.ttl)))}async update(e,t,n){return this.mutate(e,(e=>Object.assign(e,t)),n)}async _putItemUnconditionally(e,t,n){const i=await this._putItemToServer(e,t,void 0,n),r=i.item;return this._handleItemMutated(r.key,r.url,r.last_event_id,r.revision,r.data,r.date_updated,r.date_expires,i.added,!1),this.cache.getValue(r.key)}async _putItemWithIfMatch(e,t,n){const i=await this.get(e).catch((t=>{if(404===t.status)return new pi({key:e,data:{},last_event_id:-1,revision:"-1",url:null,date_updated:null,date_expires:null});throw t}));let r=t(xn(i.data));if(!r)return i;{let s=i.revision;try{const t=await this._putItemToServer(e,r,s,n),i=t.item;return this._handleItemMutated(i.key,i.url,i.last_event_id,i.revision,i.data,i.date_updated,i.date_expires,t.added,!1),this.cache.getValue(i.key)}catch(i){if(412===i.status)return await this._getItemFromServer(e),this._putItemWithIfMatch(e,t,n);throw i}}}async _putItemToServer(e,t,n,i){const r=new _n(this.links.items).pathSegment(e).build(),s={data:t};void 0!==i&&(s.ttl=i);try{const e=await this.services.network.put(r,s,n),i=e.body;i.data=t,i.date_updated=new Date(i.date_updated);return{added:201===e.status.code,item:i}}catch(e){throw 404===e.status&&this.onRemoved(!1),e}}async remove(e){const t=await this.get(e),n=xn(t.data),i=await this.services.network.delete(t.uri);this._handleItemRemoved(e,i.body.last_event_id,n,new Date(i.body.date_updated),!1)}async queryItems(e){if("string"==typeof e.key){const t=this.cache.get(e.key);return t?this.makePaginator(t.isValid?[t.value]:[],e,!1,!1):this._querySingleItemFromServer(e.key)}const t=!!e.nextPageItemId||!!e.prevPageItemId,n={...e};t&&(e.from=e.nextPageItemId??e.prevPageItemId??e.from);const i=!!e.prevPageItemId;let r="desc"===e.order?i?this.cache.getIterator(e.prevPageItemId??e.from??null):this.cache.getReverseIterator(e.nextPageItemId??e.from??null):i?this.cache.getReverseIterator(e.prevPageItemId??e.from??null):this.cache.getIterator(e.nextPageItemId??e.from??null),s=[];const a=t?e.limit+1:e.limit;for(let n of r)if((!t||n.value.key!=e.from)&&(s.push(n.value),s.length>=e.limit))return i&&li.exports.reverse(s),this.makePaginator(s,e,this._prevPageAllowed(s,e.order),this._nextPageAllowed(s,e.order));s.length>0&&(e.from=li.exports.last(s).key);const o=Math.max(a-s.length,10);i&&(e.order="desc"===e.order?"asc":"desc");if(e.from!==("desc"===n.order?i?this.cache.collectionEnd:this.cache.collectionBegin:i?this.cache.collectionBegin:this.cache.collectionEnd)){const n=await this._queryItemsFromServer({...e,limit:o}),r=n.items;this.cache.populate(r,!n.hasPrevPage,!n.hasNextPage);for(let n of r)if((!(s.length>0||t)||n.key!=e.from)&&(i?s.unshift(n):s.push(n),s.length>=e.limit))break}else i&&li.exports.reverse(s);return this.makePaginator(s,n,this._prevPageAllowed(s,n.order),this._nextPageAllowed(s,n.order))}_prevPageAllowed(e,t){return e.length>0&&li.exports.head(e).key!==("desc"===t?this.cache.collectionEnd:this.cache.collectionBegin)}_nextPageAllowed(e,t){return e.length>0&&li.exports.last(e).key!==("desc"===t?this.cache.collectionBegin:this.cache.collectionEnd)}makePaginator(e,t,n,i){t.nextPageItemId=t.prevPageItemId=null;const r=n&&this._prevPageAllowed(e,t.order),s=i&&this._nextPageAllowed(e,t.order);return new Paginator(e,(e=>this.queryItems({...t,...e})),r?li.exports.head(e).key:null,s?li.exports.last(e).key:null)}async _querySingleItemFromServer(e){const t=await this._queryItemsFromServer({key:e});return 0===t.items.length&&this.cache.delete(e,null),t}async _queryItemsFromServer(e){const t=new _n(this.links.items).queryParam("HideExpired",!0).queryParam("Key",e.key).queryParam("PageToken",e.pageToken).queryParam("From",e.from).queryParam("PageSize",e.limit).queryParam("Order",e.order).build();let n=await this.services.network.get(t),i=(n.body?.items??[]).map((e=>(e.date_updated=new Date(e.date_updated),this._handleItemMutated(e.key,e.url,e.last_event_id,e.revision,e.data,e.date_updated,e.date_expires,!1,!0),this.cache.getValue(e.key))));const r=n.body.meta;return this.makePaginator(i,e,!!r.previous_token,!!r.next_token)}async getItems(e){return Sn((e=e||{}).pageSize),e.limit=e.pageSize||e.limit||50,e.order=e.order||"asc",this.queryItems(e)}shouldIgnoreEvent(e,t){return this.cache.isKnown(e,t)}_update(e,t){switch(e.date_created=new Date(e.date_created),e.type){case"map_item_added":case"map_item_updated":this._handleItemMutated(e.item_key,e.item_url,e.id,e.item_revision,e.item_data,e.date_created,e.date_expires,"map_item_added"===e.type,!0);break;case"map_item_removed":this._handleItemRemoved(e.item_key,e.id,e.item_data,e.date_created,!0);break;case"map_removed":this.onRemoved(!1)}t&&this._advanceLastEventId(e.id,e.map_revision)}_advanceLastEventId(e,t){this.lastEventId<e&&(this.descriptor.last_event_id=e,t&&(this.descriptor.revision=t))}_updateRootDateUpdated(e){(!this.descriptor.date_updated||e.getTime()>this.descriptor.date_updated.getTime())&&(this.descriptor.date_updated=e,this.services.storage.update(this.type,this.sid,this.uniqueName,{date_updated:e}))}_handleItemMutated(e,t,n,i,r,s,a,o,c){if(this.shouldIgnoreEvent(e,n))return void Cn("SyncMapItem ",e," update skipped, current:",this.lastEventId,", remote:",n);this._updateRootDateUpdated(s);const u=this.cache.getValue(e);if(!u){const u=new pi({key:e,url:t,last_event_id:n,revision:i,data:r,date_updated:s,date_expires:a});return this.cache.store(e,u,n),void this.emitItemMutationEvent(u,c,o)}const l=xn(u.data);u.update(n,i,r,s),this.cache.store(e,u,n),void 0!==a&&u.updateDateExpires(a),this.emitItemMutationEvent(u,c,!1,l)}emitItemMutationEvent(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;const r=n?"itemAdded":"itemUpdated",s={item:e,isLocal:!t};n||(s.previousItemData=i),this.broadcastEventToListeners(r,s)}_handleItemRemoved(e,t,n,i,r){this._updateRootDateUpdated(i),this.cache.delete(e,t),this.broadcastEventToListeners("itemRemoved",{key:e,isLocal:!r,previousItemData:n})}onRemoved(e){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e})}async setTtl(e){try{const t={ttl:e},n=await this.services.network.post(this.uri,t);this.descriptor.date_expires=n.body.date_expires}catch(e){throw 404===e.status&&this.onRemoved(!1),e}}async setItemTtl(e,t){let n=await this.get(e);const i={ttl:t},r=await this.services.network.post(n.uri,i);n.updateDateExpires(r.body.date_expires)}async removeMap(){await this.services.network.delete(this.uri),this.onRemoved(!0)}}class mi extends ti{syncMapImpl;get uri(){return this.syncMapImpl.uri}get links(){return this.syncMapImpl.links}get revision(){return this.syncMapImpl.revision}get lastEventId(){return this.syncMapImpl.lastEventId}get dateExpires(){return this.syncMapImpl.dateExpires}static get type(){return fi.type}get type(){return fi.type}get sid(){return this.syncMapImpl.sid}get uniqueName(){return this.syncMapImpl.uniqueName}get dateUpdated(){return this.syncMapImpl.dateUpdated}constructor(e){super(),this.syncMapImpl=e,this.syncMapImpl.attach(this)}static itemAdded="itemAdded";static itemUpdated="itemUpdated";static itemRemoved="itemRemoved";static removed="removed";async set(e,t,n){return this.ensureNotClosed(),this.syncMapImpl.set(e,t,n)}async get(e){return this.ensureNotClosed(),this.syncMapImpl.get(e)}async mutate(e,t,n){return this.ensureNotClosed(),this.syncMapImpl.mutate(e,t,n)}async update(e,t,n){return this.ensureNotClosed(),this.syncMapImpl.update(e,t,n)}async remove(e){return this.ensureNotClosed(),this.syncMapImpl.remove(e)}async getItems(e){return this.ensureNotClosed(),this.syncMapImpl.getItems(e)}async setTtl(e){return this.ensureNotClosed(),this.syncMapImpl.setTtl(e)}async setItemTtl(e,t){return this.ensureNotClosed(),this.syncMapImpl.setItemTtl(e,t)}async removeMap(){this.ensureNotClosed(),await this.syncMapImpl.removeMap()}close(){super.close(),this.syncMapImpl.detach(this.listenerUuid)}}vn([sn.validateTypesAsync("string",sn.pureObject,["undefined",sn.objectSchema("item metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[String,Object,Object]),bn("design:returntype",Promise)],mi.prototype,"set",null),vn([sn.validateTypesAsync("string"),bn("design:type",Function),bn("design:paramtypes",[String]),bn("design:returntype",Promise)],mi.prototype,"get",null),vn([sn.validateTypesAsync("string","function",["undefined",sn.objectSchema("item metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[String,Function,Object]),bn("design:returntype",Promise)],mi.prototype,"mutate",null),vn([sn.validateTypesAsync("string",sn.pureObject,["undefined",sn.objectSchema("item metadata",{ttl:[sn.nonNegativeInteger,"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[String,Object,Object]),bn("design:returntype",Promise)],mi.prototype,"update",null),vn([sn.validateTypesAsync("string"),bn("design:type",Function),bn("design:paramtypes",[String]),bn("design:returntype",Promise)],mi.prototype,"remove",null),vn([sn.validateTypesAsync(["undefined",sn.objectSchema("query options",{from:["string","undefined"],pageSize:[sn.custom((e=>[kn(e),"a positive integer"])),"undefined"],order:[sn.custom((e=>["asc"===e||"desc"===e,"either 'asc' or 'desc'"])),"undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],mi.prototype,"getItems",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number]),bn("design:returntype",Promise)],mi.prototype,"setTtl",null),vn([sn.validateTypesAsync("string",sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[String,Number]),bn("design:returntype",Promise)],mi.prototype,"setItemTtl",null);class gi extends Zn{descriptor;constructor(e,t,n){super(e,n),this.descriptor=t}get uri(){return this.descriptor.url}get links(){return this.descriptor.links}static get type(){return"stream"}get dateExpires(){return this.descriptor.date_expires}get type(){return"stream"}get lastEventId(){return null}get indexName(){}get queryString(){}get sid(){return this.descriptor.sid}get uniqueName(){return this.descriptor.unique_name||null}async publishMessage(e){const t={data:e},n=(await this.services.network.post(this.links.messages,t)).body;return this._handleMessagePublished(n.sid,e,!1)}async setTtl(e){try{const t={ttl:e},n=await this.services.network.post(this.uri,t);this.descriptor.date_expires=n.body.date_expires}catch(e){throw 404===e.status&&this.onRemoved(!1),e}}async removeStream(){await this.services.network.delete(this.uri),this.onRemoved(!0)}_update(e){switch(e.type){case"stream_message_published":this._handleMessagePublished(e.message_sid,e.message_data,!0);break;case"stream_removed":this.onRemoved(!1)}}_handleMessagePublished(e,t,n){const i={sid:e,data:t};return this.broadcastEventToListeners("messagePublished",{message:i,isLocal:!n}),i}onRemoved(e){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e})}}vn([sn.validateTypesAsync(sn.pureObject),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],gi.prototype,"publishMessage",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number]),bn("design:returntype",Promise)],gi.prototype,"setTtl",null);class yi extends ti{syncStreamImpl;get uri(){return this.syncStreamImpl.uri}get links(){return this.syncStreamImpl.links}static get type(){return gi.type}get dateExpires(){return this.syncStreamImpl.dateExpires}get type(){return gi.type}get lastEventId(){return null}get sid(){return this.syncStreamImpl.sid}get uniqueName(){return this.syncStreamImpl.uniqueName}constructor(e){super(),this.syncStreamImpl=e,this.syncStreamImpl.attach(this)}static messagePublished="messagePublished";static removed="removed";async publishMessage(e){return this.ensureNotClosed(),this.syncStreamImpl.publishMessage(e)}async setTtl(e){return this.ensureNotClosed(),this.syncStreamImpl.setTtl(e)}async removeStream(){return this.ensureNotClosed(),this.syncStreamImpl.removeStream()}close(){super.close(),this.syncStreamImpl.detach(this.listenerUuid)}}vn([sn.validateTypesAsync(sn.pureObject),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],yi.prototype,"publishMessage",null),vn([sn.validateTypesAsync(sn.nonNegativeInteger),bn("design:type",Function),bn("design:paramtypes",[Number]),bn("design:returntype",Promise)],yi.prototype,"setTtl",null);class vi{sdk;sdkVer;os;osVer;pl;plVer;constructor(e){this.sdk="js",this.sdkVer=e,this.os=yn.os.family,this.osVer=yn.os.version,this.pl=yn.name,this.plVer=yn.version}}class bi{names;entities;constructor(){this.names=new Map,this.entities=new Map}store(e){let t=this.entities.get(e.sid);return t||(this.entities.set(e.sid,e),e.uniqueName&&this.names.set(e.type+"::"+e.uniqueName,e.sid),e)}getResolved(e,t){let n=this.names.get(t+"::"+e);return n?this.entities.get(n):null}get(e,t){return this.entities.get(e)||this.getResolved(e,t)||null}remove(e){let t=this.entities.get(e);t&&(this.entities.delete(e),t.uniqueName&&this.names.delete(t.type+"::"+t.uniqueName))}}class _i{constructor(e,t,n){this.key=e,this.value=t,this.lastEventId=n}key;value;lastEventId;get cacheKey(){return this.key}}class wi extends Zn{descriptor;cache;constructor(e,t,n,i){super(t,n),this.descriptor=e,this.cache=new ui,i&&i.forEach((e=>{const t=new _i(e.key,e.data,e.revision);this.cache.store(e.key,t,e.revision)}))}get sid(){return this.descriptor.sid}get uniqueName(){return null}get type(){return wi.type}static get type(){return"live_query"}get lastEventId(){return this.descriptor.last_event_id}get indexName(){return this.descriptor.indexName}get queryString(){return this.descriptor.queryExpression}get queryUri(){return this.descriptor.queryUri}get liveQueryDescriptor(){return this.descriptor}onRemoved(){}getItems(){const e={};return this.cache.forEach(((t,n)=>{e[t]=n.value})),e}_update(e,t){switch(e.type){case"live_query_item_updated":this.handleItemMutated(e.item_key,e.item_data,e.item_revision);break;case"live_query_item_removed":this.handleItemRemoved(e.item_key,e.item_revision);break;case"live_query_updated":this.handleBatchUpdate(e.items)}t&&this._advanceLastEventId(e.last_event_id)}handleItemMutated(e,t,n){if(this.shouldIgnoreEvent(e,n))return void Cn(`Item ${e} update skipped, revision: ${n}`);const i=new _i(e,t,n);this.cache.store(e,i,n),this.broadcastEventToListeners("itemUpdated",i)}handleItemRemoved(e,t){this.shouldIgnoreEvent(e,t)?Cn(`Item ${e} delete skipped, revision: ${t}`):(this.cache.delete(e,t),this.broadcastEventToListeners("itemRemoved",{key:e}))}handleBatchUpdate(e){let t={};null!=e&&e.forEach((e=>{t[e.key]={data:e.data,revision:e.revision}})),this.cache.forEach(((e,n)=>{const i=t[e];null!=i?this.handleItemMutated(e,i.data,i.revision):this.handleItemRemoved(e,null),delete t[e]}));for(let e in t)this.handleItemMutated(e,t[e].data,t[e].revision)}shouldIgnoreEvent(e,t){return null!=e&&null!=t&&this.cache.isKnown(e,t)}_advanceLastEventId(e,t){this.lastEventId<e&&(this.descriptor.last_event_id=e)}}async function xi(e){let{network:t,queryString:n,uri:i,type:r}=e;if(null==n)throw new SyncError("Invalid query",400,54507);const s={query_string:n};return r===Si.type&&(s.type=r),(await t.post(i,s,void 0,!0)).body}class Si extends ti{liveQueryImpl;static get type(){return wi.type}get type(){return wi.type}get lastEventId(){return this.liveQueryImpl.lastEventId}get sid(){return this.liveQueryImpl.sid}constructor(e){super(),this.liveQueryImpl=e,this.liveQueryImpl.attach(this)}static itemUpdated="itemUpdated";static itemRemoved="itemRemoved";close(){super.close(),this.liveQueryImpl.detach(this.listenerUuid)}getItems(){return this.ensureNotClosed(),this.liveQueryImpl.getItems()}}class ki extends ln.ReplayEventEmitter{indexName;queryUri;insightsUri;liveQueryCreator;network;queryExpression=null;items={};static get type(){return"instant_query"}get type(){return ki.type}constructor(e){super(),Object.assign(this,e),this.updateIndexName(e.indexName)}static searchResult="searchResult";async search(e){this.items={};try{const t=await xi({network:this.network,uri:this.queryUri,queryString:e});this.queryExpression=e,t.items&&t.items.forEach((e=>{this.items[e.key]=e.data})),this.emit("searchResult",this.getItems())}catch(t){throw Pn(`Error '${t.message}' while executing query '${e}'`),this.queryExpression=null,t}}async subscribe(){return null==this.queryExpression?Promise.reject(new SyncError("Invalid query",400,54507)):this.liveQueryCreator(this.indexName,this.queryExpression)}getItems(){return this.items}updateIndexName(e){this.indexName=e,this.queryUri=this.generateQueryUri(this.indexName)}generateQueryUri(e){return new _n(this.insightsUri).pathSegment(e).pathSegment("Items").build()}}vn([sn.validateTypesAsync("string"),bn("design:type",Function),bn("design:paramtypes",[String]),bn("design:returntype",Promise)],ki.prototype,"search",null),vn([sn.validateTypes(sn.nonEmptyString),bn("design:type",Function),bn("design:paramtypes",[String]),bn("design:returntype",void 0)],ki.prototype,"updateIndexName",null);const Ei="4.0.1-rc.1";function Ti(e){if(e){if("string"==typeof e)return{id:e,mode:"open_or_create"};{let t=e.mode||(e.id?"open_or_create":"create_new");return{...e,mode:t}}}return{mode:"create_new"}}const Ii="com.twilio.rtd.cds.document",Ci="com.twilio.rtd.cds.list",Ri="com.twilio.rtd.cds.map",Pi="twilio.sync.event";class Client extends ln.ReplayEventEmitter{services;entities;_currentState="disconnected";constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(super(),!e)throw new Error("Sync library needs a valid Twilio token to be passed");t.hasOwnProperty("logLevel")?In(t.logLevel):In("silent");const n=t.productId=t.productId||"data_sync";t.clientMetadata=t.clientMetadata||{},t.clientMetadata.hasOwnProperty("type")||(t.clientMetadata.type="sync"),t.clientMetadata.hasOwnProperty("sdk")||(t.clientMetadata.sdk="JS",t.clientMetadata.sdkv=Ei);const i=!t.twilsockClient,r=t.twilsockClient=t.twilsockClient??new an.TwilsockClient(e,n,t);r.populateInitRegistrations(new Set([Pi,Ii,Ci,Ri])),r.on("tokenAboutToExpire",(()=>this.emit("tokenAboutToExpire"))),r.on("tokenExpired",(()=>this.emit("tokenExpired"))),r.on("messageReceived",((e,t)=>this._routeMessage(e,JSON.parse(t))));let s=new Mn(t),a=new Qn(new vi(Ei),s,r),o=new Xn(s);this.services={config:s,twilsock:r,network:a,storage:o,router:this,subscriptions:null},this.services.subscriptions=new Kn(this.services),r.onWithReplay("disconnected",(e=>{this._currentState="disconnected",this.emitNextTick("connectionStateChanged","disconnected"),this.services.subscriptions.onConnectionStateChanged(!1)})),r.onWithReplay("connecting",(()=>{this._currentState="connecting",this.emitNextTick("connectionStateChanged","connecting"),this.services.subscriptions.onConnectionStateChanged(!1)})),r.onWithReplay("connected",(()=>{this._currentState="connected",this.emitNextTick("connectionStateChanged","connected"),this.services.subscriptions.onConnectionStateChanged(!0)})),this.entities=new bi,i&&r.connect()}static connectionStateChanged="connectionStateChanged";static connectionError="connectionError";static tokenAboutToExpire="tokenAboutToExpire";static tokenExpired="tokenExpired";_routeMessage(e,t){switch(Cn("Notification type:",e,"content:",t),e){case Ii:case Ci:case Ri:this.services.subscriptions.acceptMessage(t,!1);break;case Pi:this.services.subscriptions.acceptMessage(t,!0)}}_subscribe(e,t){this.services.subscriptions.add(e,t)}_unsubscribe(e){this.services.subscriptions.remove(e)}static get version(){return Ei}get connectionState(){return this._currentState}async ensureReady(){this.services.config.sessionStorageEnabled}storeRootInSessionCache(e,t,n){if(!this.services.config.sessionStorageEnabled||!t)return;let i=xn(n);e!==hi.type&&e!==mi.type||(i.last_event_id=null,delete i.items),this.services.storage.store(e,t,i)}readRootFromSessionCache(e,t){return this.services.config.sessionStorageEnabled&&t?this.services.storage.read(e,t):null}async _get(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!t)throw new SyncError("Cannot get entity without id",404);const i=new _n(e).pathSegment(t).queryParam("Include",n?"items":void 0).build();return(await this.services.network.get(i)).body}_createDocument(e,t,n){const i={unique_name:e,data:t||{}};return void 0!==n&&(i.ttl=n),this.services.network.post(this.services.config.documentsUri,i).then((e=>(e.body.data=i.data,e.body)))}async _getDocument(e){return this.readRootFromSessionCache(ii.type,e)||this._get(this.services.config.documentsUri,e)}_createList(e,t,n,i){const r={unique_name:e,purpose:t,context:n};return void 0!==i&&(r.ttl=i),this.services.network.post(this.services.config.listsUri,r).then((e=>e.body))}async _getList(e){return this.readRootFromSessionCache(hi.type,e)||this._get(this.services.config.listsUri,e)}_createMap(e,t){const n={unique_name:e};return void 0!==t&&(n.ttl=t),this.services.network.post(this.services.config.mapsUri,n).then((e=>e.body))}async _getMap(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return this.readRootFromSessionCache(mi.type,e)||this._get(this.services.config.mapsUri,e,t)}async _getStream(e){return this.readRootFromSessionCache(yi.type,e)||this._get(this.services.config.streamsUri,e,!1)}async _createStream(e,t){const n={unique_name:e};void 0!==t&&(n.ttl=t);return(await this.services.network.post(this.services.config.streamsUri,n)).body}_getLiveQuery(e){return this.readRootFromSessionCache(Si.type,e)}getCached(e,t){return e&&this.entities.get(e,t)||null}removeFromCacheAndSession(e,t,n){this.entities.remove(t),this.services.config.sessionStorageEnabled&&this.services.storage.remove(e,t,n)}async document(e){await this.ensureReady();let t,n=Ti(e);if("create_new"===n.mode)t=await this._createDocument(n.id,n.data,n.ttl);else{let i=this.getCached(n.id,ii.type);if(i)return new ii(i);try{t=await this._getDocument(n.id)}catch(i){if(404!==i.status||"open_existing"===n.mode)throw i;try{t=await this._createDocument(n.id,n.data,n.ttl)}catch(t){if(409===t.status)return this.document(e);throw t}}}this.storeRootInSessionCache(ii.type,n.id,t);let i=new ni(this.services,t,((e,t,n)=>this.removeFromCacheAndSession(e,t,n)));return i=this.entities.store(i),new ii(i)}async map(e){await this.ensureReady();let t,n=Ti(e);if("create_new"===n.mode)t=await this._createMap(n.id,n.ttl);else{let i=this.getCached(n.id,mi.type);if(i)return new mi(i);try{t=await this._getMap(n.id,n.includeItems)}catch(i){if(404!==i.status||"open_existing"===n.mode)throw i;try{t=await this._createMap(n.id,n.ttl)}catch(t){if(409===t.status)return this.map(e);throw t}}}this.storeRootInSessionCache(mi.type,n.id,t);let i=new fi(this.services,t,((e,t,n)=>this.removeFromCacheAndSession(e,t,n)));return i=this.entities.store(i),new mi(i)}async list(e){await this.ensureReady();let t,n=Ti(e);if("create_new"===n.mode)t=await this._createList(n.id,n.purpose,n.context,n.ttl);else{let i=this.getCached(n.id,hi.type);if(i)return new hi(i);try{t=await this._getList(n.id)}catch(i){if(404!==i.status||"open_existing"===n.mode)throw i;try{t=await this._createList(n.id,n.purpose,n.context,n.ttl)}catch(t){if(409===t.status)return this.list(e);throw t}}}this.storeRootInSessionCache(hi.type,n.id,t);let i=new di(this.services,t,((e,t,n)=>this.removeFromCacheAndSession(e,t,n)));return i=this.entities.store(i),new hi(i)}async stream(e){await this.ensureReady();let t,n=Ti(e);if("create_new"===n.mode)t=await this._createStream(n.id,n.ttl);else{let i=this.getCached(n.id,yi.type);if(i)return new yi(i);try{t=await this._getStream(n.id)}catch(i){if(404!==i.status||"open_existing"===n.mode)throw i;try{t=await this._createStream(n.id,n.ttl)}catch(t){if(409===t.status)return this.stream(e);throw t}}}this.storeRootInSessionCache(yi.type,n.id,t);let i=new gi(this.services,t,((e,t,n)=>this.removeFromCacheAndSession(e,t,n)));return i=this.entities.store(i),new yi(i)}async shutdown(){await this.services.subscriptions.shutdown(),await this.services.network.disconnect()}async updateToken(e){return this.services.twilsock.updateToken(e).catch((e=>{if(e instanceof zn&&401===e.errorInfo.status)throw new SyncError("Updated token was rejected by server",400,51130);throw e}))}async liveQuery(e,t){await this.ensureReady();const n=new _n(this.services.config.insightsUri).pathSegment(e).pathSegment("Items").build(),i=await xi({network:this.services.network,uri:n,queryString:t,type:Si.type});let r=this.getCached(i.query_id,Si.type);if(!r){let s=this._getLiveQuery(i.query_id);s||(s={indexName:e,queryExpression:t,sid:i.query_id,queryUri:n,last_event_id:i.last_event_id});const a=(e,t,n)=>this.removeFromCacheAndSession(e,t,n);r=new wi(s,this.services,a,i.items)}return this.storeRootInSessionCache(Si.type,i.query_id,r.liveQueryDescriptor),r=this.entities.store(r),new Si(r)}async instantQuery(e){await this.ensureReady();return new ki({indexName:e,network:this.services.network,insightsUri:this.services.config.insightsUri,liveQueryCreator:(e,t)=>this.liveQuery(e,t)})}}vn([sn.validateTypesAsync(["undefined","string",sn.objectSchema("open document options",{id:["string","undefined"],mode:[sn.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[sn.nonNegativeInteger,"undefined"],data:[sn.pureObject,"undefined",sn.literal(null)]})]),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],Client.prototype,"document",null),vn([sn.validateTypesAsync(["undefined","string",sn.objectSchema("open map options",{id:["string","undefined"],mode:[sn.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[sn.nonNegativeInteger,"undefined"],data:[sn.pureObject,"undefined",sn.literal(null)],includeItems:["boolean","undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],Client.prototype,"map",null),vn([sn.validateTypesAsync(["undefined","string",sn.objectSchema("open list options",{id:["string","undefined"],mode:[sn.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[sn.nonNegativeInteger,"undefined"],data:[sn.pureObject,"undefined",sn.literal(null)],purpose:["string","undefined"],context:[sn.pureObject,"undefined"],includeItems:["boolean","undefined"]})]),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],Client.prototype,"list",null),vn([sn.validateTypesAsync(["undefined","string",sn.objectSchema("open stream options",{id:["string","undefined"],mode:[sn.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[sn.nonNegativeInteger,"undefined"],data:[sn.pureObject,"undefined",sn.literal(null)]})]),bn("design:type",Function),bn("design:paramtypes",[Object]),bn("design:returntype",Promise)],Client.prototype,"stream",null),vn([sn.validateTypesAsync(sn.nonEmptyString),bn("design:type",Function),bn("design:paramtypes",[String]),bn("design:returntype",Promise)],Client.prototype,"updateToken",null),vn([sn.validateTypesAsync(sn.nonEmptyString,"string"),bn("design:type",Function),bn("design:paramtypes",[String,String]),bn("design:returntype",Promise)],Client.prototype,"liveQuery",null),vn([sn.validateTypesAsync(sn.nonEmptyString),bn("design:type",Function),bn("design:paramtypes",[String]),bn("design:returntype",Promise)],Client.prototype,"instantQuery",null),rn.Client=Client,rn.InsightsItem=_i,rn.InstantQuery=ki,rn.LiveQuery=Si,rn.Paginator=Paginator;var Mi=rn.SyncClient=Client;rn.SyncDocument=ii,rn.SyncList=hi,rn.SyncListItem=ri,rn.SyncMap=mi,rn.SyncMapItem=pi,rn.SyncStream=yi;var Oi={};
|
312
|
-
/*
|
313
|
-
@license
|
314
|
-
Copyright (c) 2018, Twilio, Inc.
|
315
|
-
|
316
|
-
Permission to use, copy, modify, and/or distribute this software for any
|
317
|
-
purpose with or without fee is hereby granted, provided that the above
|
318
|
-
copyright notice and this permission notice appear in all copies.
|
319
|
-
|
320
|
-
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
321
|
-
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
322
|
-
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
|
323
|
-
SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
324
|
-
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
|
325
|
-
OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
|
326
|
-
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
327
|
-
|
328
|
-
*/!function(e){var t=void 0!==t?t:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};Object.defineProperty(e,"__esModule",{value:!0});var n=Ie,i=u.exports,r=pe,s=P;function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var o=a(i);function c(e,t,n,i){var r,s=arguments.length,a=s<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,n,i);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(s<3?r(a):s>3?r(t,n,a):r(t,n))||a);return s>3&&a&&Object.defineProperty(t,n,a),a}function l(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function d(e,t){return[`${(new Date).toISOString()} MCS Client ${e}:`].concat(Array.from(t))}class h{prefix="";constructor(e){this.prefix=null!=e&&e.length>0?e+" ":""}static scope(e){return new h(e)}setLevel(e){o.setLevel(e)}static setLevel(e){o.setLevel(e)}trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.trace.apply(null,d(this.prefix+"T",t))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.debug.apply(null,d(this.prefix+"D",t))}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.info.apply(null,d(this.prefix+"I",t))}warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.warn.apply(null,d(this.prefix+"W",t))}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.error.apply(null,d(this.prefix+"E",t))}static trace(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.trace.apply(null,d("T",t))}static debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.debug.apply(null,d("D",t))}static info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.info.apply(null,d("I",t))}static warn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.warn.apply(null,d("W",t))}static error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];o.error.apply(null,d("E",t))}}const p=(e,t)=>{return`${n=e,n.startsWith("http")?"":(e=>`https://mcs.${e??"us1"}.twilio.com`)(t)}${e}`;var n};class f{token;retryWhenThrottledOverride;backoffConfigOverride;mediaUrl;mediaSetUrl;region;constructor(e,t,n,i){const r=i.MCS??i??{};this.region=r.region??i.region??"us1",this.mediaUrl=p(t,this.region),this.mediaSetUrl=n?p(n):`${this.mediaUrl}Set`,this.token=e,this.retryWhenThrottledOverride=r.retryWhenThrottledOverride??true,this.backoffConfigOverride=r.backoffConfigOverride??f.backoffConfigDefault}static get backoffConfigDefault(){return{min:1e3,max:4e3,maxAttemptsCount:3}}static get retryWhenThrottledDefault(){return true}updateToken(e){this.token=e}}class Media{state;network;config;constructor(e,t,n){this.config=e,this.network=t,this._update(n)}get sid(){return this.state.sid}get serviceSid(){return this.state.serviceSid}get dateCreated(){return this.state.dateCreated}get dateUpdated(){return this.state.dateUpdated}get contentType(){return this.state.contentType}get size(){return this.state.size}get fileName(){return this.state.filename}get filename(){return this.state.filename}get category(){return this.state.category}getContentUrl(){return new n.CancellablePromise((async(e,t,n)=>{const i=this.network.get(`${this.config.mediaUrl}/${this.sid}`);n((()=>i.cancel()));try{const t=await i;this._update(t.body),e(this.state.contentDirectUrl)}catch(e){t(e)}}))}_update(e){this.state={sid:e.sid,serviceSid:e.service_sid,channelSid:e.channel_sid,messageSid:e.message_sid,dateCreated:e.date_created?new Date(e.date_created):null,dateUploadUpdated:e.date_upload_updated?new Date(e.date_upload_updated):null,dateUpdated:e.date_updated?new Date(e.date_updated):null,size:e.size,contentType:e.content_type,author:e.author,url:e.url,contentUrl:e.links.content,contentDirectUrl:e.links.content_direct_temporary??null,filename:e.filename??null,category:e.category??"media",isMultipartUpstream:e.is_multipart_upstream??!1}}}class m extends Error{code;body;status;headers;constructor(e,t,n,i,r){super(e),this.code=t,this.body=n,this.status=i,this.headers=r}}const g=t.XMLHttpRequest||{};class y{static request(e,t,i,r){return new n.CancellablePromise(((n,s,a)=>{const o=new g;let c=!1;a((()=>{o.abort(),c=!0})),o.open(e,t,!0),o.onreadystatechange=function(){if(4!==o.readyState||c)return;const e=(t=o.getAllResponseHeaders())?t.split("\r\n").map((e=>e.split(": "))).filter((e=>2===e.length&&e[1].length>0)).reduce(((e,t)=>(e[t[0]]=t[1],e)),{}):{};var t;const i=function(e){const t=e.getResponseHeader("Content-Type");if(!t||0!==t.indexOf("application/json")||0===e.responseText.length)return e.responseText;try{return JSON.parse(e.responseText)}catch(t){return e.responseText}}(o);if(200<=o.status&&o.status<300)n({status:o.status,headers:e,body:i});else{const t=o.statusText??"NONE";let n;if("string"==typeof i)if(i&&1===i.split("\n",2).length)n=i;else{const e=i.replace(/<.*?>/g,"").split(/\r\n/g).filter((e=>e.length))[0]?.split(" ");n=e?.length>2?e?.slice(1).join(" "):""}else n=JSON.stringify(i);const r=`${o.status}: [${t}] ${n}`;s(new m(r,o.status,i,t,e))}};for(const e in i)o.setRequestHeader(e,i[e]),"Content-Type"===e&&"application/json"===i[e]&&(r=JSON.stringify(r));o.send(r)}))}get(e,t){return y.request("GET",e,t)}post(e,t,n){return y.request("POST",e,t,n)}}const v=h.scope("Network");class b{config;transport;constructor(e,t){this.config=e,this.transport=t}backoffConfig(){return Object.assign(f.backoffConfigDefault,this.config.backoffConfigOverride)}retryWhenThrottled(){return this.config.retryWhenThrottledOverride??f.retryWhenThrottledDefault??!1}executeWithRetry(e,t){return new n.CancellablePromise((async(n,i,s)=>{const a=new r.Retrier(this.backoffConfig()),o=[502,503,504];t&&o.push(429),s((()=>{a.cancel(),a.removeAllListeners()})),a.on("attempt",(async()=>{try{const t=e();s((()=>{t.cancel(),a.cancel(),a.removeAllListeners()}));const n=await t;a.succeeded(n)}catch(e){o.indexOf(e.status)>-1||"Twilsock disconnected"===e.message?a.failed(e):(a.removeAllListeners(),a.cancel(),i(e))}})),a.on("succeeded",(e=>{n(e)})),a.on("cancelled",(e=>i(e))),a.on("failed",(e=>i(e))),a.start()}))}get(e){return new n.CancellablePromise((async(t,n,i)=>{const r={"X-Twilio-Token":this.config.token},s=this.executeWithRetry((()=>this.transport.get(e,r)),this.retryWhenThrottled());v.trace("sending GET request to ",e," headers ",r),i((()=>s.cancel()));try{const e=await s;v.trace("response",e),t(e)}catch(e){v.debug(`get() error ${e}`),n(e)}}))}post(e,i,r,s,a){const o={"X-Twilio-Token":this.config.token};"undefined"!=typeof FormData&&r instanceof FormData||!s||Object.assign(o,{"Content-Type":s});const c=new URL(e);return i&&c.searchParams.append("Category",i),a&&c.searchParams.append("Filename",a),new n.CancellablePromise((async(n,i,s)=>{const a=this.transport.post(c.href,o,r);let u;s((()=>a.cancel())),v.trace(`sending POST request to ${e} with headers ${o}`);try{u=await a}catch(e){return void 0===t.XMLHttpRequest&&r instanceof FormData?void i(new TypeError("Posting FormData supported only with browser engine's FormData")):(v.debug(`post() error ${e}`),void i(e))}v.trace("response",u),n(u)}))}}const _=h.scope("");e.default=class{transport;options;network;config;static version="1.0.0-rc.6";constructor(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};this.options=i,this.options.logLevel=this.options.logLevel??"silent",this.config=new f(e,t,n,this.options),_.setLevel(this.options.logLevel),this.options.transport=this.options.transport??new y,this.transport=this.options.transport,this.network=new b(this.config,this.transport)}updateToken(e){_.info("updateToken"),this.config.updateToken(e)}get(e){return new n.CancellablePromise((async(t,n,i)=>{const r=this.network.get(`${this.config.mediaUrl}/${e}`);i((()=>r.cancel()));try{const e=await r;t(new Media(this.config,this.network,e.body))}catch(e){n(e)}}))}post(e,t,i,r){return new n.CancellablePromise((async(n,s,a)=>{const o=this.network.post(this.config.mediaUrl,i??"media",t,e,r);a((()=>o.cancel()));try{const e=await o;n(new Media(this.config,this.network,e.body))}catch(e){s(e)}}))}postFormData(e,t){return new n.CancellablePromise((async(n,i,r)=>{const s=this.network.post(this.config.mediaUrl,t??"media",e);r((()=>s.cancel()));try{const e=await s;n(new Media(this.config,this.network,e.body))}catch(e){i(e)}}))}mediaSetGet(e){return new n.CancellablePromise((async(t,n,i)=>{const r={command:"get",list:e.map((e=>({media_sid:e})))},s=this.network.post(`${this.config.mediaSetUrl}`,null,r,"application/json");i((()=>s.cancel()));try{const e=await s;t(e.body.map((e=>{if(200===e.code)return new Media(this.config,this.network,e.media_record);n(`Failed to obtain detailed information about Media items (failed SID ${e.media_record.sid})`)})))}catch(e){n(e)}}))}mediaSetGetContentUrls(e){return new n.CancellablePromise((async(t,n,i)=>{const r={command:"get",list:e.map((e=>({media_sid:e})))},s=this.network.post(`${this.config.mediaSetUrl}`,null,r,"application/json");i((()=>s.cancel()));try{const e=await s,i=new Map;e.body.forEach((e=>{200===e.code?i.set(e.media_record.sid,e.media_record.links.content_direct_temporary):n(`Failed to obtain detailed information about Media items (failed SID ${e.media_record.sid})`)})),t(i)}catch(e){n(e)}}))}},c([s.validateTypes(s.nonEmptyString),l("design:type",Function),l("design:paramtypes",[String]),l("design:returntype",void 0)],e.default.prototype,"updateToken",null),c([s.validateTypesAsync(s.nonEmptyString),l("design:type",Function),l("design:paramtypes",[String]),l("design:returntype",n.CancellablePromise)],e.default.prototype,"get",null),e.default=c([s.validateConstructorTypes(s.nonEmptyString,s.nonEmptyString,[s.nonEmptyString,s.literal(null)],[s.pureObject,"undefined"]),l("design:paramtypes",[String,String,Object,Object])],e.default),Object.defineProperty(e,"CancellablePromise",{enumerable:!0,get:function(){return n.CancellablePromise}}),e.Client=e.default,e.McsClient=e.default,e.McsMedia=Media,e.Media=Media}(Oi);const Ai=h.scope("Participant");class Participant extends ue{state;links;services;conversation;get sid(){return this.state.sid}get attributes(){return this.state.attributes}get dateCreated(){return this.state.dateCreated}get dateUpdated(){return this.state.dateUpdated}get identity(){return this.state.identity}get isTyping(){return this.state.isTyping}get lastReadMessageIndex(){return this.state.lastReadMessageIndex}get lastReadTimestamp(){return this.state.lastReadTimestamp}get roleSid(){return this.state.roleSid}get type(){return this.state.type}get bindings(){return this.state.bindings??{}}constructor(e,t,n,i,r){if(super(),this.conversation=n,this.links=i,this.services=r,this.state={attributes:C(e.attributes,"Retrieved malformed attributes from the server for participant: "+t,Ai),dateCreated:e.dateCreated?I(e.dateCreated):null,dateUpdated:e.dateCreated?I(e.dateUpdated):null,sid:t,typingTimeout:null,isTyping:!1,identity:e.identity,roleSid:e.roleSid??"",lastReadMessageIndex:Number.isInteger(e.lastConsumedMessageIndex)?e.lastConsumedMessageIndex:null,lastReadTimestamp:e.lastConsumptionTimestamp?I(e.lastConsumptionTimestamp):null,type:e.type||"chat",userInfo:e.userInfo,bindings:e.bindings??{}},!e.identity&&!e.type)throw new Error("Received invalid Participant object from server: Missing identity or type of Participant.")}static typingStarted="typingStarted";static typingEnded="typingEnded";static updated="updated";_startTyping(e){return this.state.typingTimeout&&clearTimeout(this.state.typingTimeout),this.state.isTyping=!0,this.emit("typingStarted",this),this.conversation.emit("typingStarted",this),this.state.typingTimeout=Number(setTimeout((()=>this._endTyping()),e)),this}_endTyping(){this.state.typingTimeout&&(this.state.isTyping=!1,this.emit("typingEnded",this),this.conversation.emit("typingEnded",this),clearInterval(this.state.typingTimeout),this.state.typingTimeout=null)}_update(e){const t=[],n=C(e.attributes,"Retrieved malformed attributes from the server for participant: "+this.state.sid,Ai);e.attributes&&!de(this.state.attributes,n)&&(this.state.attributes=n,t.push("attributes"));const i=I(e.dateUpdated);e.dateUpdated&&i?.getTime()!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=i,t.push("dateUpdated"));const r=I(e.dateCreated);if(e.dateCreated&&r?.getTime()!==(this.state.dateCreated&&this.state.dateCreated.getTime())&&(this.state.dateCreated=r,t.push("dateCreated")),e.roleSid&&this.state.roleSid!==e.roleSid&&(this.state.roleSid=e.roleSid,t.push("roleSid")),!Number.isInteger(e.lastConsumedMessageIndex)&&null!==e.lastConsumedMessageIndex||this.state.lastReadMessageIndex===e.lastConsumedMessageIndex||(this.state.lastReadMessageIndex=e.lastConsumedMessageIndex,t.push("lastReadMessageIndex")),e.lastConsumptionTimestamp){const n=new Date(e.lastConsumptionTimestamp);this.state.lastReadTimestamp&&this.state.lastReadTimestamp.getTime()===n.getTime()||(this.state.lastReadTimestamp=n,t.push("lastReadTimestamp"))}return e.bindings&&!de(this.state.bindings,e.bindings)&&(this.state.bindings=e.bindings,t.push("bindings")),t.length>0&&this.emit("updated",{participant:this,updateReasons:t}),this}async getUser(){if("chat"!=this.type)throw new Error("Getting User is not supported for this Participant type: "+this.type);return this.services.users.getUser(this.state.identity,this.state.userInfo)}async remove(){return this.conversation.removeParticipant(this)}async updateAttributes(e){return await this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(e)}),this}}n([X(Z),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],Participant.prototype,"updateAttributes",null);const ji=h.scope("Participants");class $i extends ue{configuration;services;links;rosterEntityPromise=null;conversation;participants;constructor(e,t,n,i,r){super(),this.conversation=e,this.participants=t,this.links=n,this.configuration=i,this.services=r}async unsubscribe(){if(this.rosterEntityPromise){(await this.rosterEntityPromise).close(),this.rosterEntityPromise=null}}subscribe(e){const t="string"==typeof e?this.services.syncClient.map({id:e,mode:"open_existing"}):Promise.resolve(e);return this.rosterEntityPromise=this.rosterEntityPromise||t.then((e=>{e.on("itemAdded",(e=>{ji.debug(this.conversation.sid+" itemAdded: "+e.item.key),this.upsertParticipant(e.item.key,e.item.data).then((e=>{this.emit("participantJoined",e)}))})),e.on("itemRemoved",(e=>{ji.debug(this.conversation.sid+" itemRemoved: "+e.key);const t=e.key;if(!this.participants.has(t))return;const n=this.participants.get(t);this.participants.delete(t),n&&this.emit("participantLeft",n)})),e.on("itemUpdated",(e=>{ji.debug(this.conversation.sid+" itemUpdated: "+e.item.key),this.upsertParticipant(e.item.key,e.item.data)}));const t=[],n=e=>(e.items.forEach((e=>{t.push(this.upsertParticipant(e.key,e.data))})),e.hasNextPage?e.nextPage().then(n):null);return e.getItems().then(n).then((()=>Promise.all(t))).then((()=>e))})).catch((e=>{throw this.rosterEntityPromise=null,"disconnected"!=this.services.syncClient.connectionState&&ji.error("Failed to get roster object for conversation",this.conversation.sid,e),ji.debug("ERROR: Failed to get roster object for conversation",this.conversation.sid,e),e}))}async upsertParticipantFromResponse(e){const{sid:t,attributes:n,date_created:i,date_updated:r,identity:s,role_sid:a,messaging_binding:o}=e;return await this.upsertParticipant(t,{attributes:n,dateCreated:new Date(i),dateUpdated:new Date(r),identity:s,roleSid:a,lastConsumedMessageIndex:null,lastConsumptionTimestamp:null,type:o?.type??"chat"})}async upsertParticipant(e,t){let n=this.participants.get(e);if(n)return n._update(t);const i={self:`${this.links.participants}/${e}`};return n=new Participant(t,e,this.conversation,i,this.services),this.participants.set(e,n),n.on("updated",(e=>this.emit("participantUpdated",e))),n}async getParticipants(){return this.rosterEntityPromise?this.rosterEntityPromise.then((()=>{const e=[];return this.participants.forEach((t=>e.push(t))),e})):[]}async getParticipantBySid(e){return this.rosterEntityPromise?this.rosterEntityPromise.then((()=>{const t=this.participants.get(e);if(!t)throw new Error("Participant with SID "+e+" was not found");return t})):null}async getParticipantByIdentity(e){let t=null;return this.rosterEntityPromise?this.rosterEntityPromise.then((()=>{if(this.participants.forEach((n=>{n.identity===e&&(t=n)})),!t)throw new Error("Participant with identity "+e+" was not found");return t})):null}async add(e,t){const n=await this.services.commandExecutor.mutateResource("post",this.links.participants,{identity:e,attributes:void 0!==t?JSON.stringify(t):void 0});return await this.upsertParticipantFromResponse(n)}async addNonChatParticipant(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};const r=await this.services.commandExecutor.mutateResource("post",this.links.participants,{attributes:void 0!==n?JSON.stringify(n):void 0,messaging_binding:{address:t,proxy_address:e,name:i?.email?.name,level:i?.email?.level}});return await this.upsertParticipantFromResponse(r)}remove(e){return this.services.commandExecutor.mutateResource("delete",`${this.links.participants}/${encodeURIComponent(e)}`)}}class Media{state;services;mcsMedia=null;constructor(e,t){this.services=t,e instanceof Oi.McsMedia&&(this.mcsMedia=e),this.state={sid:e.sid,category:e.category,filename:e.filename,contentType:e.contentType,size:e.size}}get sid(){return this.state.sid}get filename(){return this.state.filename}get contentType(){return this.state.contentType}get size(){return this.state.size}get category(){return this.state.category}getContentTemporaryUrl(){return new Oi.CancellablePromise((async(e,t,n)=>{const i=this._fetchMcsMedia();let r=this.mcsMedia?.getContentUrl();n((()=>{i.cancel(),r&&r.cancel()}));try{if(!this.mcsMedia){const e=await i;r=e.getContentUrl()}e(r?await r:null)}catch(e){t(e)}}))}_fetchMcsMedia(){return new Oi.CancellablePromise((async(e,t,n)=>{const i=this.services.mcsClient.get(this.state.sid);if(this.services.mcsClient){n((()=>i.cancel()));try{this.mcsMedia=await i,e(this.mcsMedia)}catch(e){t(e)}}else t(new Error("Media Content Service is unavailable"))}))}}class AggregatedDeliveryReceipt{state;constructor(e){this.state=e}get total(){return this.state.total}get sent(){return this.state.sent}get delivered(){return this.state.delivered}get read(){return this.state.read}get undelivered(){return this.state.undelivered}get failed(){return this.state.failed}_update(e){this.state=e}_isEquals(e){const t=this.total===e.total,n=this.sent===e.sent,i=this.delivered===e.delivered,r=this.read===e.read,s=this.undelivered===e.undelivered,a=this.failed===e.failed;return t&&n&&i&&r&&s&&a}}class Ni{state;get hasNextPage(){return!!this.state.nextToken}get hasPrevPage(){return!!this.state.prevToken}get items(){return this.state.items}constructor(e,t,n,i){this.state={prevToken:n,nextToken:i,source:t,items:e}}nextPage(){return this.hasNextPage?this.state.source(this.state.nextToken):Promise.reject(new Error("No next page"))}prevPage(){return this.hasPrevPage?this.state.source(this.state.prevToken):Promise.reject(new Error("No previous page"))}}class DetailedDeliveryReceipt{sid;messageSid;conversationSid;channelMessageSid;participantSid;status;errorCode;dateCreated;dateUpdated;constructor(e){this.sid=e.sid,this.messageSid=e.message_sid,this.conversationSid=e.conversation_sid,this.channelMessageSid=e.channel_message_sid,this.participantSid=e.participant_sid,this.status=e.status||"queued",this.errorCode=e.error_code||0,this.dateCreated=e.date_created,this.dateUpdated=e.date_updated}}const Ui=e=>e.map((e=>{const t=JSON.stringify(e);switch(e.type){case"QUICK_REPLY":return{type:"reply",title:e.title,id:e.id??"",index:e.index??0,rawData:t};case"PHONE_NUMBER":return{type:"phone",title:e.title,phone:e.phone??"",rawData:t};case"URL":return{type:"url",title:e.title,url:e.url??"",rawData:t};default:return{type:"other",rawData:t}}})),Li=(e,t)=>{const n=JSON.stringify(t);switch(e){case"twilio/text":return{type:"text",body:t.body,rawData:n};case"twilio/media":{const e=t;return{type:"media",body:e.body,media:e.media,rawData:n}}case"twilio/location":{const e=t;return{type:"location",longitude:e.longitude,latitude:e.latitude,label:e.label,rawData:n}}case"twilio/quick-reply":{const e=t;return{type:"quickReply",body:e.body,replies:e.actions,rawData:n}}case"twilio/call-to-action":{const e=t;return{type:"callToAction",body:e.body,actions:Ui(e.actions),rawData:n}}case"twilio/list-picker":{const e=t;return{type:"listPicker",body:e.body,button:e.button,items:e.items,rawData:n}}case"twilio/card":{const e=t;return{type:"card",title:e.title,subtitle:e.subtitle,media:e.media??[],actions:Ui(e.actions??[]),rawData:n}}default:return{type:"other",rawData:n}}};class ContentTemplateVariable{name;value;constructor(e,t){this.name=e,this.value=t}copyWithValue(e){return new ContentTemplateVariable(this.name,e)}}class Fi{sid;friendlyName;variables;variants;dateCreated;dateUpdated;constructor(e){this.sid=e.sid,this.friendlyName=e.friendly_name,this.variables=Object.entries(JSON.parse(e.variables)).map((e=>{let[t,n]=e;return new ContentTemplateVariable(t,n)})),this.variants=(e=>{const t=new Map;for(const[n,i]of Object.entries(e))t.set(n,Li(n,i));return t})(e.variants),this.dateCreated=new Date(e.date_created),this.dateUpdated=new Date(e.date_updated)}}const qi=h.scope("Message"),Di=t.XMLHttpRequest||{};class Message extends ue{conversation;links;configuration;services;state;constructor(e,t,n,i,r,s){super(),this.conversation=n,this.links=i,this.configuration=r,this.services=s,this.state={sid:t.sid,index:e,author:t.author,subject:t.subject,contentSid:t.contentSid,body:t.text??null,timestamp:t.timestamp?new Date(t.timestamp):null,dateUpdated:t.dateUpdated?new Date(t.dateUpdated):null,lastUpdatedBy:t.lastUpdatedBy??null,attributes:C(t.attributes,`Got malformed attributes for the message ${t.sid}`,qi),type:t.type??"text",medias:"media"===t.type&&t.medias?t.medias.map((e=>new Media(e,this.services))):"media"===t.type&&t.media&&!t.medias?[new Media({...t.media,category:"media"},this.services)]:null,participantSid:t.memberSid??null,aggregatedDeliveryReceipt:t.delivery?new AggregatedDeliveryReceipt(t.delivery):null,hasChannelMetadata:t.channelMetadata??!1}}static updated="updated";get sid(){return this.state.sid}get author(){return this.state.author}get subject(){return this.state.subject}get contentSid(){return this.state.contentSid}get body(){return this.state.body}get dateUpdated(){return this.state.dateUpdated}get index(){return this.state.index}get lastUpdatedBy(){return this.state.lastUpdatedBy}get dateCreated(){return this.state.timestamp}get attributes(){return this.state.attributes}get type(){return this.state.type}get attachedMedia(){return this.getMediaByCategories(["media"])}get participantSid(){return this.state.participantSid}get aggregatedDeliveryReceipt(){return this.state.aggregatedDeliveryReceipt}getMediaByCategories(e){return(this.state.medias??[]).filter((t=>e.includes(t.category)))}getEmailBody(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text/plain";return this.getMediaByCategories(["body"])?.filter((t=>t.contentType==e)).shift()??null}getEmailHistory(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text/plain";return this.getMediaByCategories(["history"])?.filter((t=>t.contentType==e)).shift()??null}_update(e){const t=[];!e.text&&"string"!=typeof e.text||e.text===this.state.body||(this.state.body=e.text,t.push("body")),e.subject&&e.subject!==this.state.subject&&(this.state.subject=e.subject,t.push("subject")),e.lastUpdatedBy&&e.lastUpdatedBy!==this.state.lastUpdatedBy&&(this.state.lastUpdatedBy=e.lastUpdatedBy,t.push("lastUpdatedBy")),e.author&&e.author!==this.state.author&&(this.state.author=e.author,t.push("author")),e.dateUpdated&&new Date(e.dateUpdated).getTime()!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=new Date(e.dateUpdated),t.push("dateUpdated")),e.timestamp&&new Date(e.timestamp).getTime()!==(this.state.timestamp&&this.state.timestamp.getTime())&&(this.state.timestamp=new Date(e.timestamp),t.push("dateCreated"));const n=C(e.attributes,`Got malformed attributes for the message ${this.sid}`,qi);de(this.state.attributes,n)||(this.state.attributes=n,t.push("attributes"));const i=e.delivery,r=this.state.aggregatedDeliveryReceipt;!!(i&&i.total&&i.delivered&&i.failed&&i.read&&i.sent&&i.undelivered)&&(r?r._isEquals(i)||(r._update(i),t.push("deliveryReceipt")):(this.state.aggregatedDeliveryReceipt=new AggregatedDeliveryReceipt(i),t.push("deliveryReceipt"))),t.length>0&&this.emit("updated",{message:this,updateReasons:t})}async getParticipant(){let e=null;if(this.state.participantSid&&(e=await this.conversation.getParticipantBySid(this.state.participantSid).catch((()=>(qi.debug(`Participant with sid "${this.participantSid}" not found for message ${this.sid}`),null)))),!e&&this.state.author&&(e=await this.conversation.getParticipantByIdentity(this.state.author).catch((()=>(qi.debug(`Participant with identity "${this.author}" not found for message ${this.sid}`),null)))),e)return e;let t="Participant with ";throw this.state.participantSid&&(t+="SID '"+this.state.participantSid+"' "),this.state.author&&(this.state.participantSid&&(t+="or "),t+="identity '"+this.state.author+"' "),"Participant with "===t&&(t="Participant "),t+="was not found",new Error(t)}async getDetailedDeliveryReceipts(){let e=await this._getDetailedDeliveryReceiptsPaginator(),t=e.items;for(;e.hasNextPage;)e=await e.nextPage(),t=[...t,...e.items];return t}async remove(){return await this.services.commandExecutor.mutateResource("delete",this.links.self),this}async updateBody(e){return await this.services.commandExecutor.mutateResource("post",this.links.self,{body:e}),this}async updateAttributes(e){return await this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:void 0!==e?JSON.stringify(e):void 0}),this}getTemporaryContentUrlsForMedia(e){const t=e.map((e=>e.sid));return this.getTemporaryContentUrlsForMediaSids(t)}getTemporaryContentUrlsForMediaSids(e){return new Oi.CancellablePromise((async(t,n,i)=>{const r=this.services.mcsClient.mediaSetGetContentUrls(e??[]);if(this.services.mcsClient&&e){i((()=>{r.cancel()}));try{t(await r)}catch(e){n(e)}}else n(new Error("Media Content Service is unavailable"))}))}getTemporaryContentUrlsForAttachedMedia(){const e=this.attachedMedia,t=e?.map((e=>e.sid))??[];return this.getTemporaryContentUrlsForMediaSids(t)}async _getDetailedDeliveryReceiptsPaginator(e){const t=this.configuration.links.messagesReceipts.replace("%s",this.conversation.sid).replace("%s",this.sid),n=new R(t).arg("PageToken",e?.pageToken).arg("PageSize",e?.pageSize).build(),i=await this.services.network.get(n);return new Ni(i.body.delivery_receipts.map((e=>new DetailedDeliveryReceipt(e))),((e,t)=>this._getDetailedDeliveryReceiptsPaginator({pageToken:e,pageSize:t})),i.body.meta.previous_token,i.body.meta.next_token)}getContentData(){return new Oi.CancellablePromise((async(e,t,n)=>{if(null===this.state.contentSid)return void e(null);const i=this.getMediaByCategories(["body"]);if(null===i)return void e(null);const r="application/x-vnd.com.twilio.rich.",s=i.filter((e=>e.contentType.startsWith(r)));if(0===s.length)return void e(null);const a=s[0],o=a.getContentTemporaryUrl();let c;n((()=>{o.cancel()}));try{c=await o}catch(e){return void t(e)}if(null===c)return void e(null);const u=new Promise(((e,t)=>{let i=!1;const r=new Di;r.open("GET",c??"",!0),r.responseType="text",r.onreadystatechange=()=>{4!==r.readyState||i||e(r.responseText)},r.onerror=()=>{t(r.statusText)},n((()=>{i=!0,r.abort(),t(new Error("XHR has been aborted"))})),r.send()}));let l;try{const e=await u;l=JSON.parse(e)}catch(e){return void t(e)}const d=a.contentType.replace(r,"").replace(".","/");e(Li(d,l.data))}))}async getChannelMetadata(){return this.state.hasChannelMetadata?await this.services.channelMetadataClient.getChannelMetadata(this.conversation.sid,this.sid):null}}n([Q([K,"undefined"]),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Media)],Message.prototype,"getEmailBody",null),n([Q([K,"undefined"]),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Media)],Message.prototype,"getEmailHistory",null),n([X("string"),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],Message.prototype,"updateBody",null),n([X(Z),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],Message.prototype,"updateAttributes",null),n([X(W("media",Media)),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Oi.CancellablePromise)],Message.prototype,"getTemporaryContentUrlsForMedia",null),n([X(W("strings","string")),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Oi.CancellablePromise)],Message.prototype,"getTemporaryContentUrlsForMediaSids",null);const Bi=h.scope("Messages");class zi extends ue{conversation;configuration;services;messagesByIndex;messagesListPromise;constructor(e,t,n){super(),this.conversation=e,this.configuration=t,this.services=n,this.messagesByIndex=new Map,this.messagesListPromise=null}async subscribe(e){if(this.messagesListPromise)return this.messagesListPromise;this.messagesListPromise="string"==typeof e?this.services.syncClient.list({id:e,mode:"open_existing"}):Promise.resolve(e);try{const e=await this.messagesListPromise;return e.on("itemAdded",(e=>{Bi.debug(`${this.conversation.sid} itemAdded: ${e.item.index}`),this._upsertMessage(e.item.index,e.item.data)})),e.on("itemRemoved",(e=>{Bi.debug(`#{this.conversation.sid} itemRemoved: ${e.index}`);const t=e.index;if(this.messagesByIndex.has(t)){const e=this.messagesByIndex.get(t);if(!e)return;this.messagesByIndex.delete(e.index),e.removeAllListeners("updated"),this.emit("messageRemoved",e)}})),e.on("itemUpdated",(e=>{Bi.debug(`${this.conversation.sid} itemUpdated: ${e.item.index}`);const t=this.messagesByIndex.get(e.item.index);t&&t._update(e.item.data)})),e}catch(e){throw this.messagesListPromise=null,"disconnected"!==this.services.syncClient.connectionState&&Bi.error("Failed to get messages object for conversation",this.conversation.sid,e),Bi.debug("ERROR: Failed to get messages object for conversation",this.conversation.sid,e),e}}async unsubscribe(){if(!this.messagesListPromise)return;(await this.messagesListPromise).close(),this.messagesListPromise=null}sendV2(e){return Bi.debug("Sending message V2",e.mediaContent,e.attributes,e.emailOptions),new Oi.CancellablePromise((async(t,n,i)=>{const r=[],s=[];i((()=>{s.forEach((e=>e.cancel()))}));for(const[t,i]of e.mediaContent)try{Bi.debug("Adding media to a message as "+(i instanceof FormData?"FormData":"SendMediaOptions"),i);const e=i instanceof FormData?this.services.mcsClient.postFormData(i,t):this.services.mcsClient.post(i.contentType??"",i.media??"",t,i.filename);s.push(e),r.push(await e)}catch(e){return void n(e)}const a=this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{body:e.text,subject:e.emailOptions?.subject,media_sids:r.map((e=>e.sid)),attributes:void 0!==e.attributes?JSON.stringify(e.attributes):void 0,content_sid:e.contentSid,content_variables:void 0!==e.contentVariables?JSON.stringify(e.contentVariables.reduce(((e,t)=>({...e,[t.name]:t.value})),{})):void 0});try{t(await a)}catch(e){n(e)}}))}async send(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0;return Bi.debug("Sending text message",e,t,n),this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{body:e??"",attributes:void 0!==t?JSON.stringify(t):void 0,subject:n?.subject})}async sendMedia(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0;Bi.debug("Sending media message",e,t,n),Bi.debug("Sending media message as "+(e instanceof FormData?"FormData":"SendMediaOptions"),e,t);const i=e instanceof FormData?await this.services.mcsClient.postFormData(e):await this.services.mcsClient.post(e.contentType??"",e.media??"","media",e.filename);return await this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{media_sids:[i.sid],attributes:void 0!==t?JSON.stringify(t):void 0})}async getMessages(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"backwards";return this._getMessages(e,t,n)}_wrapPaginator(e,t,n){const i="desc"===e,r=()=>t.nextPage().then((t=>this._wrapPaginator(e,t,n))),s=()=>t.prevPage().then((t=>this._wrapPaginator(e,t,n)));return n(t.items).then((e=>({items:e.sort(((e,t)=>e.index-t.index)),hasPrevPage:i?t.hasNextPage:t.hasPrevPage,hasNextPage:i?t.hasPrevPage:t.hasNextPage,prevPage:i?r:s,nextPage:i?s:r})))}_upsertMessage(e,t){const n=this.messagesByIndex.get(e);if(n)return Bi.debug("Attempted to upsert a message, but it is already known and therefore ignored",this.conversation.sid),n;const i={self:`${this.conversation._links.messages}/${t.sid}`,conversation:this.conversation._links.self,messages_receipts:`${this.conversation._links.messages}/${t.sid}/Receipts`},r=new Message(e,t,this.conversation,i,this.configuration,this.services);return this.messagesByIndex.set(r.index,r),r.on("updated",(e=>this.emit("messageUpdated",e))),this.emit("messageAdded",r),r}async _getMessages(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:30,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"end";const n="backwards"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"forward")?"desc":"asc",i=await this.messagesListPromise,r=await(i?.getItems({from:"end"!==t?t:void 0,pageSize:e,order:n,limit:e}));return await this._wrapPaginator(n,r,(e=>Promise.all(e.map((e=>this._upsertMessage(e.index,e.data))))))}}class Wi{messagesEntity;text;attributes={};mediaContent=[];emailOptions={};contentSid;contentVariables;constructor(e){this.messagesEntity=e}send(){return new Oi.CancellablePromise((async(e,t,n)=>{const i=this.messagesEntity.sendV2(this);n((()=>i.cancel()));try{e(T((await i).index))}catch(e){t(e)}}))}}class Ki{limits;message;emailBodies;emailHistories;constructor(e,t){this.limits=e,this.message=new Wi(t),this.emailBodies=new Map,this.emailHistories=new Map}setBody(e){return this.message.text=e,this}setSubject(e){return this.message.emailOptions.subject=e,this}setAttributes(e){return this.message.attributes=e,this}setEmailBody(e,t){return this.emailBodies.set(e,t),this}setEmailHistory(e,t){return this.emailHistories.set(e,t),this}setContentTemplate(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return this.message.contentSid=e,this.message.contentVariables=t,this}addMedia(e){if("undefined"==typeof FormData&&e instanceof FormData)throw new Error("Could not add FormData content whilst not in a browser");if(!(e instanceof FormData)){const t=e;if(!t.contentType||!t.media)throw new Error("Media content in SendMediaOptions must contain non-empty contentType and media")}return this.message.mediaContent.push(["media",e]),this}build(){if(this.emailBodies.forEach(((e,t)=>{if(!this.limits.emailBodiesAllowedContentTypes.includes(t))throw new Error(`Unsupported email body content type ${t}`)})),this.emailHistories.forEach(((e,t)=>{if(!this.limits.emailHistoriesAllowedContentTypes.includes(t))throw new Error(`Unsupported email history content type ${t}`)})),this.emailBodies.size>this.limits.emailBodiesAllowedContentTypes.length)throw new Error(`Too many email bodies attached to the message (${this.emailBodies.size} > ${this.limits.emailBodiesAllowedContentTypes.length})`);if(this.emailHistories.size>this.limits.emailHistoriesAllowedContentTypes.length)throw new Error(`Too many email histories attached to the message (${this.emailHistories.size} > ${this.limits.emailHistoriesAllowedContentTypes.length})`);if(this.message.mediaContent.length>this.limits.mediaAttachmentsCountLimit)throw new Error(`Too many media attachments in the message (${this.message.mediaContent.length} > ${this.limits.mediaAttachmentsCountLimit})`);return this.emailBodies.forEach((e=>{this.message.mediaContent.push(["body",e])})),this.emailHistories.forEach((e=>{this.message.mediaContent.push(["history",e])})),this.message}buildAndSend(){return this.build().send()}}n([Q("string"),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Ki)],Ki.prototype,"setBody",null),n([Q("string"),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Ki)],Ki.prototype,"setSubject",null),n([Q(Z),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Ki)],Ki.prototype,"setAttributes",null),n([Q("string",[FormData,ee]),i("design:type",Function),i("design:paramtypes",[String,Object]),i("design:returntype",Ki)],Ki.prototype,"setEmailBody",null),n([Q("string",[FormData,ee]),i("design:type",Function),i("design:paramtypes",[String,Object]),i("design:returntype",Ki)],Ki.prototype,"setEmailHistory",null),n([Q("string",[D("content variables",ContentTemplateVariable),"undefined"]),i("design:type",Function),i("design:paramtypes",[String,Array]),i("design:returntype",Ki)],Ki.prototype,"setContentTemplate",null),n([Q([FormData,ee]),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Ki)],Ki.prototype,"addMedia",null);const Hi={lastMessage:"lastMessage",attributes:"attributes",createdBy:"createdBy",dateCreated:"dateCreated",dateUpdated:"dateUpdated",friendlyName:"friendlyName",lastConsumedMessageIndex:"lastConsumedMessageIndex",notificationLevel:"notificationLevel",sid:"sid",status:"status",uniqueName:"uniqueName",state:"state",bindings:"bindings"};class Conversation extends ue{static participantJoined="participantJoined";static participantLeft="participantLeft";static participantUpdated="participantUpdated";static messageAdded="messageAdded";static messageRemoved="messageRemoved";static messageUpdated="messageUpdated";static typingEnded="typingEnded";static typingStarted="typingStarted";static updated="updated";static removed="removed";static _logger=h.scope("Conversation");sid;_links;_participants;_configuration;_services;_internalState;_entityName;_messagesEntity;_messagesList;_participantsEntity;_participantsMap;_dataSource;_entityPromise;_entity;constructor(e,t,n,i,r){super(),this.sid=t,this._links=n,this._configuration=i,this._services=r,this._entityName=e.channel,this._internalState={uniqueName:e.uniqueName||null,status:"notParticipating",attributes:e.attributes??{},createdBy:e.createdBy,dateCreated:I(e.dateCreated),dateUpdated:I(e.dateUpdated),friendlyName:e.friendlyName||null,lastReadMessageIndex:Number.isInteger(e.lastConsumedMessageIndex)?e.lastConsumedMessageIndex:null,bindings:e.bindings??{}},e.notificationLevel&&(this._internalState.notificationLevel=e.notificationLevel);const s={participants:this._links.participants};this._participants=new Map,this._participantsEntity=new $i(this,this._participants,s,this._configuration,this._services),this._participantsEntity.on("participantJoined",(e=>this.emit("participantJoined",e))),this._participantsEntity.on("participantLeft",(e=>this.emit("participantLeft",e))),this._participantsEntity.on("participantUpdated",(e=>this.emit("participantUpdated",e))),this._messagesEntity=new zi(this,i,r),this._messagesEntity.on("messageAdded",(e=>this._onMessageAdded(e))),this._messagesEntity.on("messageUpdated",(e=>this.emit("messageUpdated",e))),this._messagesEntity.on("messageRemoved",(e=>this.emit("messageRemoved",e)))}get uniqueName(){return this._internalState.uniqueName}get status(){return this._internalState.status}get friendlyName(){return this._internalState.friendlyName}get dateUpdated(){return this._internalState.dateUpdated}get dateCreated(){return this._internalState.dateCreated}get createdBy(){return this._internalState.createdBy??""}get attributes(){return this._internalState.attributes}get lastReadMessageIndex(){return this._internalState.lastReadMessageIndex}get lastMessage(){return this._internalState.lastMessage??void 0}get notificationLevel(){return this._internalState.notificationLevel??"default"}get bindings(){return this._internalState.bindings}get limits(){return this._configuration.limits}get state(){return this._internalState.state}get _statusSource(){return this._dataSource}static preprocessUpdate(e,t){try{"string"==typeof e.attributes?e.attributes=JSON.parse(e.attributes):e.attributes&&JSON.stringify(e.attributes)}catch(n){Conversation._logger.warn("Retrieved malformed attributes from the server for conversation: "+t),e.attributes={}}try{e.dateCreated&&(e.dateCreated=new Date(e.dateCreated))}catch(n){Conversation._logger.warn("Retrieved malformed dateCreated from the server for conversation: "+t),delete e.dateCreated}try{e.dateUpdated&&(e.dateUpdated=new Date(e.dateUpdated))}catch(n){Conversation._logger.warn("Retrieved malformed dateUpdated from the server for conversation: "+t),delete e.dateUpdated}try{e.lastMessage&&e.lastMessage.timestamp&&(e.lastMessage.timestamp=new Date(e.lastMessage.timestamp))}catch(n){Conversation._logger.warn("Retrieved malformed lastMessage.timestamp from the server for conversation: "+t),delete e.lastMessage.timestamp}}async add(e,t){return this._participantsEntity.add(e,t??{})}async addNonChatParticipant(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return this._participantsEntity.addNonChatParticipant(e,t,n??{},i??{})}async advanceLastReadMessageIndex(e){return await this._subscribeStreams(),e<(this.lastReadMessageIndex??0)?await this._setLastReadMessageIndex(this.lastReadMessageIndex):await this._setLastReadMessageIndex(e)}async delete(){return await this._services.commandExecutor.mutateResource("delete",this._links.self),this}async getAttributes(){return await this._subscribe(),this.attributes}async getMessages(e,t,n){return await this._subscribeStreams(),this._messagesEntity.getMessages(e,t,n)}async getParticipants(){return await this._subscribeStreams(),this._participantsEntity.getParticipants()}async getParticipantsCount(){const e=new R(this._configuration.links.conversations).path(this.sid).build();return(await this._services.network.get(e)).body.participants_count??0}async getParticipantBySid(e){return this._participantsEntity.getParticipantBySid(e)}async getParticipantByIdentity(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return this._participantsEntity.getParticipantByIdentity(e??"")}async getMessagesCount(){const e=new R(this._configuration.links.conversations).path(this.sid).build();return(await this._services.network.get(e)).body.messages_count??0}async getUnreadMessagesCount(){const e=new R(this._configuration.links.myConversations).path(this.sid).build(),t=await this._services.network.get(e);if(t.body.conversation_sid!==this.sid)throw new Error("Conversation was not found in the user conversations list");const n=t.body.unread_messages_count;return"number"==typeof n?n:null}async join(){return await this._services.commandExecutor.mutateResource("post",this._links.participants,{identity:this._configuration.userIdentity}),this}async leave(){return"joined"===this._internalState.status&&await this._services.commandExecutor.mutateResource("delete",`${this._links.participants}/${encodeURIComponent(this._configuration.userIdentity)}`),this}async removeParticipant(e){await this._participantsEntity.remove("string"==typeof e?e:e.sid)}async sendMessage(e,t,n){const i="string"==typeof e||null===e?await this._messagesEntity.send(e,t,n):await this._messagesEntity.sendMedia(e,t,n),r="string"==typeof e||null===e?"text":"media";let s;try{s=JSON.parse(i.attributes)}catch(e){}const a={sid:i.sid,text:i.body,type:r,author:i.author,subject:i.subject,contentSid:i.content_sid,lastUpdatedBy:i.participant_sid,attributes:s,dateUpdated:i.date_updated,timestamp:i.date_created,memberSid:i.participant_sid,medias:Array.isArray(i.media)?i.media.map((e=>({sid:e.sid,size:Number(e.size),category:e.category,filename:e.filename,contentType:e.content_type}))):null,media:i.media&&"object"==typeof i.media&&!Array.isArray(i.media)?{sid:i.media.sid,size:Number(i.media.size),category:i.media.category,filename:i.media.filename,contentType:i.media.content_type}:null,hasChannelMetadata:!1};return this._messagesEntity._upsertMessage(i.index,a)}prepareMessage(){return new Ki(this.limits,this._messagesEntity)}async setAllMessagesRead(){await this._subscribeStreams();const e=await this.getMessages(1);return e.items.length>0?this.advanceLastReadMessageIndex(e.items[0].index):0}async setAllMessagesUnread(){return await this._subscribeStreams(),await this._setLastReadMessageIndex(null)}async setUserNotificationLevel(e){await this._services.commandExecutor.mutateResource("post",`${this._configuration.links.myConversations}/${this.sid}`,{notification_level:e})}typing(){return this._services.typingIndicator.send(this.sid)}async updateAttributes(e){return await this._services.commandExecutor.mutateResource("post",this._links.self,{attributes:void 0!==e?JSON.stringify(e):void 0}),this}async updateFriendlyName(e){return this._internalState.friendlyName!==e&&await this._services.commandExecutor.mutateResource("post",this._links.self,{friendly_name:e}),this}async updateLastReadMessageIndex(e){return await this._subscribeStreams(),this._setLastReadMessageIndex(e)}async updateUniqueName(e){return this._internalState.uniqueName!==e&&(e||="",await this._services.commandExecutor.mutateResource("post",this._links.self,{unique_name:e})),this}async _subscribe(){if(this._entityPromise)return this._entityPromise;this._entityPromise=this._services.syncClient.document({id:this._entityName,mode:"open_existing"});try{return this._entity=await this._entityPromise,this._entity.on("updated",(e=>this._update(e.data))),this._entity.on("removed",(()=>this.emit("removed",this))),this._update(this._entity.data),this._entity}catch(e){throw this._entity=null,this._entityPromise=null,"disconnected"!=this._services.syncClient.connectionState&&Conversation._logger.error("Failed to get conversation object",e),Conversation._logger.debug("ERROR: Failed to get conversation object",e),e}}async _fetchStreams(){await this._subscribe(),Conversation._logger.trace("_streamsAvailable, this.entity.data=",this._entity?.data);const e=this._entity?.data;this._messagesList=await this._services.syncClient.list({id:e.messages,mode:"open_existing"}),this._participantsMap=await this._services.syncClient.map({id:e.roster,mode:"open_existing"})}async _subscribeStreams(){try{await this._subscribe(),Conversation._logger.trace("_subscribeStreams, this.entity.data=",this._entity?.data);const e=this._entity?.data,t=e.messages,n=e.roster;await Promise.all([this._messagesEntity.subscribe(this._messagesList??t),this._participantsEntity.subscribe(this._participantsMap??n)])}catch(e){throw"disconnected"!==this._services.syncClient.connectionState&&Conversation._logger.error("Failed to subscribe on conversation objects",this.sid,e),Conversation._logger.debug("ERROR: Failed to subscribe on conversation objects",this.sid,e),e}}async _unsubscribe(){return this._entity&&(await this._entity.close(),this._entity=null,this._entityPromise=null),Promise.all([this._participantsEntity.unsubscribe(),this._messagesEntity.unsubscribe()])}_setStatus(e,t){this._dataSource=t,this._internalState.status!==e&&(this._internalState.status=e,"joined"!==e?this._entityPromise&&this._unsubscribe().catch((t=>{if(Conversation._logger.debug("ERROR while setting conversation status "+e,t),"disconnected"!==this._services.syncClient.connectionState)throw t})):this._subscribeStreams().catch((t=>{if(Conversation._logger.debug("ERROR while setting conversation status "+e,t),"disconnected"!==this._services.syncClient.connectionState)throw t})))}_update(e){Conversation._logger.trace("_update",e),Conversation.preprocessUpdate(e,this.sid);const t=new Set;for(const n of Object.keys(e)){const i=Hi[n];if(i)switch(i){case Hi.status:if(!e.status||"unknown"===e.status||this._internalState.status===e.status)break;this._internalState.status=e.status,t.add(i);break;case Hi.attributes:if(de(this._internalState.attributes,e.attributes))break;this._internalState.attributes=e.attributes,t.add(i);break;case Hi.lastConsumedMessageIndex:if(void 0===e.lastConsumedMessageIndex||e.lastConsumedMessageIndex===this._internalState.lastReadMessageIndex)break;this._internalState.lastReadMessageIndex=e.lastConsumedMessageIndex,t.add("lastReadMessageIndex");break;case Hi.lastMessage:if(this._internalState.lastMessage&&!e.lastMessage){delete this._internalState.lastMessage,t.add(i);break}this._internalState.lastMessage=this._internalState.lastMessage||{},void 0!==e.lastMessage?.index&&e.lastMessage.index!==this._internalState.lastMessage.index&&(this._internalState.lastMessage.index=e.lastMessage.index,t.add(i)),void 0!==e.lastMessage?.timestamp&&this._internalState.lastMessage?.dateCreated?.getTime()!==e.lastMessage.timestamp.getTime()&&(this._internalState.lastMessage.dateCreated=e.lastMessage.timestamp,t.add(i)),de(this._internalState.lastMessage,{})&&delete this._internalState.lastMessage;break;case Hi.state:const r=e.state||void 0;if(void 0!==r&&(r.dateUpdated=new Date(r.dateUpdated)),de(this._internalState.state,r))break;this._internalState.state=r,t.add(i);break;case Hi.bindings:if(de(this._internalState.bindings,e.bindings))break;this._internalState.bindings=e.bindings,t.add(i);break;default:const s=e[n]instanceof Date,a=s&&this._internalState[i]?.getTime()===e[n].getTime(),o=!s&&this[i]===e[n];if(a||o)break;this._internalState[i]=e[n],t.add(i)}}t.size>0&&this.emit("updated",{conversation:this,updateReasons:[...t]})}_onMessageAdded(e){for(const t of this._participants.values())if(t.identity===e.author){t._endTyping();break}this.emit("messageAdded",e)}async _setLastReadMessageIndex(e){return(await this._services.commandExecutor.mutateResource("post",`${this._configuration.links.myConversations}/${this.sid}`,{last_read_message_index:e})).unread_messages_count}}n([X(K,Y),i("design:type",Function),i("design:paramtypes",[String,Object]),i("design:returntype",Promise)],Conversation.prototype,"add",null),n([X(K,K,Y),i("design:type",Function),i("design:paramtypes",[String,String,Object,Object]),i("design:returntype",Promise)],Conversation.prototype,"addNonChatParticipant",null),n([X(H),i("design:type",Function),i("design:paramtypes",[Number]),i("design:returntype",Promise)],Conversation.prototype,"advanceLastReadMessageIndex",null),n([X(["undefined",H],["undefined",H],["undefined",z("backwards","forward")]),i("design:type",Function),i("design:paramtypes",[Number,Number,String]),i("design:returntype",Promise)],Conversation.prototype,"getMessages",null),n([X(K),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],Conversation.prototype,"getParticipantBySid",null),n([X(K),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],Conversation.prototype,"getParticipantByIdentity",null),n([X([K,Participant]),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],Conversation.prototype,"removeParticipant",null),n([X(["string",FormData,z(null),V("media options",{contentType:K,media:B((e=>{let t="string"==typeof e&&e.length>0||e instanceof Uint8Array||e instanceof ArrayBuffer;return"function"==typeof Blob&&(t=t||e instanceof Blob),[t,"a non-empty string, an instance of Buffer or an instance of Blob"]}))})],Y,["undefined",z(null),V("email attributes",{subject:[K,"undefined"]})]),i("design:type",Function),i("design:paramtypes",[Object,Object,Object]),i("design:returntype",Promise)],Conversation.prototype,"sendMessage",null),n([X(z("default","muted")),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],Conversation.prototype,"setUserNotificationLevel",null),n([X(Z),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],Conversation.prototype,"updateAttributes",null),n([X("string"),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],Conversation.prototype,"updateFriendlyName",null),n([X([z(null),H]),i("design:type",Function),i("design:paramtypes",[Number]),i("design:returntype",Promise)],Conversation.prototype,"updateLastReadMessageIndex",null),n([X(["string",z(null)]),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],Conversation.prototype,"updateUniqueName",null);class Vi{_promise;_resolve;_reject;current;constructor(){this._promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}get promise(){return this._promise}update(e){this._resolve(e)}set(e){this.current=e,this._resolve(e)}fail(e){this._reject(e)}}const Ji=h.scope("Conversations");class Gi extends ue{conversations=new Map;myConversationsRead=new Vi;configuration;services;tombstones=new Set;myConversationsFetched=!1;constructor(e,t){super(),this.configuration=e,this.services=t}async addConversation(e){const t=void 0!==e?.attributes?e.attributes:{},n=await this.services.commandExecutor.mutateResource("post",this.configuration.links.conversations,{friendly_name:e.friendlyName,unique_name:e.uniqueName,attributes:void 0!==t?JSON.stringify(t):void 0}),i=n.sid??null,r=n.sync_objects?.conversation??null,s={self:n.url,...n.links},a=this.conversations.get(i);if(a)return await a._subscribe(),a;const o=new Conversation({channel:r,entityName:"",uniqueName:"",attributes:null,createdBy:"",friendlyName:"",lastConsumedMessageIndex:0,dateCreated:null,dateUpdated:null},i,s,this.configuration,this.services);return this.conversations.set(o.sid,o),this._registerForEvents(o),await o._subscribe(),this.emit("conversationAdded",o),o}async fetchConversations(){try{const e=await this._getMap();e.on("itemAdded",(e=>{Ji.debug(`itemAdded: ${e.item.key}`),this._upsertConversation("sync",e.item.key,e.item.data)})),e.on("itemRemoved",(e=>{Ji.debug(`itemRemoved: ${e.key}`);const t=e.key;this.myConversationsFetched||this.tombstones.add(t);const n=this.conversations.get(t);n&&("joined"===n.status&&(n._setStatus("notParticipating","sync"),this.emit("conversationLeft",n)),this.conversations.delete(t),this.emit("conversationRemoved",n),n.emit("removed",n))})),e.on("itemUpdated",(e=>{Ji.debug(`itemUpdated: ${e.item.key}`),this._upsertConversation("sync",e.item.key,e.item.data)}));const t=await this._fetchMyConversations(),n=[];for(const e of t)n.push(this._upsertConversation("rest",e.channel_sid,e));return this.myConversationsRead.set(!0),await Promise.all(n),this.myConversationsFetched=!0,this.tombstones.clear(),Ji.debug("The conversations list has been successfully fetched"),this}catch(e){const t="Failed to fetch the conversations list";throw"disconnected"!==this.services.syncClient.connectionState&&Ji.error(t,e),Ji.debug(`ERROR: ${t}`,e),e}}async getConversations(){const e=await this._getMap(),t=await e.getItems();return this._wrapPaginator(t,(e=>Promise.all(e.map((e=>this._upsertConversation("sync",e.key,e.data))))))}async getConversation(e){const t=await this._getMap(),n=(await t.getItems({key:e})).items.map((e=>this._upsertConversation("sync",e.key,e.data)));return n.length>0?n[0]:null}async getConversationByUniqueName(e){const t=new R(this.configuration.links.myConversations).path(e).build(),n=(await this.services.network.get(t)).body,i=n.conversation_sid,r={entityName:null,lastConsumedMessageIndex:n.last_read_message_index,status:n?.status||"unknown",friendlyName:n.friendly_name,dateUpdated:n.date_updated,dateCreated:n.date_created,uniqueName:n.unique_name,createdBy:n.created_by,attributes:n.attributes,channel:n.sync_objects.conversation,notificationLevel:n?.notification_level,sid:i};return i?this._upsertConversation("sync",i,r):null}async peekConversation(e){const t=new R(this.configuration.links.conversations).path(e).build(),n=(await this.services.network.get(t)).body,i={entityName:null,status:n?.status||"unknown",friendlyName:n.friendly_name,dateUpdated:n.date_updated,dateCreated:n.date_created,uniqueName:n.unique_name,createdBy:n.created_by,attributes:n.attributes,channel:`${e}.channel`,sid:e};return this._upsertConversation("sync",e,i)}async _getMap(){return await this.services.syncClient.map({id:this.configuration.myConversations,mode:"open_existing"})}async _wrapPaginator(e,t){return{items:(await t(e.items)).filter((e=>null!==e)),hasNextPage:e.hasNextPage,hasPrevPage:e.hasPrevPage,nextPage:()=>e.nextPage().then((e=>this._wrapPaginator(e,t))),prevPage:()=>e.prevPage().then((e=>this._wrapPaginator(e,t)))}}async _updateConversation(e,t,n){const i=void 0!==t._statusSource&&e!==t._statusSource,r="rest"!==e||"sync"===t._statusSource;if(i&&r&&"sync"!==e)Ji.trace("upsertConversation: conversation is known from sync and came from REST, ignoring",{sid:t.sid,data:n.status,conversation:t.status});else{if("joined"===n.status&&"joined"!==t.status){t._setStatus("joined",e);const i={};return void 0!==n.notificationLevel&&(i.notificationLevel=n.notificationLevel),void 0!==n.lastConsumedMessageIndex&&(i.lastConsumedMessageIndex=n.lastConsumedMessageIndex),de(i,{})||t._update(i),await t._subscribe(),void this.emit("conversationJoined",t)}if("notParticipating"===n.status&&"joined"===t.status)return t._setStatus("notParticipating",e),t._update(n),await t._subscribe(),void this.emit("conversationLeft",t);"notParticipating"!==n.status?t._update(n):await t._subscribe()}}async _upsertConversation(e,t,n){Ji.trace(`upsertConversation called for ${t}`,n);const i=this.conversations.get(t);if(i){Ji.trace(`upsertConversation: the conversation ${i.sid} is known;its status is known from the source ${i._statusSource} and the update came from the source ${e}`,i);try{await this._updateConversation(e,i,n),await i._subscribe()}catch(e){if("SyncError"!==e.name)throw e;return Ji.trace("upsertChannel: the conversation is missing some Sync entity(ies), ignoring",t,e),this.conversations.delete(t),null}return i}if("rest"===e&&this.tombstones.has(t))return Ji.trace("upsertChannel: the conversation is deleted but reappeared again from REST, ignoring",t),null;Ji.trace("upsertConversation: creating a local conversation object with sid "+t,n);const r=`${this.configuration.links.conversations}/${t}`,s=new Conversation(n,t,{self:r,messages:`${r}/Messages`,participants:`${r}/Participants`},this.configuration,this.services);this.conversations.set(t,s);try{await s._subscribe(),"joined"===n.status&&await s._fetchStreams()}catch(e){if("SyncError"!==e.name)throw e;return Ji.trace("upsertChannel: the conversation is missing some Sync entity(ies), ignoring",t,e),this.conversations.delete(t),null}return this._registerForEvents(s),this.emit("conversationAdded",s),"joined"===n.status&&(s._setStatus("joined",e),this.emit("conversationJoined",s)),s}async _fetchMyConversations(){let e=[],t=null;do{const n=new R(this.configuration.links.myConversations);t&&n.arg("PageToken",t);const i=await this.services.network.get(n.build()),r=i.body?.conversations.map((e=>({descriptor:e,channel_sid:e.conversation_sid,status:e.status,channel:e.sync_objects.conversation,messages:e.sync_objects.messages,roster:`${e.conversation_sid}.roster`,lastConsumedMessageIndex:e.last_read_message_index,notificationLevel:e.notification_level})));t=i.body.meta.next_token,e=[...e,...r]}while(t);return e}_onConversationRemoved(e){const t=this.conversations.get(e);t&&(this.conversations.delete(e),this.emit("conversationRemoved",t))}_registerForEvents(e){e.on("removed",(()=>this._onConversationRemoved(e.sid))),e.on("updated",(e=>this.emit("conversationUpdated",e))),e.on("participantJoined",(e=>this.emit("participantJoined",e))),e.on("participantLeft",(e=>this.emit("participantLeft",e))),e.on("participantUpdated",(e=>this.emit("participantUpdated",e))),e.on("messageAdded",(e=>this.emit("messageAdded",e))),e.on("messageUpdated",(e=>this.emit("messageUpdated",e))),e.on("messageRemoved",(e=>this.emit("messageRemoved",e))),e.on("typingStarted",(e=>this.emit("typingStarted",e))),e.on("typingEnded",(e=>this.emit("typingEnded",e)))}}class Qi extends ue{configuration;services;subscribedUsers;fifoStack;myself;constructor(e,t,n){super(),this.configuration=t,this.services=n,this.fifoStack=[],this.myself=e,this.myself.on("updated",(e=>this.emit("userUpdated",e))),this.myself.on("userSubscribed",(()=>this.emit("userSubscribed",this.myself))),this.myself.on("userUnsubscribed",(()=>{this.emit("userUnsubscribed",this.myself),this.myself._ensureFetched()})),this.subscribedUsers=new Map}handleUnsubscribeUser(e){this.subscribedUsers.has(e.identity)&&this.subscribedUsers.delete(e.identity);let t=0;this.fifoStack.find(((n,i)=>n==e.identity&&(t=i,!0)))&&this.fifoStack.splice(t,1),this.emit("userUnsubscribed",e)}handleSubscribeUser(e){if(!this.subscribedUsers.has(e.identity)){if(this.fifoStack.length>=this.configuration.userInfosToSubscribe){const e=this.fifoStack.shift();this.subscribedUsers?.get(e)?.unsubscribe()}this.fifoStack.push(e.identity),this.subscribedUsers.set(e.identity,e),this.emit("userSubscribed",e)}}async getUser(e,t){if(await this.myself._ensureFetched(),e==this.myself.identity)return this.myself;const n=this.subscribedUsers.get(e);if(n)return n;t??=await this.getSyncUniqueName(e);const i=new User(e,t,this.configuration,this.services);return i.on("updated",(e=>this.emit("userUpdated",e))),i.on("userSubscribed",(()=>this.handleSubscribeUser(i))),i.on("userUnsubscribed",(()=>this.handleUnsubscribeUser(i))),await i._ensureFetched(),i}async getSubscribedUsers(){await this.myself._ensureFetched();const e=[this.myself];return this.subscribedUsers.forEach((t=>e.push(t))),e}async getSyncUniqueName(e){const t=new R(this.configuration.links.users).path(e).build();return(await this.services.network.get(t)).body.sync_objects.user_info_map??""}}const Xi=h.scope("TypingIndicator");class Zi{services;configuration;sentUpdates;getConversation;serviceTypingTimeout;constructor(e,t,n){this.configuration=t,this.services=n,this.getConversation=e,this.serviceTypingTimeout=null,this.sentUpdates=new Map}get typingTimeout(){return this.configuration.typingIndicatorTimeoutOverride||this.serviceTypingTimeout||this.configuration.typingIndicatorTimeoutDefault}initialize(){this.services.notificationClient.on("message",(async(e,t)=>{e===tn.TYPING_INDICATOR&&await this._handleRemoteTyping(JSON.parse(t))}))}async _handleRemoteTyping(e){Xi.trace("Got new typing indicator ",e),this.getConversation(e.channel_sid).then((t=>{t&&t._participants.forEach((t=>{if(t.identity!==e.identity)return;const n=this.configuration.typingIndicatorTimeoutOverride?this.configuration.typingIndicatorTimeoutOverride+1e3:1e3*e.typing_timeout;t._startTyping(n)}))})).catch((e=>{throw Xi.error(e),e}))}send(e){const t=this.sentUpdates.get(e);return t&&t>Date.now()-this.typingTimeout?Promise.resolve():(this.sentUpdates.set(e,Date.now()),this._send(e))}_send(e){Xi.trace("Sending typing indicator");const t=this.configuration.links.typing,n=`ChannelSid=${e}`;return this.services.twilsockClient.sendRequest(new Te.HttpRequest({method:"POST",url:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},payload:n,grant:this.configuration.productId})).then((e=>{const t=JSON.parse(e.payload);t.hasOwnProperty("typing_timeout")&&(this.serviceTypingTimeout=1e3*t.typing_timeout)})).catch((e=>{throw Xi.error("Failed to send typing indicator:",e),e}))}}class PushNotification{title;body;sound;badge;action;type;data;constructor(e){this.title=e.title||null,this.body=e.body||null,this.sound=e.sound||null,this.badge=e.badge||null,this.action=e.action||null,this.type=e.type||null,this.data=e.data||{}}}var Yi="3.0.1-rc.1";const er=e=>e.replace(/(^\/+|\/+$)/g,"");class tr extends Error{constructor(e){super(e)}}class nr{_serviceUrl;_services;_productId;constructor(e,t,n){this._serviceUrl=e,this._services=t,this._productId=n}_preProcessUrl(e){const t=er(e);return/^https?:\/\//.test(e)?t:`${er(this._serviceUrl)}/${t}`}async _makeRequest(e,t,n,i){const r=this._preProcessUrl(t),s={"Content-Type":"application/json; charset=utf-8",...i||{}};let a;switch(e){case"get":let e=r;n&&(e+="?"+Object.entries(n).map((e=>e.map((e=>encodeURIComponent(String(e)))).join("="))).join("&")),a=await this._services.transport.sendRequest(new Te.HttpRequest({url:e,headers:s,grant:this._productId}));break;case"post":a=await this._services.transport.sendRequest(new Te.HttpRequest({method:"POST",url:r,headers:s,payload:JSON.stringify(n),grant:this._productId}));break;case"delete":a=await this._services.transport.sendRequest(new Te.HttpRequest({method:"DELETE",url:r,headers:s,grant:this._productId}))}return a}async fetchResource(e,t){const n=new ke({min:50,max:1600,maxAttemptsCount:6});let i;try{i=await n.run((async()=>{const n=await this._makeRequest("get",e,t),i=JSON.parse(n.payload);if(404===n.statusCode&&50530===i.code)return{type:"noMetadata"};if(n.statusCode>=400)throw new Error(i.message);return{type:"success",data:i}}))}catch(t){throw new Error(`Fetch resource from "${e}" failed. ${t?.message?t.message:""}`)}if("noMetadata"===i.type)throw new tr("No metadata found.");return i.data}async mutateResource(e,t,n){const i=await this._makeRequest(e,t,n,{"X-Twilio-Mutation-Id":Pe()});let r={};try{r=JSON.parse(i.payload)}catch{}if(202===i.statusCode)return await this.fetchResource(r.resource_url);if(i.statusCode<200||i.statusCode>=300)throw new Error(`Mutation resulted with a non-success code ${i.statusCode}`);return r}}class ir{_services;_pageSize;_cacheTtlMs;_cachedTemplates=null;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5e3;this._services=e,this._pageSize=t,this._cacheTtlMs=n}async getContentTemplates(){if(null!==this._cachedTemplates)return this._cachedTemplates;let[e,t]=await this._fetchContentTemplates(),n=e;for(;null!==t;)[e,t]=await this._fetchContentTemplates(t),n=[...n,...e];return this._cachedTemplates=Object.freeze(n),setTimeout((()=>{this._cachedTemplates=null}),this._cacheTtlMs),n}async _fetchContentTemplates(e){const t=new R("Client/v2/ContentTemplates");t.arg("PageSize",this._pageSize),void 0!==e&&t.arg("PageToken",e);const n=await this._services.commandExecutor.fetchResource(t.build());return[n.templates.map((e=>new Fi(e))),n.meta.next_token]}}class rr{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,"function"==typeof this.onEviction)for(const[e,t]of this.oldCache.entries())this.onEviction(e,t);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){const t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){return this.cache.has(e)?this.cache.get(e):this.oldCache.has(e)?this.oldCache.get(e):void 0}delete(e){const t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.cache)yield e;for(const e of this.oldCache){const[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(const t of this.oldCache.keys())this.cache.has(t)||e++;return Math.min(this._size+e,this.maxSize)}}var sr,ar=rr;class or{type;data;constructor(e,t){this.type=e,this.data=t,Object.freeze(t)}}class cr{_services;_configuration;_cache;constructor(e,t){this._services=e,this._configuration=t,this._cache=new ar({maxSize:t.channelMetadataCacheCapacity})}async getChannelMetadata(e,t){const n=`${e},${t}`,i=this._cache.get(n);if(i)return i.item;const r=`${this._configuration.links.conversations}/${e}/Messages/${t}/ChannelMetadata`;let s;try{s=await this._services.commandExecutor.fetchResource(r)}catch(e){if(e instanceof tr)return this._cache.set(n,{item:null}),null;throw e}const a=new or(s.type,s.data);return this._cache.set(n,{item:a}),a}}class ur{commandExecutor;twilsockClient;users;notificationClient;network;typingIndicator;syncClient;mcsClient;transport;contentClient;channelMetadataClient}return e.Client=sr=class extends ue{static conversationAdded="conversationAdded";static conversationJoined="conversationJoined";static conversationLeft="conversationLeft";static conversationRemoved="conversationRemoved";static conversationUpdated="conversationUpdated";static participantJoined="participantJoined";static participantLeft="participantLeft";static participantUpdated="participantUpdated";static messageAdded="messageAdded";static messageRemoved="messageRemoved";static messageUpdated="messageUpdated";static tokenAboutToExpire="tokenAboutToExpire";static tokenExpired="tokenExpired";static typingEnded="typingEnded";static typingStarted="typingStarted";static pushNotification="pushNotification";static userSubscribed="userSubscribed";static userUnsubscribed="userUnsubscribed";static userUpdated="userUpdated";static initialized="initialized";static initFailed="initFailed";static connectionStateChanged="connectionStateChanged";static connectionError="connectionError";static version=Yi;static _logger=h.scope("Client");static _supportedPushChannels=["fcm","apn"];static _supportedPushDataFields={conversation_sid:"conversationSid",conversation_title:"conversationTitle",message_sid:"messageSid",message_index:"messageIndex",media_count:"mediaCount",media:"media"};version=Yi;connectionState="unknown";_ensureReady;_options;_services;_myself;_resolveEnsureReady;_rejectEnsureReady;_fpaToken;_configuration;_conversationsEntity;_conversationsPromise;constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(super(),this._fpaToken=e??"",this._options=t??{},!this._options.disableDeepClone){let e={...this._options,transport:void 0,twilsockClient:void 0};n=e,e=JSON.parse(JSON.stringify(n)),e.transport=this._options.transport,e.twilsockClient=this._options.twilsockClient,this._options=e}var n;this._options.logLevel=this._options.logLevel??"silent",sr._logger.setLevel(this._options.logLevel);const i=this._options.productId="ip_messaging";if(this._options.clientMetadata=this._options.clientMetadata||{},this._options.clientMetadata.hasOwnProperty("type")||(this._options.clientMetadata.type="conversations"),this._options.clientMetadata.hasOwnProperty("sdk")||(this._options.clientMetadata.sdk="JS",this._options.clientMetadata.sdkv=Yi),this._options.Sync=this._options.Sync||{},void 0===this._options.Sync.enableSessionStorage&&(this._options.Sync.enableSessionStorage=!0),this._options.region&&(this._options.Sync.region=this._options.region),!e)throw new Error("A valid Twilio token should be provided");this._services=new ur,this._myself=new User("","",null,this._services);const r=!this._options.twilsockClient;this._services.twilsockClient=this._options.twilsockClient=this._options.twilsockClient??new Te.TwilsockClient(e,i,this._options),this._services.twilsockClient.populateInitRegistrations(new Set([tn.TYPING_INDICATOR])),this._services.twilsockClient.on("tokenAboutToExpire",(()=>this.emit("tokenAboutToExpire"))),this._services.twilsockClient.on("tokenExpired",(()=>this.emit("tokenExpired"))),this._services.twilsockClient.on("disconnected",(()=>{sr._logger.debug("Handling stateChanged for ConversationsClient: new state disconnected"),"disconnected"!==this.connectionState&&(this.connectionState="disconnected",this.emit("connectionStateChanged",this.connectionState))})),this._services.twilsockClient.on("connecting",(()=>{sr._logger.debug("Handling stateChanged for ConversationsClient: new state connecting"),"connecting"!==this.connectionState&&(this.connectionState="connecting",this.emit("connectionStateChanged",this.connectionState))})),this._services.twilsockClient.on("connected",(()=>{sr._logger.debug("Handling stateChanged for ConversationsClient: new state connected"),"connected"!==this.connectionState&&(this.connectionState="connected",this.emit("connectionStateChanged",this.connectionState))})),this._services.transport=this._options.transport=this._options.transport??this._options.twilsockClient,this._services.notificationClient=this._options.notificationsClient=this._options.notificationsClient??new nn.Notifications(e,this._options),this._services.syncClient=this._options.syncClient=this._options.syncClient??new Mi(e,this._options);const s=t?.Chat||t?.IPMessaging||t||{},a=s.region||t?.region,o=s.apiUri||s.typingUri||`https://aim.${a||"us1"}.twilio.com`;this._services.commandExecutor=new nr(o,{transport:this._options.transport},i),this._services.contentClient=new ir(this._services);const c=this._services.twilsockClient.onceWithReplay("fatalError",(e=>{const t={terminal:!0,message:e.description};this._rejectEnsureReady(t),this.emit("initFailed",{error:t})}));this._services.twilsockClient.onceWithReplay("connected",(async()=>{sr._logger.debug("ConversationsClient started INITIALIZING"),c();try{await this._initialize()}catch(e){const t={terminal:!0,message:e.message};this._rejectEnsureReady(t),this.emit("initFailed",{error:t})}})),this._ensureReady=new Promise(((e,t)=>{this._resolveEnsureReady=e,this._rejectEnsureReady=t})).catch((e=>{sr._logger.error(e)})),r&&this._services.twilsockClient.connect()}get user(){return this._myself}get reachabilityEnabled(){if(!this._configuration)throw new Error("Reachability information could not yet be accessed as the client has not yet been initialized. Subscribe to 'initialized' and 'initFailed' events to properly react to the client initialization.");return this._configuration.reachabilityEnabled}static parsePushNotification(e){if(sr._logger.debug("parsePushNotification, notificationPayload=",e),void 0!==e.aps){if(!e.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");const t=sr._parsePushNotificationChatData(e),n=e.aps;let i,r=null;return"string"==typeof n.alert?i=n.alert||null:(i=n.alert?.body||null,r=n.alert?.title||null),new PushNotification({title:r,body:i,sound:n.sound||null,badge:n.badge||null,action:n.category||null,type:e.twi_message_type,data:t})}if(void 0!==e.data){const t=e.data;if(!t.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");const n=sr._parsePushNotificationChatData(e.data);return new PushNotification({title:t.twi_title||null,body:t.twi_body||null,sound:t.twi_sound||null,badge:null,action:t.twi_action||null,type:t.twi_message_type,data:n})}throw new Error("Provided push notification payload is not Programmable Chat notification")}static _parsePushNotificationChatData(e){const t={};for(const n in sr._supportedPushDataFields){const i=e[n];if(null!=i)if("message_index"!==n&&"media_count"!==n){if("media"!==n)t[sr._supportedPushDataFields[n]]=i;else if("string"==typeof i)try{t[sr._supportedPushDataFields[n]]=JSON.parse(i)}catch{sr._logger.debug("Media message notification parsing error")}}else{const e=T(i);null!==e&&(t[sr._supportedPushDataFields[n]]=e)}}return t}async shutdown(){await this._ensureReady,await(this._services.network?.disconnect())}async updateToken(e){return await this._ensureReady,sr._logger.info("updateToken"),this._fpaToken===e||(await this._services.twilsockClient.updateToken(e),await this._services.notificationClient.updateToken(e),await this._services.mcsClient.updateToken(e),this._fpaToken=e),this}async getConversationBySid(e){await this._ensureReady,await this._conversationsEntity.myConversationsRead.promise;const t=await this._conversationsEntity.getConversation(e);if(!t)throw new Error(`Conversation with SID ${e} was not found.`);return t}async peekConversationBySid(e){await this._ensureReady;const t=await this._conversationsEntity.peekConversation(e);if(!t)throw new Error(`Conversation with SID ${e} was not found.`);return t}async getConversationByUniqueName(e){await this._ensureReady,await this._conversationsEntity.myConversationsRead.promise;const t=await this._conversationsEntity.getConversationByUniqueName(e);if(!t)throw new Error(`Conversation with unique name ${e} was not found.`);return t}async getSubscribedConversations(){await this._ensureReady;const e=await this._conversationsPromise;return await e.getConversations()}async createConversation(e){return await this._ensureReady,e=e||{},this._conversationsPromise.then((t=>t.addConversation(e)))}async setPushRegistrationId(e,t){await this._ensureReady,this._subscribeToPushNotifications(e),this._services.notificationClient.setPushRegistrationId(e,t),await this._services.notificationClient.commitChanges()}async removePushRegistrations(e,t){await this._services.notificationClient.removeRegistrations(e,t)}parsePushNotification=sr.parsePushNotification;async handlePushNotification(e){await this._ensureReady,sr._logger.debug("handlePushNotification, notificationPayload=",e),this.emit("pushNotification",sr.parsePushNotification(e))}async getUser(e){return await this._ensureReady,this._services.users.getUser(e)}async getSubscribedUsers(){return await this._ensureReady,this._services.users.getSubscribedUsers()}getTemporaryContentUrlsForMediaSids(e){return new Oi.CancellablePromise((async(t,n,i)=>{if(!this._services.mcsClient||!e)return void n(new Error("Media Content Service is unavailable"));const r=this._services.mcsClient.mediaSetGetContentUrls(e);i((()=>{r.cancel()}));try{t(await r)}catch(e){n(e)}}))}getTemporaryContentUrlsForMedia(e){const t=e.map((e=>e.sid));return this.getTemporaryContentUrlsForMediaSids(t)}async getContentTemplates(){return await this._ensureReady,await this._services.contentClient.getContentTemplates()}async _initialize(){const e=await this._services.commandExecutor.fetchResource("Client/v2/Configuration");this._configuration=new E(this._options,e,sr._logger),this._services.channelMetadataClient=new cr(this._services,this._configuration),this._myself._resolveInitialization(this._configuration,this._configuration.userIdentity,this._configuration.userInfo,!0),this._services.typingIndicator=new Zi(this.getConversationBySid.bind(this),this._configuration,this._services),this._services.network=new en(this._configuration,this._services),this._services.users=new Qi(this._myself,this._configuration,this._services),this._services.users.on("userSubscribed",(e=>{this.emit("userSubscribed",e)})),this._services.users.on("userUpdated",(e=>this.emit("userUpdated",e))),this._services.users.on("userUnsubscribed",(e=>{this.emit("userUnsubscribed",e)})),this._conversationsEntity=new Gi(this._configuration,this._services),this._conversationsEntity.on("conversationAdded",(e=>{this.emit("conversationAdded",e)})),this._conversationsEntity.on("conversationRemoved",(e=>{this.emit("conversationRemoved",e)})),this._conversationsEntity.on("conversationJoined",(e=>{this.emit("conversationJoined",e)})),this._conversationsEntity.on("conversationLeft",(e=>{this.emit("conversationLeft",e)})),this._conversationsEntity.on("conversationUpdated",(e=>this.emit("conversationUpdated",e))),this._conversationsEntity.on("participantJoined",(e=>{this.emit("participantJoined",e)})),this._conversationsEntity.on("participantLeft",(e=>{this.emit("participantLeft",e)})),this._conversationsEntity.on("participantUpdated",(e=>this.emit("participantUpdated",e))),this._conversationsEntity.on("messageAdded",(e=>this.emit("messageAdded",e))),this._conversationsEntity.on("messageUpdated",(e=>this.emit("messageUpdated",e))),this._conversationsEntity.on("messageRemoved",(e=>this.emit("messageRemoved",e))),this._conversationsEntity.on("typingStarted",(e=>this.emit("typingStarted",e))),this._conversationsEntity.on("typingEnded",(e=>this.emit("typingEnded",e))),this._conversationsPromise=this._conversationsEntity.fetchConversations().then((()=>this._conversationsEntity)).catch((e=>{if("Client has been shut down."===e.message)return this._conversationsEntity;throw e})),await this._services.users.myself._ensureFetched(),sr._supportedPushChannels.forEach((e=>this._subscribeToPushNotifications(e))),this._services.typingIndicator.initialize(),this._services.mcsClient=new Oi.McsClient(this._fpaToken,this._configuration.links.mediaService,this._configuration.links.mediaSetService,{...this._options,transport:void 0}),this._resolveEnsureReady(),this.emit("initialized")}_subscribeToPushNotifications(e){[tn.NEW_MESSAGE,tn.ADDED_TO_CONVERSATION,tn.REMOVED_FROM_CONVERSATION,tn.TYPING_INDICATOR,tn.CONSUMPTION_UPDATE].forEach((t=>{this._services.notificationClient.subscribe(e,t)}))}},n([X(K),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],e.Client.prototype,"updateToken",null),n([X(K),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],e.Client.prototype,"getConversationBySid",null),n([X(K),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],e.Client.prototype,"peekConversationBySid",null),n([X(K),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],e.Client.prototype,"getConversationByUniqueName",null),n([X(["undefined",V("conversation options",{friendlyName:["string","undefined"],isPrivate:["boolean","undefined"],uniqueName:["string","undefined"]})]),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],e.Client.prototype,"createConversation",null),n([X(z("fcm","apn"),"string"),i("design:type",Function),i("design:paramtypes",[String,String]),i("design:returntype",Promise)],e.Client.prototype,"setPushRegistrationId",null),n([X(z("fcm","apn"),K),i("design:type",Function),i("design:paramtypes",[String,String]),i("design:returntype",Promise)],e.Client.prototype,"removePushRegistrations",null),n([X(J),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",Promise)],e.Client.prototype,"handlePushNotification",null),n([X(K),i("design:type",Function),i("design:paramtypes",[String]),i("design:returntype",Promise)],e.Client.prototype,"getUser",null),n([X(W("strings","string")),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Oi.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMediaSids",null),n([X(W("media",Media)),i("design:type",Function),i("design:paramtypes",[Array]),i("design:returntype",Oi.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMedia",null),n([Q(J),i("design:type",Function),i("design:paramtypes",[Object]),i("design:returntype",PushNotification)],e.Client,"parsePushNotification",null),e.Client=sr=n([G(K,[J,"undefined"]),i("design:paramtypes",[String,Object])],e.Client),e.AggregatedDeliveryReceipt=AggregatedDeliveryReceipt,e.CancellablePromise=Be,e.CancellationError=ze,e.ChannelMetadata=or,e.ContentTemplate=Fi,e.ContentTemplateVariable=ContentTemplateVariable,e.Conversation=Conversation,e.DetailedDeliveryReceipt=DetailedDeliveryReceipt,e.Media=Media,e.Message=Message,e.MessageBuilder=Ki,e.NotificationTypes=tn,e.Participant=Participant,e.PushNotification=PushNotification,e.RestPaginator=Ni,e.UnsentMessage=Wi,e.User=User,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|
129
|
+
this.Twilio=this.Twilio||{},this.Twilio.Conversations=function(e){"use strict";var t=void 0!==t?t:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{};function r(e){if(e.__esModule)return e;var t=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(e).forEach((function(n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})})),t}var i=function(e){return e&&e.Math==Math&&e},a=i("object"==typeof globalThis&&globalThis)||i("object"==typeof window&&window)||i("object"==typeof self&&self)||i("object"==typeof n&&n)||function(){return this}()||Function("return this")(),s={},o=function(e){try{return!!e()}catch(e){return!0}},u=!o((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),c={},l={}.propertyIsEnumerable,f=Object.getOwnPropertyDescriptor,d=f&&!l.call({1:2},1);c.f=d?function(e){var t=f(this,e);return!!t&&t.enumerable}:l;var p,h,v=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},y={}.toString,m=function(e){return y.call(e).slice(8,-1)},g=m,b="".split,w=o((function(){return!Object("z").propertyIsEnumerable(0)}))?function(e){return"String"==g(e)?b.call(e,""):Object(e)}:Object,k=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e},x=w,_=k,S=function(e){return x(_(e))},E=function(e){return"object"==typeof e?null!==e:"function"==typeof e},T=a,R=function(e){return"function"==typeof e?e:void 0},C=function(e,t){return arguments.length<2?R(T[e]):T[e]&&T[e][t]},I=C("navigator","userAgent")||"",O=a,P=I,A=O.process,j=O.Deno,M=A&&A.versions||j&&j.version,L=M&&M.v8;L?h=(p=L.split("."))[0]<4?1:p[0]+p[1]:P&&(!(p=P.match(/Edge\/(\d+)/))||p[1]>=74)&&(p=P.match(/Chrome\/(\d+)/))&&(h=p[1]);var N=h&&+h,U=N,D=o,F=!!Object.getOwnPropertySymbols&&!D((function(){var e=Symbol();return!String(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&U&&U<41})),B=F&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,q=C,z=B?function(e){return"symbol"==typeof e}:function(e){var t=q("Symbol");return"function"==typeof t&&Object(e)instanceof t},W=E,G={exports:{}},$=a,V=function(e,t){try{Object.defineProperty($,e,{value:t,configurable:!0,writable:!0})}catch(n){$[e]=t}return t},J=V,K="__core-js_shared__",H=a[K]||J(K,{}),Y=H;(G.exports=function(e,t){return Y[e]||(Y[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.17.3",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"});var Q=k,X=function(e){return Object(Q(e))},Z=X,ee={}.hasOwnProperty,te=Object.hasOwn||function(e,t){return ee.call(Z(e),t)},ne=0,re=Math.random(),ie=function(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++ne+re).toString(36)},ae=a,se=G.exports,oe=te,ue=ie,ce=F,le=B,fe=se("wks"),de=ae.Symbol,pe=le?de:de&&de.withoutSetter||ue,he=function(e){return oe(fe,e)&&(ce||"string"==typeof fe[e])||(ce&&oe(de,e)?fe[e]=de[e]:fe[e]=pe("Symbol."+e)),fe[e]},ve=E,ye=z,me=function(e,t){var n,r;if("string"===t&&"function"==typeof(n=e.toString)&&!W(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!W(r=n.call(e)))return r;if("string"!==t&&"function"==typeof(n=e.toString)&&!W(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")},ge=he("toPrimitive"),be=function(e,t){if(!ve(e)||ye(e))return e;var n,r=e[ge];if(void 0!==r){if(void 0===t&&(t="default"),n=r.call(e,t),!ve(n)||ye(n))return n;throw TypeError("Can't convert object to primitive value")}return void 0===t&&(t="number"),me(e,t)},we=be,ke=z,xe=function(e){var t=we(e,"string");return ke(t)?t:String(t)},_e=E,Se=a.document,Ee=_e(Se)&&_e(Se.createElement),Te=function(e){return Ee?Se.createElement(e):{}},Re=Te,Ce=!u&&!o((function(){return 7!=Object.defineProperty(Re("div"),"a",{get:function(){return 7}}).a})),Ie=u,Oe=c,Pe=v,Ae=S,je=xe,Me=te,Le=Ce,Ne=Object.getOwnPropertyDescriptor;s.f=Ie?Ne:function(e,t){if(e=Ae(e),t=je(t),Le)try{return Ne(e,t)}catch(e){}if(Me(e,t))return Pe(!Oe.f.call(e,t),e[t])};var Ue={},De=E,Fe=function(e){if(!De(e))throw TypeError(String(e)+" is not an object");return e},Be=u,qe=Ce,ze=Fe,We=xe,Ge=Object.defineProperty;Ue.f=Be?Ge:function(e,t,n){if(ze(e),t=We(t),ze(n),qe)try{return Ge(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var $e=Ue,Ve=v,Je=u?function(e,t,n){return $e.f(e,t,Ve(1,n))}:function(e,t,n){return e[t]=n,e},Ke={exports:{}},He=H,Ye=Function.toString;"function"!=typeof He.inspectSource&&(He.inspectSource=function(e){return Ye.call(e)});var Qe,Xe,Ze,et=He.inspectSource,tt=et,nt=a.WeakMap,rt="function"==typeof nt&&/native code/.test(tt(nt)),it=G.exports,at=ie,st=it("keys"),ot=function(e){return st[e]||(st[e]=at(e))},ut={},ct=rt,lt=E,ft=Je,dt=te,pt=H,ht=ot,vt=ut,yt="Object already initialized",mt=a.WeakMap;if(ct||pt.state){var gt=pt.state||(pt.state=new mt),bt=gt.get,wt=gt.has,kt=gt.set;Qe=function(e,t){if(wt.call(gt,e))throw new TypeError(yt);return t.facade=e,kt.call(gt,e,t),t},Xe=function(e){return bt.call(gt,e)||{}},Ze=function(e){return wt.call(gt,e)}}else{var xt=ht("state");vt[xt]=!0,Qe=function(e,t){if(dt(e,xt))throw new TypeError(yt);return t.facade=e,ft(e,xt,t),t},Xe=function(e){return dt(e,xt)?e[xt]:{}},Ze=function(e){return dt(e,xt)}}var _t={set:Qe,get:Xe,has:Ze,enforce:function(e){return Ze(e)?Xe(e):Qe(e,{})},getterFor:function(e){return function(t){var n;if(!lt(t)||(n=Xe(t)).type!==e)throw TypeError("Incompatible receiver, "+e+" required");return n}}},St=a,Et=Je,Tt=te,Rt=V,Ct=et,It=_t.get,Ot=_t.enforce,Pt=String(String).split("String");(Ke.exports=function(e,t,n,r){var i,a=!!r&&!!r.unsafe,s=!!r&&!!r.enumerable,o=!!r&&!!r.noTargetGet;"function"==typeof n&&("string"!=typeof t||Tt(n,"name")||Et(n,"name",t),(i=Ot(n)).source||(i.source=Pt.join("string"==typeof t?t:""))),e!==St?(a?!o&&e[t]&&(s=!0):delete e[t],s?e[t]=n:Et(e,t,n)):s?e[t]=n:Rt(t,n)})(Function.prototype,"toString",(function(){return"function"==typeof this&&It(this).source||Ct(this)}));var At={},jt=Math.ceil,Mt=Math.floor,Lt=function(e){return isNaN(e=+e)?0:(e>0?Mt:jt)(e)},Nt=Lt,Ut=Math.min,Dt=function(e){return e>0?Ut(Nt(e),9007199254740991):0},Ft=Lt,Bt=Math.max,qt=Math.min,zt=function(e,t){var n=Ft(e);return n<0?Bt(n+t,0):qt(n,t)},Wt=S,Gt=Dt,$t=zt,Vt=function(e){return function(t,n,r){var i,a=Wt(t),s=Gt(a.length),o=$t(r,s);if(e&&n!=n){for(;s>o;)if((i=a[o++])!=i)return!0}else for(;s>o;o++)if((e||o in a)&&a[o]===n)return e||o||0;return!e&&-1}},Jt={includes:Vt(!0),indexOf:Vt(!1)},Kt=te,Ht=S,Yt=Jt.indexOf,Qt=ut,Xt=function(e,t){var n,r=Ht(e),i=0,a=[];for(n in r)!Kt(Qt,n)&&Kt(r,n)&&a.push(n);for(;t.length>i;)Kt(r,n=t[i++])&&(~Yt(a,n)||a.push(n));return a},Zt=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],en=Xt,tn=Zt.concat("length","prototype");At.f=Object.getOwnPropertyNames||function(e){return en(e,tn)};var nn={};nn.f=Object.getOwnPropertySymbols;var rn=At,an=nn,sn=Fe,on=C("Reflect","ownKeys")||function(e){var t=rn.f(sn(e)),n=an.f;return n?t.concat(n(e)):t},un=te,cn=on,ln=s,fn=Ue,dn=function(e,t){for(var n=cn(t),r=fn.f,i=ln.f,a=0;a<n.length;a++){var s=n[a];un(e,s)||r(e,s,i(t,s))}},pn=o,hn=/#|\.prototype\./,vn=function(e,t){var n=mn[yn(e)];return n==bn||n!=gn&&("function"==typeof t?pn(t):!!t)},yn=vn.normalize=function(e){return String(e).replace(hn,".").toLowerCase()},mn=vn.data={},gn=vn.NATIVE="N",bn=vn.POLYFILL="P",wn=vn,kn=a,xn=s.f,_n=Je,Sn=Ke.exports,En=V,Tn=dn,Rn=wn,Cn=function(e,t){var n,r,i,a,s,o=e.target,u=e.global,c=e.stat;if(n=u?kn:c?kn[o]||En(o,{}):(kn[o]||{}).prototype)for(r in t){if(a=t[r],i=e.noTargetGet?(s=xn(n,r))&&s.value:n[r],!Rn(u?r:o+(c?".":"#")+r,e.forced)&&void 0!==i){if(typeof a==typeof i)continue;Tn(a,i)}(e.sham||i&&i.sham)&&_n(a,"sham",!0),Sn(n,r,a,e)}},In=Ue.f,On=te,Pn=he("toStringTag"),An=function(e,t,n){e&&!On(e=n?e:e.prototype,Pn)&&In(e,Pn,{configurable:!0,value:t})},jn=a,Mn=An;Cn({global:!0},{Reflect:{}}),Mn(jn.Reflect,"Reflect",!0);var Ln,Nn=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e},Un=Xt,Dn=Zt,Fn=Object.keys||function(e){return Un(e,Dn)},Bn=Ue,qn=Fe,zn=Fn,Wn=u?Object.defineProperties:function(e,t){qn(e);for(var n,r=zn(t),i=r.length,a=0;i>a;)Bn.f(e,n=r[a++],t[n]);return e},Gn=C("document","documentElement"),$n=Fe,Vn=Wn,Jn=Zt,Kn=ut,Hn=Gn,Yn=Te,Qn=ot("IE_PROTO"),Xn=function(){},Zn=function(e){return"<script>"+e+"</"+"script>"},er=function(e){e.write(Zn("")),e.close();var t=e.parentWindow.Object;return e=null,t},tr=function(){try{Ln=new ActiveXObject("htmlfile")}catch(e){}var e,t;tr="undefined"!=typeof document?document.domain&&Ln?er(Ln):((t=Yn("iframe")).style.display="none",Hn.appendChild(t),t.src=String("javascript:"),(e=t.contentWindow.document).open(),e.write(Zn("document.F=Object")),e.close(),e.F):er(Ln);for(var n=Jn.length;n--;)delete tr.prototype[Jn[n]];return tr()};Kn[Qn]=!0;var nr=Object.create||function(e,t){var n;return null!==e?(Xn.prototype=$n(e),n=new Xn,Xn.prototype=null,n[Qn]=e):n=tr(),void 0===t?n:Vn(n,t)},rr=Nn,ir=E,ar=[].slice,sr={},or=function(e,t,n){if(!(t in sr)){for(var r=[],i=0;i<t;i++)r[i]="a["+i+"]";sr[t]=Function("C,a","return new C("+r.join(",")+")")}return sr[t](e,n)},ur=Function.bind||function(e){var t=rr(this),n=ar.call(arguments,1),r=function(){var i=n.concat(ar.call(arguments));return this instanceof r?or(t,i.length,i):t.apply(e,i)};return ir(t.prototype)&&(r.prototype=t.prototype),r},cr=Cn,lr=Nn,fr=Fe,dr=E,pr=nr,hr=ur,vr=o,yr=C("Reflect","construct"),mr=vr((function(){function e(){}return!(yr((function(){}),[],e)instanceof e)})),gr=!vr((function(){yr((function(){}))})),br=mr||gr;cr({target:"Reflect",stat:!0,forced:br,sham:br},{construct:function(e,t){lr(e),fr(t);var n=arguments.length<3?e:lr(arguments[2]);if(gr&&!mr)return yr(e,t,n);if(e==n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var r=[null];return r.push.apply(r,t),new(hr.apply(e,r))}var i=n.prototype,a=pr(dr(i)?i:Object.prototype),s=Function.apply.call(e,a,t);return dr(s)?s:a}});var wr=X,kr=Fn;Cn({target:"Object",stat:!0,forced:o((function(){kr(1)}))},{keys:function(e){return kr(wr(e))}});var xr=m,_r=Array.isArray||function(e){return"Array"==xr(e)},Sr=z,Er=function(e){if(Sr(e))throw TypeError("Cannot convert a Symbol value to a string");return String(e)},Tr={},Rr=S,Cr=At.f,Ir={}.toString,Or="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];Tr.f=function(e){return Or&&"[object Window]"==Ir.call(e)?function(e){try{return Cr(e)}catch(e){return Or.slice()}}(e):Cr(Rr(e))};var Pr={},Ar=he;Pr.f=Ar;var jr=a,Mr=te,Lr=Pr,Nr=Ue.f,Ur=function(e){var t=jr.Symbol||(jr.Symbol={});Mr(t,e)||Nr(t,e,{value:Lr.f(e)})},Dr=Nn,Fr=function(e,t,n){if(Dr(e),void 0===t)return e;switch(n){case 0:return function(){return e.call(t)};case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,i){return e.call(t,n,r,i)}}return function(){return e.apply(t,arguments)}},Br=E,qr=_r,zr=he("species"),Wr=function(e){var t;return qr(e)&&("function"!=typeof(t=e.constructor)||t!==Array&&!qr(t.prototype)?Br(t)&&null===(t=t[zr])&&(t=void 0):t=void 0),void 0===t?Array:t},Gr=function(e,t){return new(Wr(e))(0===t?0:t)},$r=Fr,Vr=w,Jr=X,Kr=Dt,Hr=Gr,Yr=[].push,Qr=function(e){var t=1==e,n=2==e,r=3==e,i=4==e,a=6==e,s=7==e,o=5==e||a;return function(u,c,l,f){for(var d,p,h=Jr(u),v=Vr(h),y=$r(c,l,3),m=Kr(v.length),g=0,b=f||Hr,w=t?b(u,m):n||s?b(u,0):void 0;m>g;g++)if((o||g in v)&&(p=y(d=v[g],g,h),e))if(t)w[g]=p;else if(p)switch(e){case 3:return!0;case 5:return d;case 6:return g;case 2:Yr.call(w,d)}else switch(e){case 4:return!1;case 7:Yr.call(w,d)}return a?-1:r||i?i:w}},Xr={forEach:Qr(0),map:Qr(1),filter:Qr(2),some:Qr(3),every:Qr(4),find:Qr(5),findIndex:Qr(6),filterReject:Qr(7)},Zr=Cn,ei=a,ti=C,ni=u,ri=F,ii=o,ai=te,si=_r,oi=E,ui=z,ci=Fe,li=X,fi=S,di=xe,pi=Er,hi=v,vi=nr,yi=Fn,mi=At,gi=Tr,bi=nn,wi=s,ki=Ue,xi=c,_i=Je,Si=Ke.exports,Ei=G.exports,Ti=ut,Ri=ie,Ci=he,Ii=Pr,Oi=Ur,Pi=An,Ai=_t,ji=Xr.forEach,Mi=ot("hidden"),Li="Symbol",Ni=Ci("toPrimitive"),Ui=Ai.set,Di=Ai.getterFor(Li),Fi=Object.prototype,Bi=ei.Symbol,qi=ti("JSON","stringify"),zi=wi.f,Wi=ki.f,Gi=gi.f,$i=xi.f,Vi=Ei("symbols"),Ji=Ei("op-symbols"),Ki=Ei("string-to-symbol-registry"),Hi=Ei("symbol-to-string-registry"),Yi=Ei("wks"),Qi=ei.QObject,Xi=!Qi||!Qi.prototype||!Qi.prototype.findChild,Zi=ni&&ii((function(){return 7!=vi(Wi({},"a",{get:function(){return Wi(this,"a",{value:7}).a}})).a}))?function(e,t,n){var r=zi(Fi,t);r&&delete Fi[t],Wi(e,t,n),r&&e!==Fi&&Wi(Fi,t,r)}:Wi,ea=function(e,t){var n=Vi[e]=vi(Bi.prototype);return Ui(n,{type:Li,tag:e,description:t}),ni||(n.description=t),n},ta=function(e,t,n){e===Fi&&ta(Ji,t,n),ci(e);var r=di(t);return ci(n),ai(Vi,r)?(n.enumerable?(ai(e,Mi)&&e[Mi][r]&&(e[Mi][r]=!1),n=vi(n,{enumerable:hi(0,!1)})):(ai(e,Mi)||Wi(e,Mi,hi(1,{})),e[Mi][r]=!0),Zi(e,r,n)):Wi(e,r,n)},na=function(e,t){ci(e);var n=fi(t),r=yi(n).concat(sa(n));return ji(r,(function(t){ni&&!ra.call(n,t)||ta(e,t,n[t])})),e},ra=function(e){var t=di(e),n=$i.call(this,t);return!(this===Fi&&ai(Vi,t)&&!ai(Ji,t))&&(!(n||!ai(this,t)||!ai(Vi,t)||ai(this,Mi)&&this[Mi][t])||n)},ia=function(e,t){var n=fi(e),r=di(t);if(n!==Fi||!ai(Vi,r)||ai(Ji,r)){var i=zi(n,r);return!i||!ai(Vi,r)||ai(n,Mi)&&n[Mi][r]||(i.enumerable=!0),i}},aa=function(e){var t=Gi(fi(e)),n=[];return ji(t,(function(e){ai(Vi,e)||ai(Ti,e)||n.push(e)})),n},sa=function(e){var t=e===Fi,n=Gi(t?Ji:fi(e)),r=[];return ji(n,(function(e){!ai(Vi,e)||t&&!ai(Fi,e)||r.push(Vi[e])})),r};(ri||(Bi=function(){if(this instanceof Bi)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?pi(arguments[0]):void 0,t=Ri(e),n=function(e){this===Fi&&n.call(Ji,e),ai(this,Mi)&&ai(this[Mi],t)&&(this[Mi][t]=!1),Zi(this,t,hi(1,e))};return ni&&Xi&&Zi(Fi,t,{configurable:!0,set:n}),ea(t,e)},Si(Bi.prototype,"toString",(function(){return Di(this).tag})),Si(Bi,"withoutSetter",(function(e){return ea(Ri(e),e)})),xi.f=ra,ki.f=ta,wi.f=ia,mi.f=gi.f=aa,bi.f=sa,Ii.f=function(e){return ea(Ci(e),e)},ni&&(Wi(Bi.prototype,"description",{configurable:!0,get:function(){return Di(this).description}}),Si(Fi,"propertyIsEnumerable",ra,{unsafe:!0}))),Zr({global:!0,wrap:!0,forced:!ri,sham:!ri},{Symbol:Bi}),ji(yi(Yi),(function(e){Oi(e)})),Zr({target:Li,stat:!0,forced:!ri},{for:function(e){var t=pi(e);if(ai(Ki,t))return Ki[t];var n=Bi(t);return Ki[t]=n,Hi[n]=t,n},keyFor:function(e){if(!ui(e))throw TypeError(e+" is not a symbol");if(ai(Hi,e))return Hi[e]},useSetter:function(){Xi=!0},useSimple:function(){Xi=!1}}),Zr({target:"Object",stat:!0,forced:!ri,sham:!ni},{create:function(e,t){return void 0===t?vi(e):na(vi(e),t)},defineProperty:ta,defineProperties:na,getOwnPropertyDescriptor:ia}),Zr({target:"Object",stat:!0,forced:!ri},{getOwnPropertyNames:aa,getOwnPropertySymbols:sa}),Zr({target:"Object",stat:!0,forced:ii((function(){bi.f(1)}))},{getOwnPropertySymbols:function(e){return bi.f(li(e))}}),qi)&&Zr({target:"JSON",stat:!0,forced:!ri||ii((function(){var e=Bi();return"[null]"!=qi([e])||"{}"!=qi({a:e})||"{}"!=qi(Object(e))}))},{stringify:function(e,t,n){for(var r,i=[e],a=1;arguments.length>a;)i.push(arguments[a++]);if(r=t,(oi(t)||void 0!==e)&&!ui(e))return si(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!ui(t))return t}),i[1]=t,qi.apply(null,i)}});Bi.prototype[Ni]||_i(Bi.prototype,Ni,Bi.prototype.valueOf),Pi(Bi,Li),Ti[Mi]=!0;var oa=o,ua=N,ca=he("species"),la=function(e){return ua>=51||!oa((function(){var t=[];return(t.constructor={})[ca]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},fa=Xr.filter;Cn({target:"Array",proto:!0,forced:!la("filter")},{filter:function(e){return fa(this,e,arguments.length>1?arguments[1]:void 0)}});var da=Cn,pa=o,ha=S,va=s.f,ya=u,ma=pa((function(){va(1)}));da({target:"Object",stat:!0,forced:!ya||ma,sham:!ya},{getOwnPropertyDescriptor:function(e,t){return va(ha(e),t)}});var ga=xe,ba=Ue,wa=v,ka=function(e,t,n){var r=ga(t);r in e?ba.f(e,r,wa(0,n)):e[r]=n},xa=on,_a=S,Sa=s,Ea=ka;function Ta(e,t,n,r,i,a,s){try{var o=e[a](s),u=o.value}catch(e){return void n(e)}o.done?t(u):Promise.resolve(u).then(r,i)}function Ra(e){return function(){var t=this,n=arguments;return new Promise((function(r,i){var a=e.apply(t,n);function s(e){Ta(a,r,i,s,o,"next",e)}function o(e){Ta(a,r,i,s,o,"throw",e)}s(void 0)}))}}function Ca(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ia(e,t){return Ia=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Ia(e,t)}function Oa(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Ia(e,t)}function Pa(e){return Pa="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Pa(e)}function Aa(e,t){if(t&&("object"===Pa(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return Ca(e)}function ja(e){return ja=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},ja(e)}function Ma(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function La(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 Na(e,t,n){return t&&La(e.prototype,t),n&&La(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function Ua(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Cn({target:"Object",stat:!0,sham:!u},{getOwnPropertyDescriptors:function(e){for(var t,n,r=_a(e),i=Sa.f,a=xa(r),s={},o=0;a.length>o;)void 0!==(n=i(r,t=a[o++]))&&Ea(s,t,n);return s}});var Da={};Da[he("toStringTag")]="z";var Fa="[object z]"===String(Da),Ba=Fa,qa=m,za=he("toStringTag"),Wa="Arguments"==qa(function(){return arguments}()),Ga=Ba?qa:function(e){var t,n,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),za))?n:Wa?qa(t):"Object"==(r=qa(t))&&"function"==typeof t.callee?"Arguments":r},$a=Ga,Va=Fa?{}.toString:function(){return"[object "+$a(this)+"]"},Ja=Fa,Ka=Ke.exports,Ha=Va;Ja||Ka(Object.prototype,"toString",Ha,{unsafe:!0});var Ya=a.Promise,Qa=Ke.exports,Xa=function(e,t,n){for(var r in t)Qa(e,r,t[r],n);return e},Za=E,es=Fe,ts=function(e){if(!Za(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e},ns=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(n,[]),t=n instanceof Array}catch(e){}return function(n,r){return es(n),ts(r),t?e.call(n,r):n.__proto__=r,n}}():void 0),rs=C,is=Ue,as=u,ss=he("species"),os=function(e){var t=rs(e),n=is.f;as&&t&&!t[ss]&&n(t,ss,{configurable:!0,get:function(){return this}})},us=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e},cs={},ls=cs,fs=he("iterator"),ds=Array.prototype,ps=function(e){return void 0!==e&&(ls.Array===e||ds[fs]===e)},hs=Ga,vs=cs,ys=he("iterator"),ms=function(e){if(null!=e)return e[ys]||e["@@iterator"]||vs[hs(e)]},gs=Fe,bs=ms,ws=function(e,t){var n=arguments.length<2?bs(e):t;if("function"!=typeof n)throw TypeError(String(e)+" is not iterable");return gs(n.call(e))},ks=Fe,xs=function(e,t,n){var r,i;ks(e);try{if(void 0===(r=e.return)){if("throw"===t)throw n;return n}r=r.call(e)}catch(e){i=!0,r=e}if("throw"===t)throw n;if(i)throw r;return ks(r),n},_s=Fe,Ss=ps,Es=Dt,Ts=Fr,Rs=ws,Cs=ms,Is=xs,Os=function(e,t){this.stopped=e,this.result=t},Ps=function(e,t,n){var r,i,a,s,o,u,c,l=n&&n.that,f=!(!n||!n.AS_ENTRIES),d=!(!n||!n.IS_ITERATOR),p=!(!n||!n.INTERRUPTED),h=Ts(t,l,1+f+p),v=function(e){return r&&Is(r,"normal",e),new Os(!0,e)},y=function(e){return f?(_s(e),p?h(e[0],e[1],v):h(e[0],e[1])):p?h(e,v):h(e)};if(d)r=e;else{if("function"!=typeof(i=Cs(e)))throw TypeError("Target is not iterable");if(Ss(i)){for(a=0,s=Es(e.length);s>a;a++)if((o=y(e[a]))&&o instanceof Os)return o;return new Os(!1)}r=Rs(e,i)}for(u=r.next;!(c=u.call(r)).done;){try{o=y(c.value)}catch(e){Is(r,"throw",e)}if("object"==typeof o&&o&&o instanceof Os)return o}return new Os(!1)},As=he("iterator"),js=!1;try{var Ms=0,Ls={next:function(){return{done:!!Ms++}},return:function(){js=!0}};Ls[As]=function(){return this},Array.from(Ls,(function(){throw 2}))}catch(e){}var Ns,Us,Ds,Fs,Bs=function(e,t){if(!t&&!js)return!1;var n=!1;try{var r={};r[As]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(e){}return n},qs=Fe,zs=Nn,Ws=he("species"),Gs=function(e,t){var n,r=qs(e).constructor;return void 0===r||null==(n=qs(r)[Ws])?t:zs(n)},$s=/(?:ipad|iphone|ipod).*applewebkit/i.test(I),Vs="process"==m(a.process),Js=a,Ks=o,Hs=Fr,Ys=Gn,Qs=Te,Xs=$s,Zs=Vs,eo=Js.setImmediate,to=Js.clearImmediate,no=Js.process,ro=Js.MessageChannel,io=Js.Dispatch,ao=0,so={},oo="onreadystatechange";try{Ns=Js.location}catch(e){}var uo=function(e){if(so.hasOwnProperty(e)){var t=so[e];delete so[e],t()}},co=function(e){return function(){uo(e)}},lo=function(e){uo(e.data)},fo=function(e){Js.postMessage(String(e),Ns.protocol+"//"+Ns.host)};eo&&to||(eo=function(e){for(var t=[],n=arguments.length,r=1;n>r;)t.push(arguments[r++]);return so[++ao]=function(){("function"==typeof e?e:Function(e)).apply(void 0,t)},Us(ao),ao},to=function(e){delete so[e]},Zs?Us=function(e){no.nextTick(co(e))}:io&&io.now?Us=function(e){io.now(co(e))}:ro&&!Xs?(Fs=(Ds=new ro).port2,Ds.port1.onmessage=lo,Us=Hs(Fs.postMessage,Fs,1)):Js.addEventListener&&"function"==typeof postMessage&&!Js.importScripts&&Ns&&"file:"!==Ns.protocol&&!Ks(fo)?(Us=fo,Js.addEventListener("message",lo,!1)):Us=oo in Qs("script")?function(e){Ys.appendChild(Qs("script")).onreadystatechange=function(){Ys.removeChild(this),uo(e)}}:function(e){setTimeout(co(e),0)});var po,ho,vo,yo,mo,go,bo,wo,ko={set:eo,clear:to},xo=a,_o=/ipad|iphone|ipod/i.test(I)&&void 0!==xo.Pebble,So=/web0s(?!.*chrome)/i.test(I),Eo=a,To=s.f,Ro=ko.set,Co=$s,Io=_o,Oo=So,Po=Vs,Ao=Eo.MutationObserver||Eo.WebKitMutationObserver,jo=Eo.document,Mo=Eo.process,Lo=Eo.Promise,No=To(Eo,"queueMicrotask"),Uo=No&&No.value;Uo||(po=function(){var e,t;for(Po&&(e=Mo.domain)&&e.exit();ho;){t=ho.fn,ho=ho.next;try{t()}catch(e){throw ho?yo():vo=void 0,e}}vo=void 0,e&&e.enter()},Co||Po||Oo||!Ao||!jo?!Io&&Lo&&Lo.resolve?((bo=Lo.resolve(void 0)).constructor=Lo,wo=bo.then,yo=function(){wo.call(bo,po)}):yo=Po?function(){Mo.nextTick(po)}:function(){Ro.call(Eo,po)}:(mo=!0,go=jo.createTextNode(""),new Ao(po).observe(go,{characterData:!0}),yo=function(){go.data=mo=!mo}));var Do=Uo||function(e){var t={fn:e,next:void 0};vo&&(vo.next=t),ho||(ho=t,yo()),vo=t},Fo={},Bo=Nn,qo=function(e){var t,n;this.promise=new e((function(e,r){if(void 0!==t||void 0!==n)throw TypeError("Bad Promise constructor");t=e,n=r})),this.resolve=Bo(t),this.reject=Bo(n)};Fo.f=function(e){return new qo(e)};var zo,Wo,Go,$o,Vo=Fe,Jo=E,Ko=Fo,Ho=a,Yo="object"==typeof window,Qo=Cn,Xo=a,Zo=C,eu=Ya,tu=Ke.exports,nu=Xa,ru=ns,iu=An,au=os,su=E,ou=Nn,uu=us,cu=et,lu=Ps,fu=Bs,du=Gs,pu=ko.set,hu=Do,vu=function(e,t){if(Vo(e),Jo(t)&&t.constructor===e)return t;var n=Ko.f(e);return(0,n.resolve)(t),n.promise},yu=function(e,t){var n=Ho.console;n&&n.error&&(1===arguments.length?n.error(e):n.error(e,t))},mu=Fo,gu=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},bu=_t,wu=wn,ku=Yo,xu=Vs,_u=N,Su=he("species"),Eu="Promise",Tu=bu.get,Ru=bu.set,Cu=bu.getterFor(Eu),Iu=eu&&eu.prototype,Ou=eu,Pu=Iu,Au=Xo.TypeError,ju=Xo.document,Mu=Xo.process,Lu=mu.f,Nu=Lu,Uu=!!(ju&&ju.createEvent&&Xo.dispatchEvent),Du="function"==typeof PromiseRejectionEvent,Fu="unhandledrejection",Bu=!1,qu=wu(Eu,(function(){var e=cu(Ou),t=e!==String(Ou);if(!t&&66===_u)return!0;if(_u>=51&&/native code/.test(e))return!1;var n=new Ou((function(e){e(1)})),r=function(e){e((function(){}),(function(){}))};return(n.constructor={})[Su]=r,!(Bu=n.then((function(){}))instanceof r)||!t&&ku&&!Du})),zu=qu||!fu((function(e){Ou.all(e).catch((function(){}))})),Wu=function(e){var t;return!(!su(e)||"function"!=typeof(t=e.then))&&t},Gu=function(e,t){if(!e.notified){e.notified=!0;var n=e.reactions;hu((function(){for(var r=e.value,i=1==e.state,a=0;n.length>a;){var s,o,u,c=n[a++],l=i?c.ok:c.fail,f=c.resolve,d=c.reject,p=c.domain;try{l?(i||(2===e.rejection&&Ku(e),e.rejection=1),!0===l?s=r:(p&&p.enter(),s=l(r),p&&(p.exit(),u=!0)),s===c.promise?d(Au("Promise-chain cycle")):(o=Wu(s))?o.call(s,f,d):f(s)):d(r)}catch(e){p&&!u&&p.exit(),d(e)}}e.reactions=[],e.notified=!1,t&&!e.rejection&&Vu(e)}))}},$u=function(e,t,n){var r,i;Uu?((r=ju.createEvent("Event")).promise=t,r.reason=n,r.initEvent(e,!1,!0),Xo.dispatchEvent(r)):r={promise:t,reason:n},!Du&&(i=Xo["on"+e])?i(r):e===Fu&&yu("Unhandled promise rejection",n)},Vu=function(e){pu.call(Xo,(function(){var t,n=e.facade,r=e.value;if(Ju(e)&&(t=gu((function(){xu?Mu.emit("unhandledRejection",r,n):$u(Fu,n,r)})),e.rejection=xu||Ju(e)?2:1,t.error))throw t.value}))},Ju=function(e){return 1!==e.rejection&&!e.parent},Ku=function(e){pu.call(Xo,(function(){var t=e.facade;xu?Mu.emit("rejectionHandled",t):$u("rejectionhandled",t,e.value)}))},Hu=function(e,t,n){return function(r){e(t,r,n)}},Yu=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=2,Gu(e,!0))},Qu=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw Au("Promise can't be resolved itself");var r=Wu(t);r?hu((function(){var n={done:!1};try{r.call(t,Hu(Qu,n,e),Hu(Yu,n,e))}catch(t){Yu(n,t,e)}})):(e.value=t,e.state=1,Gu(e,!1))}catch(t){Yu({done:!1},t,e)}}};if(qu&&(Pu=(Ou=function(e){uu(this,Ou,Eu),ou(e),zo.call(this);var t=Tu(this);try{e(Hu(Qu,t),Hu(Yu,t))}catch(e){Yu(t,e)}}).prototype,(zo=function(e){Ru(this,{type:Eu,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=nu(Pu,{then:function(e,t){var n=Cu(this),r=Lu(du(this,Ou));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=xu?Mu.domain:void 0,n.parent=!0,n.reactions.push(r),0!=n.state&&Gu(n,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Wo=function(){var e=new zo,t=Tu(e);this.promise=e,this.resolve=Hu(Qu,t),this.reject=Hu(Yu,t)},mu.f=Lu=function(e){return e===Ou||e===Go?new Wo(e):Nu(e)},"function"==typeof eu&&Iu!==Object.prototype)){$o=Iu.then,Bu||(tu(Iu,"then",(function(e,t){var n=this;return new Ou((function(e,t){$o.call(n,e,t)})).then(e,t)}),{unsafe:!0}),tu(Iu,"catch",Pu.catch,{unsafe:!0}));try{delete Iu.constructor}catch(e){}ru&&ru(Iu,Pu)}Qo({global:!0,wrap:!0,forced:qu},{Promise:Ou}),iu(Ou,Eu,!1),au(Eu),Go=Zo(Eu),Qo({target:Eu,stat:!0,forced:qu},{reject:function(e){var t=Lu(this);return t.reject.call(void 0,e),t.promise}}),Qo({target:Eu,stat:!0,forced:qu},{resolve:function(e){return vu(this,e)}}),Qo({target:Eu,stat:!0,forced:zu},{all:function(e){var t=this,n=Lu(t),r=n.resolve,i=n.reject,a=gu((function(){var n=ou(t.resolve),a=[],s=0,o=1;lu(e,(function(e){var u=s++,c=!1;a.push(void 0),o++,n.call(t,e).then((function(e){c||(c=!0,a[u]=e,--o||r(a))}),i)})),--o||r(a)}));return a.error&&i(a.value),n.promise},race:function(e){var t=this,n=Lu(t),r=n.reject,i=gu((function(){var i=ou(t.resolve);lu(e,(function(e){i.call(t,e).then(n.resolve,r)}))}));return i.error&&r(i.value),n.promise}});var Xu=Xr.map;Cn({target:"Array",proto:!0,forced:!la("map")},{map:function(e){return Xu(this,e,arguments.length>1?arguments[1]:void 0)}});var Zu={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},ec=Te("span").classList,tc=ec&&ec.constructor&&ec.constructor.prototype,nc=tc===Object.prototype?void 0:tc,rc=o,ic=function(e,t){var n=[][e];return!!n&&rc((function(){n.call(null,t||function(){throw 1},1)}))},ac=Xr.forEach,sc=ic("forEach")?[].forEach:function(e){return ac(this,e,arguments.length>1?arguments[1]:void 0)},oc=a,uc=Zu,cc=nc,lc=sc,fc=Je,dc=function(e){if(e&&e.forEach!==lc)try{fc(e,"forEach",lc)}catch(t){e.forEach=lc}};for(var pc in uc)dc(oc[pc]&&oc[pc].prototype);dc(cc);var hc,vc=Object.prototype,yc=vc.hasOwnProperty,mc="function"==typeof Symbol?Symbol:{},gc=mc.iterator||"@@iterator",bc=mc.asyncIterator||"@@asyncIterator",wc=mc.toStringTag||"@@toStringTag";function kc(e,t,n,r){var i=t&&t.prototype instanceof Cc?t:Cc,a=Object.create(i.prototype),s=new qc(r||[]);return a._invoke=function(e,t,n){var r=_c;return function(i,a){if(r===Ec)throw new Error("Generator is already running");if(r===Tc){if("throw"===i)throw a;return Wc()}for(n.method=i,n.arg=a;;){var s=n.delegate;if(s){var o=Dc(s,n);if(o){if(o===Rc)continue;return o}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(r===_c)throw r=Tc,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r=Ec;var u=xc(e,t,n);if("normal"===u.type){if(r=n.done?Tc:Sc,u.arg===Rc)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(r=Tc,n.method="throw",n.arg=u.arg)}}}(e,n,s),a}function xc(e,t,n){try{return{type:"normal",arg:e.call(t,n)}}catch(e){return{type:"throw",arg:e}}}var _c="suspendedStart",Sc="suspendedYield",Ec="executing",Tc="completed",Rc={};function Cc(){}function Ic(){}function Oc(){}var Pc={};Pc[gc]=function(){return this};var Ac=Object.getPrototypeOf,jc=Ac&&Ac(Ac(zc([])));jc&&jc!==vc&&yc.call(jc,gc)&&(Pc=jc);var Mc=Oc.prototype=Cc.prototype=Object.create(Pc);function Lc(e){["next","throw","return"].forEach((function(t){e[t]=function(e){return this._invoke(t,e)}}))}function Nc(e){var t="function"==typeof e&&e.constructor;return!!t&&(t===Ic||"GeneratorFunction"===(t.displayName||t.name))}function Uc(e,t){function n(r,i,a,s){var o=xc(e[r],e,i);if("throw"!==o.type){var u=o.arg,c=u.value;return c&&"object"===Pa(c)&&yc.call(c,"__await")?t.resolve(c.__await).then((function(e){n("next",e,a,s)}),(function(e){n("throw",e,a,s)})):t.resolve(c).then((function(e){u.value=e,a(u)}),(function(e){return n("throw",e,a,s)}))}s(o.arg)}var r;this._invoke=function(e,i){function a(){return new t((function(t,r){n(e,i,t,r)}))}return r=r?r.then(a,a):a()}}function Dc(e,t){var n=e.iterator[t.method];if(n===hc){if(t.delegate=null,"throw"===t.method){if(e.iterator.return&&(t.method="return",t.arg=hc,Dc(e,t),"throw"===t.method))return Rc;t.method="throw",t.arg=new TypeError("The iterator does not provide a 'throw' method")}return Rc}var r=xc(n,e.iterator,t.arg);if("throw"===r.type)return t.method="throw",t.arg=r.arg,t.delegate=null,Rc;var i=r.arg;return i?i.done?(t[e.resultName]=i.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=hc),t.delegate=null,Rc):i:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,Rc)}function Fc(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function Bc(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function qc(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(Fc,this),this.reset(!0)}function zc(e){if(e){var t=e[gc];if(t)return t.call(e);if("function"==typeof e.next)return e;if(!isNaN(e.length)){var n=-1,r=function t(){for(;++n<e.length;)if(yc.call(e,n))return t.value=e[n],t.done=!1,t;return t.value=hc,t.done=!0,t};return r.next=r}}return{next:Wc}}function Wc(){return{value:hc,done:!0}}Ic.prototype=Mc.constructor=Oc,Oc.constructor=Ic,Oc[wc]=Ic.displayName="GeneratorFunction",Lc(Uc.prototype),Uc.prototype[bc]=function(){return this},Lc(Mc),Mc[wc]="Generator",Mc[gc]=function(){return this},Mc.toString=function(){return"[object Generator]"},qc.prototype={constructor:qc,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=hc,this.done=!1,this.delegate=null,this.method="next",this.arg=hc,this.tryEntries.forEach(Bc),!e)for(var t in this)"t"===t.charAt(0)&&yc.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=hc)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(e){if(this.done)throw e;var t=this;function n(n,r){return a.type="throw",a.arg=e,t.next=n,r&&(t.method="next",t.arg=hc),!!r}for(var r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var s=yc.call(i,"catchLoc"),o=yc.call(i,"finallyLoc");if(s&&o){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(s){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!o)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(e,t){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&yc.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===e||"continue"===e)&&i.tryLoc<=t&&t<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=e,a.arg=t,i?(this.method="next",this.next=i.finallyLoc,Rc):this.complete(a)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),Rc},finish:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.finallyLoc===e)return this.complete(n.completion,n.afterLoc),Bc(n),Rc}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var n=this.tryEntries[t];if(n.tryLoc===e){var r=n.completion;if("throw"===r.type){var i=r.arg;Bc(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,n){return this.delegate={iterator:zc(e),resultName:t,nextLoc:n},"next"===this.method&&(this.arg=hc),Rc}};var Gc={wrap:kc,isGeneratorFunction:Nc,AsyncIterator:Uc,mark:function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,Oc):(e.__proto__=Oc,wc in e||(e[wc]="GeneratorFunction")),e.prototype=Object.create(Mc),e},awrap:function(e){return{__await:e}},async:function(e,t,n,r,i){void 0===i&&(i=Promise);var a=new Uc(kc(e,t,n,r),i);return Nc(t)?a:a.next().then((function(e){return e.done?e.value:a.next()}))},keys:function(e){var t=[];for(var n in e)t.push(n);return t.reverse(),function n(){for(;t.length;){var r=t.pop();if(r in e)return n.value=r,n.done=!1,n}return n.done=!0,n}},values:zc},$c=Object.freeze({__proto__:null,default:Gc});function Vc(e,t,n,r){var i,a=arguments.length,s=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"===("undefined"==typeof Reflect?"undefined":Pa(Reflect))&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(s=(a<3?i(s):a>3?i(t,n,s):i(t,n))||s);return a>3&&s&&Object.defineProperty(t,n,s),s}function Jc(e,t){if("object"===("undefined"==typeof Reflect?"undefined":Pa(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}var Kc=Cn,Hc=o,Yc=_r,Qc=E,Xc=X,Zc=Dt,el=ka,tl=Gr,nl=la,rl=N,il=he("isConcatSpreadable"),al=9007199254740991,sl="Maximum allowed index exceeded",ol=rl>=51||!Hc((function(){var e=[];return e[il]=!1,e.concat()[0]!==e})),ul=nl("concat"),cl=function(e){if(!Qc(e))return!1;var t=e[il];return void 0!==t?!!t:Yc(e)};Kc({target:"Array",proto:!0,forced:!ol||!ul},{concat:function(e){var t,n,r,i,a,s=Xc(this),o=tl(s,0),u=0;for(t=-1,r=arguments.length;t<r;t++)if(cl(a=-1===t?s:arguments[t])){if(u+(i=Zc(a.length))>al)throw TypeError(sl);for(n=0;n<i;n++,u++)n in a&&el(o,u,a[n])}else{if(u>=al)throw TypeError(sl);el(o,u++,a)}return o.length=u,o}});var ll=Fe,fl=xs,dl=Fr,pl=X,hl=function(e,t,n,r){try{return r?t(ll(n)[0],n[1]):t(n)}catch(t){fl(e,"throw",t)}},vl=ps,yl=Dt,ml=ka,gl=ws,bl=ms,wl=function(e){var t,n,r,i,a,s,o=pl(e),u="function"==typeof this?this:Array,c=arguments.length,l=c>1?arguments[1]:void 0,f=void 0!==l,d=bl(o),p=0;if(f&&(l=dl(l,c>2?arguments[2]:void 0,2)),null==d||u==Array&&vl(d))for(n=new u(t=yl(o.length));t>p;p++)s=f?l(o[p],p):o[p],ml(n,p,s);else for(a=(i=gl(o,d)).next,n=new u;!(r=a.call(i)).done;p++)s=f?hl(i,l,[r.value,p],!0):r.value,ml(n,p,s);return n.length=p,n},kl=wl;Cn({target:"Array",stat:!0,forced:!Bs((function(e){Array.from(e)}))},{from:kl});var xl,_l,Sl,El=Lt,Tl=Er,Rl=k,Cl=function(e){return function(t,n){var r,i,a=Tl(Rl(t)),s=El(n),o=a.length;return s<0||s>=o?e?"":void 0:(r=a.charCodeAt(s))<55296||r>56319||s+1===o||(i=a.charCodeAt(s+1))<56320||i>57343?e?a.charAt(s):r:e?a.slice(s,s+2):i-56320+(r-55296<<10)+65536}},Il={codeAt:Cl(!1),charAt:Cl(!0)},Ol=!o((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Pl=te,Al=X,jl=Ol,Ml=ot("IE_PROTO"),Ll=Object.prototype,Nl=jl?Object.getPrototypeOf:function(e){return e=Al(e),Pl(e,Ml)?e[Ml]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?Ll:null},Ul=o,Dl=Nl,Fl=Je,Bl=he("iterator"),ql=!1;[].keys&&("next"in(Sl=[].keys())?(_l=Dl(Dl(Sl)))!==Object.prototype&&(xl=_l):ql=!0);var zl=null==xl||Ul((function(){var e={};return xl[Bl].call(e)!==e}));zl&&(xl={}),"function"!=typeof xl[Bl]&&Fl(xl,Bl,(function(){return this}));var Wl={IteratorPrototype:xl,BUGGY_SAFARI_ITERATORS:ql},Gl=Wl.IteratorPrototype,$l=nr,Vl=v,Jl=An,Kl=cs,Hl=function(){return this},Yl=function(e,t,n){var r=t+" Iterator";return e.prototype=$l(Gl,{next:Vl(1,n)}),Jl(e,r,!1),Kl[r]=Hl,e},Ql=Cn,Xl=Yl,Zl=Nl,ef=ns,tf=An,nf=Je,rf=Ke.exports,af=cs,sf=Wl.IteratorPrototype,of=Wl.BUGGY_SAFARI_ITERATORS,uf=he("iterator"),cf="keys",lf="values",ff="entries",df=function(){return this},pf=function(e,t,n,r,i,a,s){Xl(n,t,r);var o,u,c,l=function(e){if(e===i&&v)return v;if(!of&&e in p)return p[e];switch(e){case cf:case lf:case ff:return function(){return new n(this,e)}}return function(){return new n(this)}},f=t+" Iterator",d=!1,p=e.prototype,h=p[uf]||p["@@iterator"]||i&&p[i],v=!of&&h||l(i),y="Array"==t&&p.entries||h;if(y&&(o=Zl(y.call(new e)))!==Object.prototype&&o.next&&(Zl(o)!==sf&&(ef?ef(o,sf):"function"!=typeof o[uf]&&nf(o,uf,df)),tf(o,f,!0)),i==lf&&h&&h.name!==lf&&(d=!0,v=function(){return h.call(this)}),p[uf]!==v&&nf(p,uf,v),af[t]=v,i)if(u={values:l(lf),keys:a?v:l(cf),entries:l(ff)},s)for(c in u)(of||d||!(c in p))&&rf(p,c,u[c]);else Ql({target:t,proto:!0,forced:of||d},u);return u},hf=Il.charAt,vf=Er,yf=_t,mf=pf,gf="String Iterator",bf=yf.set,wf=yf.getterFor(gf);mf(String,"String",(function(e){bf(this,{type:gf,string:vf(e),index:0})}),(function(){var e,t=wf(this),n=t.string,r=t.index;return r>=n.length?{value:void 0,done:!0}:(e=hf(n,r),t.index+=e.length,{value:e,done:!1})}));var kf,xf,_f,Sf={exports:{}};function Ef(e,t){return["".concat((new Date).toISOString()," Conversations ").concat(e,":")].concat(Array.from(t))}xf=n,_f=function(){var e=function(){},t="undefined",n=("undefined"==typeof window?"undefined":Pa(window))!==t&&Pa(window.navigator)!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function i(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function s(r){return"debug"===r&&(r="log"),("undefined"==typeof console?"undefined":Pa(console))!==t&&("trace"===r&&n?a:void 0!==console[r]?i(console,r):void 0!==console.log?i(console,"log"):e)}function o(t,n){for(var i=0;i<r.length;i++){var a=r[i];this[a]=i<t?e:this.methodFactory(a,t,n)}this.log=this.debug}function u(e,n,r){return function(){("undefined"==typeof console?"undefined":Pa(console))!==t&&(o.call(this,n,r),this[e].apply(this,arguments))}}function c(e,t,n){return s(e)||u.apply(this,arguments)}function l(e,n,i){var a,s=this;n=null==n?"WARN":n;var u="loglevel";function l(){var e;if(("undefined"==typeof window?"undefined":Pa(window))!==t&&u){try{e=window.localStorage[u]}catch(e){}if(Pa(e)===t)try{var n=window.document.cookie,r=n.indexOf(encodeURIComponent(u)+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r))[1])}catch(e){}return void 0===s.levels[e]&&(e=void 0),e}}"string"==typeof e?u+=":"+e:"symbol"===Pa(e)&&(u=void 0),s.name=e,s.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},s.methodFactory=i||c,s.getLevel=function(){return a},s.setLevel=function(n,i){if("string"==typeof n&&void 0!==s.levels[n.toUpperCase()]&&(n=s.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=s.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(a=n,!1!==i&&function(e){var n=(r[e]||"silent").toUpperCase();if(("undefined"==typeof window?"undefined":Pa(window))!==t&&u){try{return void(window.localStorage[u]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"="+n+";"}catch(e){}}}(n),o.call(s,n,e),("undefined"==typeof console?"undefined":Pa(console))===t&&n<s.levels.SILENT)return"No console available for logging"},s.setDefaultLevel=function(e){n=e,l()||s.setLevel(e,!1)},s.resetLevel=function(){s.setLevel(n,!1),function(){if(("undefined"==typeof window?"undefined":Pa(window))!==t&&u){try{return void window.localStorage.removeItem(u)}catch(e){}try{window.document.cookie=encodeURIComponent(u)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},s.enableAll=function(e){s.setLevel(s.levels.TRACE,e)},s.disableAll=function(e){s.setLevel(s.levels.SILENT,e)};var f=l();null==f&&(f=n),s.setLevel(f,!1)}var f=new l,d={};f.getLogger=function(e){if("symbol"!==Pa(e)&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=d[e];return t||(t=d[e]=new l(e,f.getLevel(),f.methodFactory)),t};var p=("undefined"==typeof window?"undefined":Pa(window))!==t?window.log:void 0;return f.noConflict=function(){return("undefined"==typeof window?"undefined":Pa(window))!==t&&window.log===f&&(window.log=p),f},f.getLoggers=function(){return d},f.default=f,f},(kf=Sf).exports?kf.exports=_f():xf.log=_f();var Tf,Rf,Cf=Sf.exports.getLogger("twilio-conversations"),If=function(){function e(t){Ua(this,e),Ma(this,"prefix",""),this.prefix=null!=t&&t.length>0?t+" ":""}return Na(e,[{key:"setLevel",value:function(e){Cf.setLevel(e)}},{key:"trace",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.trace.apply(null,Ef(this.prefix+"T",t))}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.debug.apply(null,Ef(this.prefix+"D",t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.info.apply(null,Ef(this.prefix+"I",t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.warn.apply(null,Ef(this.prefix+"W",t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.error.apply(null,Ef(this.prefix+"E",t))}}],[{key:"scope",value:function(t){return new e(t)}},{key:"setLevel",value:function(e){Cf.setLevel(e)}},{key:"trace",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.trace.apply(null,Ef("T",t))}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.debug.apply(null,Ef("D",t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.info.apply(null,Ef("I",t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.warn.apply(null,Ef("W",t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];Cf.error.apply(null,Ef("E",t))}}]),e}(),Of={};Object.defineProperty(Of,"__esModule",{value:!0});var Pf=["weeks","years","months","days","hours","minutes","seconds"],Af=Of.pattern=new RegExp("P(?:(\\d+(?:[\\.,]\\d+)?W)|(\\d+(?:[\\.,]\\d+)?Y)?(\\d+(?:[\\.,]\\d+)?M)?(\\d+(?:[\\.,]\\d+)?D)?(?:T(\\d+(?:[\\.,]\\d+)?H)?(\\d+(?:[\\.,]\\d+)?M)?(\\d+(?:[\\.,]\\d+)?S)?)?)"),jf=Rf=Of.parse=function(e){return e.match(Af).slice(1).reduce((function(e,t,n){return e[Pf[n]]=parseFloat(t)||0,e}),{})},Mf=Of.end=function(e,t){var n=t?t.getTime():Date.now(),r=new Date(n);return r.setFullYear(r.getFullYear()+e.years),r.setMonth(r.getMonth()+e.months),r.setDate(r.getDate()+e.days),r.setHours(r.getHours()+e.hours),r.setMinutes(r.getMinutes()+e.minutes),r.setMilliseconds(r.getMilliseconds()+1e3*e.seconds),r.setDate(r.getDate()+7*e.weeks),r},Lf=Tf=Of.toSeconds=function(e,t){var n=t?t.getTime():Date.now(),r=new Date(n);return(Mf(e,r).getTime()-r.getTime())/1e3};function Nf(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 Uf(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Nf(Object(n),!0).forEach((function(t){Ma(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Nf(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}Of.default={end:Mf,toSeconds:Lf,pattern:Af,parse:jf};var Df="PT5S",Ff="PT5S",Bf=Na((function e(){var t,n,r,i,a,s,o,u,c=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},l=arguments.length>1?arguments[1]:void 0,f=arguments.length>2?arguments[2]:void 0;Ua(this,e),Ma(this,"typingIndicatorTimeoutDefault",5e3);var d=c.Chat||c.IPMessaging||c||{};this.productId=d.productId,this.links={myConversations:l.links.my_conversations,conversations:l.links.conversations,users:l.links.users,currentUser:l.links.current_user,typing:l.links.typing,mediaService:l.links.media_service,mediaSetService:l.links.media_set_service,messagesReceipts:l.links.messages_receipts},this.limits={mediaAttachmentsCountLimit:l.options.media_attachments_count_limit,mediaAttachmentSizeLimitInMb:l.options.media_attachment_size_limit_in_mb,mediaAttachmentsTotalSizeLimitInMb:l.options.media_attachments_total_size_limit_in_mb,emailHistoriesAllowedContentTypes:l.options.email_histories_allowed_mime_types,emailBodiesAllowedContentTypes:l.options.email_bodies_allowed_mime_types},this.typingIndicatorTimeoutOverride=d.typingIndicatorTimeoutOverride,this.backoffConfiguration=Uf({min:1e3,max:4e3,maxAttemptsCount:3},d.backoffConfigOverride),this.retryWhenThrottled=void 0===d.retryWhenThrottledOverride||d.retryWhenThrottledOverride,this.userInfosToSubscribe=null!==(t=null!==(n=d.userInfosToSubscribeOverride)&&void 0!==n?n:l.options.user_infos_to_subscribe)&&void 0!==t?t:100,this.reachabilityEnabled=l.options.reachability_enabled,this.userIdentity=l.identity,this.userInfo=l.sync_objects.my_user_info,this.myConversations=l.sync_objects.my_conversations;var p=null!==(r=null!==(i=d.httpCacheIntervalOverride)&&void 0!==i?i:l.options.http_cache_interval)&&void 0!==r?r:Df;try{this.httpCacheInterval=Tf(Rf(p))}catch(e){f.error("Failed to parse http cache interval ".concat(p,", using default value ").concat(Df)),this.httpCacheInterval=Tf(Rf(Df))}var h=null!==(a=null!==(s=d.consumptionReportIntervalOverride)&&void 0!==s?s:l.options.consumption_report_interval)&&void 0!==a?a:Ff;try{this.consumptionReportInterval=Tf(Rf(h))}catch(e){f.error("Failed to parse consumption report interval ".concat(h,", using default value ").concat(Ff)),this.consumptionReportInterval=Tf(Rf(Ff))}this.channelMetadataCacheCapacity=null!==(o=c.channelMetadataCacheCapacity)&&void 0!==o?o:100,this.messageRecipientsCacheCapacity=null!==(u=c.messageRecipientsCacheCapacity)&&void 0!==u?u:1e3})),qf=nr,zf=Ue,Wf=he("unscopables"),Gf=Array.prototype;null==Gf[Wf]&&zf.f(Gf,Wf,{configurable:!0,value:qf(null)});var $f=function(e){Gf[Wf][e]=!0},Vf=S,Jf=$f,Kf=cs,Hf=_t,Yf=pf,Qf="Array Iterator",Xf=Hf.set,Zf=Hf.getterFor(Qf),ed=Yf(Array,"Array",(function(e,t){Xf(this,{type:Qf,target:Vf(e),index:0,kind:t})}),(function(){var e=Zf(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?(e.target=void 0,{value:void 0,done:!0}):"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}}),"values");Kf.Arguments=Kf.Array,Jf("keys"),Jf("values"),Jf("entries");var td=a,nd=Zu,rd=nc,id=ed,ad=Je,sd=he,od=sd("iterator"),ud=sd("toStringTag"),cd=id.values,ld=function(e,t){if(e){if(e[od]!==cd)try{ad(e,od,cd)}catch(t){e[od]=cd}if(e[ud]||ad(e,ud,t),nd[t])for(var n in id)if(e[n]!==id[n])try{ad(e,n,id[n])}catch(t){e[n]=id[n]}}};for(var fd in nd)ld(td[fd]&&td[fd].prototype,fd);ld(rd,"DOMTokenList");var dd=Cn,pd=o,hd=C("JSON","stringify"),vd=/[\uD800-\uDFFF]/g,yd=/^[\uD800-\uDBFF]$/,md=/^[\uDC00-\uDFFF]$/,gd=function(e,t,n){var r=n.charAt(t-1),i=n.charAt(t+1);return yd.test(e)&&!md.test(i)||md.test(e)&&!yd.test(r)?"\\u"+e.charCodeAt(0).toString(16):e},bd=pd((function(){return'"\\udf06\\ud834"'!==hd("\udf06\ud834")||'"\\udead"'!==hd("\udead")}));hd&&dd({target:"JSON",stat:!0,forced:bd},{stringify:function(e,t,n){var r=hd.apply(null,arguments);return"string"==typeof r?r.replace(vd,gd):r}});var wd=E,kd=ns,xd=function(e,t,n){var r,i;return kd&&"function"==typeof(r=t.constructor)&&r!==n&&wd(i=r.prototype)&&i!==n.prototype&&kd(e,i),e},_d=k,Sd=Er,Ed="[\t\n\v\f\r \u2028\u2029\ufeff]",Td=RegExp("^"+Ed+Ed+"*"),Rd=RegExp(Ed+Ed+"*$"),Cd=function(e){return function(t){var n=Sd(_d(t));return 1&e&&(n=n.replace(Td,"")),2&e&&(n=n.replace(Rd,"")),n}},Id={start:Cd(1),end:Cd(2),trim:Cd(3)},Od=u,Pd=a,Ad=wn,jd=Ke.exports,Md=te,Ld=m,Nd=xd,Ud=z,Dd=be,Fd=o,Bd=nr,qd=At.f,zd=s.f,Wd=Ue.f,Gd=Id.trim,$d="Number",Vd=Pd.Number,Jd=Vd.prototype,Kd=Ld(Bd(Jd))==$d,Hd=function(e){if(Ud(e))throw TypeError("Cannot convert a Symbol value to a number");var t,n,r,i,a,s,o,u,c=Dd(e,"number");if("string"==typeof c&&c.length>2)if(43===(t=(c=Gd(c)).charCodeAt(0))||45===t){if(88===(n=c.charCodeAt(2))||120===n)return NaN}else if(48===t){switch(c.charCodeAt(1)){case 66:case 98:r=2,i=49;break;case 79:case 111:r=8,i=55;break;default:return+c}for(s=(a=c.slice(2)).length,o=0;o<s;o++)if((u=a.charCodeAt(o))<48||u>i)return NaN;return parseInt(a,r)}return+c};if(Ad($d,!Vd(" 0o1")||!Vd("0b1")||Vd("+0x1"))){for(var Yd,Qd=function(e){var t=arguments.length<1?0:e,n=this;return n instanceof Qd&&(Kd?Fd((function(){Jd.valueOf.call(n)})):Ld(n)!=$d)?Nd(new Vd(Hd(t)),n,Qd):Hd(t)},Xd=Od?qd(Vd):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,fromString,range".split(","),Zd=0;Xd.length>Zd;Zd++)Md(Vd,Yd=Xd[Zd])&&!Md(Qd,Yd)&&Wd(Qd,Yd,zd(Vd,Yd));Qd.prototype=Jd,Jd.constructor=Qd,jd(Pd,$d,Qd)}var ep=Fe,tp=function(){var e=ep(this),t="";return e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.sticky&&(t+="y"),t},np={},rp=o,ip=a.RegExp;np.UNSUPPORTED_Y=rp((function(){var e=ip("a","y");return e.lastIndex=2,null!=e.exec("abcd")})),np.BROKEN_CARET=rp((function(){var e=ip("^r","gy");return e.lastIndex=2,null!=e.exec("str")}));var ap,sp,op=o,up=a.RegExp,cp=op((function(){var e=up(".","s");return!(e.dotAll&&e.exec("\n")&&"s"===e.flags)})),lp=o,fp=a.RegExp,dp=lp((function(){var e=fp("(?<a>b)","g");return"b"!==e.exec("b").groups.a||"bc"!=="b".replace(e,"$<a>c")})),pp=Er,hp=tp,vp=np,yp=G.exports,mp=nr,gp=_t.get,bp=cp,wp=dp,kp=RegExp.prototype.exec,xp=yp("native-string-replace",String.prototype.replace),_p=kp,Sp=(ap=/a/,sp=/b*/g,kp.call(ap,"a"),kp.call(sp,"a"),0!==ap.lastIndex||0!==sp.lastIndex),Ep=vp.UNSUPPORTED_Y||vp.BROKEN_CARET,Tp=void 0!==/()??/.exec("")[1];(Sp||Tp||Ep||bp||wp)&&(_p=function(e){var t,n,r,i,a,s,o,u=this,c=gp(u),l=pp(e),f=c.raw;if(f)return f.lastIndex=u.lastIndex,t=_p.call(f,l),u.lastIndex=f.lastIndex,t;var d=c.groups,p=Ep&&u.sticky,h=hp.call(u),v=u.source,y=0,m=l;if(p&&(-1===(h=h.replace("y","")).indexOf("g")&&(h+="g"),m=l.slice(u.lastIndex),u.lastIndex>0&&(!u.multiline||u.multiline&&"\n"!==l.charAt(u.lastIndex-1))&&(v="(?: "+v+")",m=" "+m,y++),n=new RegExp("^(?:"+v+")",h)),Tp&&(n=new RegExp("^"+v+"$(?!\\s)",h)),Sp&&(r=u.lastIndex),i=kp.call(p?n:u,m),p?i?(i.input=i.input.slice(y),i[0]=i[0].slice(y),i.index=u.lastIndex,u.lastIndex+=i[0].length):u.lastIndex=0:Sp&&i&&(u.lastIndex=u.global?i.index+i[0].length:r),Tp&&i&&i.length>1&&xp.call(i[0],n,(function(){for(a=1;a<arguments.length-2;a++)void 0===arguments[a]&&(i[a]=void 0)})),i&&d)for(i.groups=s=mp(null),a=0;a<d.length;a++)s[(o=d[a])[0]]=i[o[1]];return i});var Rp=_p;Cn({target:"RegExp",proto:!0,forced:/./.exec!==Rp},{exec:Rp});var Cp=Ke.exports,Ip=Rp,Op=o,Pp=he,Ap=Je,jp=Pp("species"),Mp=RegExp.prototype,Lp=function(e,t,n,r){var i=Pp(e),a=!Op((function(){var t={};return t[i]=function(){return 7},7!=""[e](t)})),s=a&&!Op((function(){var t=!1,n=/a/;return"split"===e&&((n={}).constructor={},n.constructor[jp]=function(){return n},n.flags="",n[i]=/./[i]),n.exec=function(){return t=!0,null},n[i](""),!t}));if(!a||!s||n){var o=/./[i],u=t(i,""[e],(function(e,t,n,r,i){var s=t.exec;return s===Ip||s===Mp.exec?a&&!i?{done:!0,value:o.call(t,n,r)}:{done:!0,value:e.call(n,t,r)}:{done:!1}}));Cp(String.prototype,e,u[0]),Cp(Mp,i,u[1])}r&&Ap(Mp[i],"sham",!0)},Np=Il.charAt,Up=function(e,t,n){return t+(n?Np(e,t).length:1)},Dp=X,Fp=Math.floor,Bp="".replace,qp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,zp=/\$([$&'`]|\d{1,2})/g,Wp=m,Gp=Rp,$p=function(e,t){var n=e.exec;if("function"==typeof n){var r=n.call(e,t);if("object"!=typeof r)throw TypeError("RegExp exec method returned something other than an Object or null");return r}if("RegExp"!==Wp(e))throw TypeError("RegExp#exec called on incompatible receiver");return Gp.call(e,t)},Vp=Lp,Jp=o,Kp=Fe,Hp=Lt,Yp=Dt,Qp=Er,Xp=k,Zp=Up,eh=function(e,t,n,r,i,a){var s=n+e.length,o=r.length,u=zp;return void 0!==i&&(i=Dp(i),u=qp),Bp.call(a,u,(function(a,u){var c;switch(u.charAt(0)){case"$":return"$";case"&":return e;case"`":return t.slice(0,n);case"'":return t.slice(s);case"<":c=i[u.slice(1,-1)];break;default:var l=+u;if(0===l)return a;if(l>o){var f=Fp(l/10);return 0===f?a:f<=o?void 0===r[f-1]?u.charAt(1):r[f-1]+u.charAt(1):a}c=r[l-1]}return void 0===c?"":c}))},th=$p,nh=he("replace"),rh=Math.max,ih=Math.min,ah="$0"==="a".replace(/./,"$0"),sh=!!/./[nh]&&""===/./[nh]("a","$0"),oh=!Jp((function(){var e=/./;return e.exec=function(){var e=[];return e.groups={a:"7"},e},"7"!=="".replace(e,"$<a>")}));Vp("replace",(function(e,t,n){var r=sh?"$":"$0";return[function(e,n){var r=Xp(this),i=null==e?void 0:e[nh];return void 0!==i?i.call(e,r,n):t.call(Qp(r),e,n)},function(e,i){var a=Kp(this),s=Qp(e);if("string"==typeof i&&-1===i.indexOf(r)&&-1===i.indexOf("$<")){var o=n(t,a,s,i);if(o.done)return o.value}var u="function"==typeof i;u||(i=Qp(i));var c=a.global;if(c){var l=a.unicode;a.lastIndex=0}for(var f=[];;){var d=th(a,s);if(null===d)break;if(f.push(d),!c)break;""===Qp(d[0])&&(a.lastIndex=Zp(s,Yp(a.lastIndex),l))}for(var p,h="",v=0,y=0;y<f.length;y++){d=f[y];for(var m=Qp(d[0]),g=rh(ih(Hp(d.index),s.length),0),b=[],w=1;w<d.length;w++)b.push(void 0===(p=d[w])?p:String(p));var k=d.groups;if(u){var x=[m].concat(b,g,s);void 0!==k&&x.push(k);var _=Qp(i.apply(void 0,x))}else _=eh(m,s,g,b,k,i);g>=v&&(h+=s.slice(v,g)+_,v=g+m.length)}return h+s.slice(v)}]}),!oh||!ah||sh);var uh=Cn,ch=S,lh=[].join,fh=w!=Object,dh=ic("join",",");function ph(e){return JSON.parse(JSON.stringify(e))}function hh(e){return void 0===e||isNaN(Number(e))?null:Number(e)}function vh(e){try{return new Date(e)}catch(e){return null}}function yh(e,t,n){var r={};if(e)try{r=JSON.parse(e)}catch(e){n.warn(t,e)}return r}uh({target:"Array",proto:!0,forced:fh||!dh},{join:function(e){return lh.call(ch(this),void 0===e?",":e)}});var mh=function(){function e(t){Ua(this,e),this.base=t.replace(/\/$/,""),this.args=[],this.paths=[]}return Na(e,[{key:"arg",value:function(e,t){return void 0!==t&&this.args.push(encodeURIComponent(e)+"="+encodeURIComponent(t)),this}},{key:"path",value:function(e){return this.paths.push(encodeURIComponent(e)),this}},{key:"build",value:function(){var e=this.base;return this.paths.length&&(e+="/"+this.paths.join("/")),this.args.length&&(e+="?"+this.args.join("&")),e}}]),e}(),gh={},bh=Cn,wh=E,kh=_r,xh=zt,_h=Dt,Sh=S,Eh=ka,Th=he,Rh=la("slice"),Ch=Th("species"),Ih=[].slice,Oh=Math.max;bh({target:"Array",proto:!0,forced:!Rh},{slice:function(e,t){var n,r,i,a=Sh(this),s=_h(a.length),o=xh(e,s),u=xh(void 0===t?s:t,s);if(kh(a)&&("function"!=typeof(n=a.constructor)||n!==Array&&!kh(n.prototype)?wh(n)&&null===(n=n[Ch])&&(n=void 0):n=void 0,n===Array||void 0===n))return Ih.call(a,o,u);for(r=new(void 0===n?Array:n)(Oh(u-o,0)),i=0;o<u;o++,i++)o in a&&Eh(r,i,a[o]);return r.length=i,r}});var Ph=Cn,Ah=E,jh=function(){var e=!1,t=/[ac]/;return t.exec=function(){return e=!0,/./.exec.apply(this,arguments)},!0===t.test("abc")&&e}(),Mh=/./.test;Ph({target:"RegExp",proto:!0,forced:!jh},{test:function(e){if("function"!=typeof this.exec)return Mh.call(this,e);var t=this.exec(e);if(null!==t&&!Ah(t))throw new Error("RegExp exec method returned something other than an Object or null");return!!t}});var Lh=Cn,Nh=u,Uh=a,Dh=te,Fh=E,Bh=Ue.f,qh=dn,zh=Uh.Symbol;if(Nh&&"function"==typeof zh&&(!("description"in zh.prototype)||void 0!==zh().description)){var Wh={},Gh=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),t=this instanceof Gh?new zh(e):void 0===e?zh():zh(e);return""===e&&(Wh[t]=!0),t};qh(Gh,zh);var $h=Gh.prototype=zh.prototype;$h.constructor=Gh;var Vh=$h.toString,Jh="Symbol(test)"==String(zh("test")),Kh=/^Symbol\((.*)\)[^)]+$/;Bh($h,"description",{configurable:!0,get:function(){var e=Fh(this)?this.valueOf():this,t=Vh.call(e);if(Dh(Wh,e))return"";var n=Jh?t.slice(7,-1):t.replace(Kh,"$1");return""===n?void 0:n}}),Lh({global:!0,forced:!0},{Symbol:Gh})}Ur("iterator");var Hh={exports:{}};!function(e){function t(n){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(Hh);var Yh=u,Qh=Ue.f,Xh=Function.prototype,Zh=Xh.toString,ev=/^\s*function ([^ (]*)/,tv="name";Yh&&!(tv in Xh)&&Qh(Xh,tv,{configurable:!0,get:function(){try{return Zh.call(this).match(ev)[1]}catch(e){return""}}});var nv={exports:{}},rv={exports:{}};!function(e){e.exports=function(e){if(Array.isArray(e))return e},e.exports.__esModule=!0,e.exports.default=e.exports}(rv);var iv={exports:{}};!function(e){e.exports=function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a=[],s=!0,o=!1;try{for(n=n.call(e);!(s=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);s=!0);}catch(e){o=!0,i=e}finally{try{s||null==n.return||n.return()}finally{if(o)throw i}}return a}},e.exports.__esModule=!0,e.exports.default=e.exports}(iv);var av={exports:{}},sv={exports:{}};!function(e){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r},e.exports.__esModule=!0,e.exports.default=e.exports}(sv),function(e){var t=sv.exports;e.exports=function(e,n){if(e){if("string"==typeof e)return t(e,n);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?t(e,n):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports}(av);var ov={exports:{}};!function(e){e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports}(ov),function(e){var t=rv.exports,n=iv.exports,r=av.exports,i=ov.exports;e.exports=function(e,a){return t(e)||n(e,a)||r(e,a)||i()},e.exports.__esModule=!0,e.exports.default=e.exports}(nv);var uv={exports:{}},cv={exports:{}};!function(e){var t=sv.exports;e.exports=function(e){if(Array.isArray(e))return t(e)},e.exports.__esModule=!0,e.exports.default=e.exports}(cv);var lv={exports:{}};!function(e){e.exports=function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)},e.exports.__esModule=!0,e.exports.default=e.exports}(lv);var fv={exports:{}};!function(e){e.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports}(fv),function(e){var t=cv.exports,n=lv.exports,r=av.exports,i=fv.exports;e.exports=function(e){return t(e)||n(e)||r(e)||i()},e.exports.__esModule=!0,e.exports.default=e.exports}(uv);var dv={exports:{}};!function(e){function t(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)}}e.exports=function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e},e.exports.__esModule=!0,e.exports.default=e.exports}(dv);var pv={exports:{}};!function(e){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},e.exports.__esModule=!0,e.exports.default=e.exports}(pv);var hv={exports:{}},vv={exports:{}};!function(e){function t(n,r){return e.exports=t=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},e.exports.__esModule=!0,e.exports.default=e.exports,t(n,r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(vv),function(e){var t=vv.exports;e.exports=function(e,n){if("function"!=typeof n&&null!==n)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(n&&n.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),n&&t(e,n)},e.exports.__esModule=!0,e.exports.default=e.exports}(hv);var yv={exports:{}},mv={exports:{}};!function(e){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e},e.exports.__esModule=!0,e.exports.default=e.exports}(mv),function(e){var t=Hh.exports.default,n=mv.exports;e.exports=function(e,r){if(r&&("object"===t(r)||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined");return n(e)},e.exports.__esModule=!0,e.exports.default=e.exports}(yv);var gv={exports:{}};!function(e){function t(n){return e.exports=t=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},e.exports.__esModule=!0,e.exports.default=e.exports,t(n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(gv);var bv=Jt.includes,wv=$f;Cn({target:"Array",proto:!0},{includes:function(e){return bv(this,e,arguments.length>1?arguments[1]:void 0)}}),wv("includes");var kv=E,xv=Math.floor,_v=function(e){return!kv(e)&&isFinite(e)&&xv(e)===e};Cn({target:"Number",stat:!0},{isInteger:_v});var Sv=u,Ev=Fn,Tv=S,Rv=c.f,Cv=function(e){return function(t){for(var n,r=Tv(t),i=Ev(r),a=i.length,s=0,o=[];a>s;)n=i[s++],Sv&&!Rv.call(r,n)||o.push(e?[n,r[n]]:r[n]);return o}},Iv={entries:Cv(!0),values:Cv(!1)}.entries;Cn({target:"Object",stat:!0},{entries:function(e){return Iv(e)}}),Object.defineProperty(gh,"__esModule",{value:!0});var Ov=nv.exports,Pv=uv.exports,Av=dv.exports,jv=pv.exports,Mv=hv.exports,Lv=yv.exports,Nv=gv.exports;function Uv(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}var Dv=Uv(Hh.exports),Fv=Uv(Ov),Bv=Uv(Pv),qv=Uv(Av),zv=Uv(jv),Wv=Uv(Mv),Gv=Uv(Lv),$v=Uv(Nv),Vv=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return{checks:t}};function Jv(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return Kv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Kv(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function Kv(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var Hv=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Vv((function(e){var n,r=!1,i=[],a=Jv(t);try{for(a.s();!(n=a.n()).done;){var s=n.value;"string"!=typeof s?(r=r||e instanceof s,i.push("an instance of ".concat(s.name))):(r=r||Dv.default(e)===s,i.push("of type ".concat(s)))}}catch(e){a.e(e)}finally{a.f()}return[r,i]}))};function Yv(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return Qv(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Qv(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function Qv(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function Xv(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=$v.default(e);if(t){var i=$v.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Gv.default(this,n)}}function Zv(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return ey(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return ey(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function ey(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var ty=function(e,t){if(t.length>e.length)throw new Error("Expected at most ".concat(e.length," argument(s), but got ").concat(t.length));for(;t.length<e.length;)t.push(void 0);var n,r=Zv(t.entries());try{for(r.s();!(n=r.n()).done;){var i=Fv.default(n.value,2),a=i[0],s=i[1],o=ay(e[a],s),u=Fv.default(o,4),c=u[0],l=u[1],f=u[2],d=u[3];if(!c)throw new Error("Argument ".concat(a+1," is expected to be ").concat(f).concat(d," but got ").concat(l))}}catch(e){r.e(e)}finally{r.f()}},ny=function(e){var t,n,r;(["undefined","boolean","number","bigint","string"].includes(Dv.default(e))&&(n="string"==typeof e?'"'.concat(e,'"'):"".concat(e)),"object"===Dv.default(e)&&"Object"!==(null==e||null===(t=e.constructor)||void 0===t?void 0:t.name))&&(n=null===e?"null":"instance of ".concat(null==e||null===(r=e.constructor)||void 0===r?void 0:r.name));return n||(n=Dv.default(e)),n},ry=function(e){var t,n=[],r=Zv(e);try{for(r.s();!(t=r.n()).done;){var i=t.value;n.push(iy(i))}}catch(e){r.e(e)}finally{r.f()}return n},iy=function(e){var t,n=[],r=Zv(Array.isArray(e)?e:[e]);try{for(r.s();!(t=r.n()).done;){var i=t.value;"string"!=typeof i&&"function"!=typeof i?n.push(i):n.push(Hv(i))}}catch(e){r.e(e)}finally{r.f()}return n},ay=function(e,t){var n,r,i=[],a=!1,s=Zv(e);try{for(s.s();!(r=s.n()).done;){var o,u=Zv(r.value.checks);try{for(u.s();!(o=u.n()).done;){var c=(0,o.value)(t),l=Fv.default(c,3),f=l[0],d=l[1],p=l[2];a=a||f,!n&&p&&(n=p),d&&(i=[].concat(Bv.default(i),"string"==typeof d?[d]:Bv.default(d)))}}catch(e){u.e(e)}finally{u.f()}}}catch(e){s.e(e)}finally{s.f()}if(a)return[!0];var h=n||ny(t),v=i.length-1;return[!1,h,v>0?"".concat(i.slice(0,v).join(", ")," or ").concat(i[v]):i.join(", "),v>1?";":","]};function sy(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return oy(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return oy(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function oy(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var uy=Vv((function(e){return["string"==typeof e&&e.length>0,"a non-empty string"]})),cy=Vv((function(e){return["number"==typeof e&&Number.isInteger(e)&&e>=0,"a non-negative integer"]})),ly=Vv((function(e){return["object"===Dv.default(e)&&null!==e&&!Array.isArray(e),"a pure object (non-null and non-array)"]}));function fy(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return dy(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return dy(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function dy(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var py=gh.array=function(e,t){return Vv((function(n){if(!Array.isArray(n))return[!1,"an array of ".concat(e)];var r,i=fy(n.entries());try{for(i.s();!(r=i.n()).done;){var a=Fv.default(r.value,2),s=a[0],o=a[1],u=ay(iy(t),o),c=Fv.default(u,3),l=c[0],f=c[1],d=c[2];if(!l)return[!1,"a valid array of ".concat(e," (index ").concat(s," should be ").concat(d,")"),"malformed array of ".concat(e," (index ").concat(s," is ").concat(f,")")]}}catch(e){i.e(e)}finally{i.f()}return[!0]}))},hy=gh.custom=Vv,vy=gh.literal=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return Vv((function(e){var n,r=!1,i=[],a=Yv(t);try{for(a.s();!(n=a.n()).done;){var s=n.value;r=r||e===s,i.push("string"==typeof s?'"'.concat(s,'"'):"".concat(s))}}catch(e){a.e(e)}finally{a.f()}return[r,i]}))},yy=gh.nonEmptyArray=function(e,t){return Vv((function(n){if(!Array.isArray(n)||n.length<1)return[!1,"a non-empty array of ".concat(e)];var r,i=sy(n.entries());try{for(i.s();!(r=i.n()).done;){var a=Fv.default(r.value,2),s=a[0],o=a[1],u=ay(iy(t),o),c=Fv.default(u,3),l=c[0],f=c[1],d=c[2];if(!l)return[!1,"a valid non-empty array of ".concat(e," (index ").concat(s," should be ").concat(d,")"),"malformed array of ".concat(e," (index ").concat(s," is ").concat(f,")")]}}catch(e){i.e(e)}finally{i.f()}return[!0]}))},my=gh.nonEmptyString=uy,gy=gh.nonNegativeInteger=cy,by=gh.objectSchema=function(e,t){return Vv((function(n){if("object"!==Dv.default(n)||null===n||Array.isArray(n))return[!1,"valid ".concat(e," (should be a pure object)")];for(var r=0,i=Object.entries(t);r<i.length;r++){var a=Fv.default(i[r],2),s=a[0],o=a[1],u=ay(iy(o),n[s]),c=Fv.default(u,3),l=c[0],f=c[1],d=c[2];if(!l)return[!1,"valid ".concat(e,' (key "').concat(s,'" should be ').concat(d,")"),"malformed ".concat(e,' (key "').concat(s,'" is ').concat(f,")")]}return[!0]}))},wy=gh.pureObject=ly;gh.runtimeTypeValidation=ty,gh.stringifyReceivedType=ny,gh.type=Hv;var ky=gh.validateConstructorTypes=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=ry(t);return function(e){return function(e){Wv.default(n,e);var t=Xv(n);function n(){zv.default(this,n);for(var e=arguments.length,i=new Array(e),a=0;a<e;a++)i[a]=arguments[a];return ty(r,i),t.call.apply(t,[this].concat(i))}return qv.default(n)}(e)}},xy=gh.validateTypes=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=ry(t);return function(e,t,n){if("function"!=typeof n.value)throw new Error("The validateTypes decorator can only be applied to methods");var i=n.value;n.value=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return ty(r,t),i.apply(this,t)}}},_y=gh.validateTypesAsync=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=ry(t);return function(e,t,n){if("function"!=typeof n.value)throw new Error("The validateTypesAsync decorator can only be applied to methods");var i=n.value;n.value=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];try{ty(r,t)}catch(e){return Promise.reject(e)}return i.apply(this,t)}}};function Sy(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function Ey(e,t){if(e){if("string"==typeof e)return Sy(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Sy(e,t):void 0}}function Ty(e){return function(e){if(Array.isArray(e))return Sy(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||Ey(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var Ry=hy((function(e){return[["string","number","boolean","object"].includes(Pa(e)),"a JSON type"]})),Cy=hy((function(e){return[["undefined","string","number","boolean","object"].includes(Pa(e)),"an optional JSON type"]})),Iy=by("send media options",{contentType:[vy(null),"string"],filename:["string","undefined"],media:[vy("null"),"string"].concat(Ty("function"==typeof Buffer?[Buffer]:[]),Ty("function"==typeof Blob?[Blob]:[]))}),Oy={},Py={exports:{}},Ay={exports:{}};!function(e){var t=gv.exports;e.exports=function(e,n){for(;!Object.prototype.hasOwnProperty.call(e,n)&&null!==(e=t(e)););return e},e.exports.__esModule=!0,e.exports.default=e.exports}(Ay),function(e){var t=Ay.exports;function n(){return"undefined"!=typeof Reflect&&Reflect.get?(e.exports=n=Reflect.get,e.exports.__esModule=!0,e.exports.default=e.exports):(e.exports=n=function(e,n,r){var i=t(e,n);if(i){var a=Object.getOwnPropertyDescriptor(i,n);return a.get?a.get.call(arguments.length<3?e:r):a.value}},e.exports.__esModule=!0,e.exports.default=e.exports),n.apply(this,arguments)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Py);var jy={exports:{}};!function(e){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},e.exports.__esModule=!0,e.exports.default=e.exports}(jy),Object.defineProperty(Oy,"__esModule",{value:!0});var My=pv.exports,Ly=dv.exports,Ny=mv.exports,Uy=Py.exports,Dy=hv.exports,Fy=yv.exports,By=gv.exports,qy=jy.exports;function zy(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}var Wy=zy(uv.exports),Gy=zy(My),$y=zy(Ly),Vy=zy(Ny),Jy=zy(Uy),Ky=zy(Dy),Hy=zy(Fy),Yy=zy(By),Qy=zy(qy);function Xy(){}function Zy(){Zy.init.call(this)}function em(e){return void 0===e._maxListeners?Zy.defaultMaxListeners:e._maxListeners}function tm(e,t,n){if(t)e.call(n);else for(var r=e.length,i=cm(e,r),a=0;a<r;++a)i[a].call(n)}function nm(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,a=cm(e,i),s=0;s<i;++s)a[s].call(n,r)}function rm(e,t,n,r,i){if(t)e.call(n,r,i);else for(var a=e.length,s=cm(e,a),o=0;o<a;++o)s[o].call(n,r,i)}function im(e,t,n,r,i,a){if(t)e.call(n,r,i,a);else for(var s=e.length,o=cm(e,s),u=0;u<s;++u)o[u].call(n,r,i,a)}function am(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,a=cm(e,i),s=0;s<i;++s)a[s].apply(n,r)}function sm(e,t,n,r){var i,a,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),s=a[t]):(a=e._events=new Xy,e._eventsCount=0),s){if("function"==typeof s?s=a[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),!s.warned&&(i=em(e))&&i>0&&s.length>i){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,o=u,"function"==typeof console.warn?console.warn(o):console.log(o)}}else s=a[t]=n,++e._eventsCount;return e}function om(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function um(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function cm(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}function lm(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=Yy.default(e);if(t){var i=Yy.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Hy.default(this,n)}}Xy.prototype=Object.create(null),Zy.EventEmitter=Zy,Zy.usingDomains=!1,Zy.prototype.domain=void 0,Zy.prototype._events=void 0,Zy.prototype._maxListeners=void 0,Zy.defaultMaxListeners=10,Zy.init=function(){this.domain=null,Zy.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Xy,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Zy.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Zy.prototype.getMaxListeners=function(){return em(this)},Zy.prototype.emit=function(e){var t,n,r,i,a,s,o,u="error"===e;if(s=this._events)u=u&&null==s.error;else if(!u)return!1;if(o=this.domain,u){if(t=arguments[1],!o){if(t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=s[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:tm(n,l,this);break;case 2:nm(n,l,this,arguments[1]);break;case 3:rm(n,l,this,arguments[1],arguments[2]);break;case 4:im(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),a=1;a<r;a++)i[a-1]=arguments[a];am(n,l,this,i)}return!0},Zy.prototype.addListener=function(e,t){return sm(this,e,t,!1)},Zy.prototype.on=Zy.prototype.addListener,Zy.prototype.prependListener=function(e,t){return sm(this,e,t,!0)},Zy.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,om(this,e,t)),this},Zy.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,om(this,e,t)),this},Zy.prototype.removeListener=function(e,t){var n,r,i,a,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new Xy:(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new Xy,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}(n,i);r.removeListener&&this.emit("removeListener",e,s||t)}return this},Zy.prototype.off=function(e,t){return this.removeListener(e,t)},Zy.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new Xy,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new Xy:delete n[e]),this;if(0===arguments.length){for(var r,i=Object.keys(n),a=0;a<i.length;++a)"removeListener"!==(r=i[a])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new Xy,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},Zy.prototype.listeners=function(e){var t,n,r=this._events;return n=r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},Zy.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):um.call(e,t)},Zy.prototype.listenerCount=um,Zy.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var fm=function(e){Ky.default(n,e);var t=lm(n);function n(){var e;return Gy.default(this,n),e=t.call(this),Qy.default(Vy.default(e),"eventHistory",new Map),e}return $y.default(n,[{key:"on",value:function(e,t){return Jy.default(Yy.default(n.prototype),"on",this).call(this,e,t)}},{key:"once",value:function(e,t){return Jy.default(Yy.default(n.prototype),"once",this).call(this,e,t)}},{key:"off",value:function(e,t){return Jy.default(Yy.default(n.prototype),"off",this).call(this,e,t)}},{key:"emit",value:function(e){for(var t,r=arguments.length,i=new Array(r>1?r-1:0),a=1;a<r;a++)i[a-1]=arguments[a];return this.eventHistory.set(e,i),(t=Jy.default(Yy.default(n.prototype),"emit",this)).call.apply(t,[this,e].concat(i))}},{key:"addListener",value:function(e,t){return Jy.default(Yy.default(n.prototype),"addListener",this).call(this,e,t)}},{key:"removeListener",value:function(e,t){return Jy.default(Yy.default(n.prototype),"removeListener",this).call(this,e,t)}},{key:"addListenerWithReplay",value:function(e,t){var n=this.eventHistory.get(e);return void 0!==n&&t.apply(void 0,Wy.default(n)),this.addListener(e,t)}},{key:"onWithReplay",value:function(e,t){return this.addListenerWithReplay(e,t)}},{key:"onceWithReplay",value:function(e,t){var r=this.eventHistory.get(e);return void 0!==r?(t.apply(void 0,Wy.default(r)),this):Jy.default(Yy.default(n.prototype),"once",this).call(this,e,t)}}]),n}(Zy),dm=Oy.ReplayEventEmitter=fm,pm={exports:{}};!function(e,t){var r="__lodash_hash_undefined__",i=9007199254740991,a="[object Arguments]",s="[object Array]",o="[object Boolean]",u="[object Date]",c="[object Error]",l="[object Function]",f="[object Map]",d="[object Number]",p="[object Object]",h="[object Promise]",v="[object RegExp]",y="[object Set]",m="[object String]",g="[object Symbol]",b="[object WeakMap]",w="[object ArrayBuffer]",k="[object DataView]",x=/^\[object .+?Constructor\]$/,_=/^(?:0|[1-9]\d*)$/,S={};S["[object Float32Array]"]=S["[object Float64Array]"]=S["[object Int8Array]"]=S["[object Int16Array]"]=S["[object Int32Array]"]=S["[object Uint8Array]"]=S["[object Uint8ClampedArray]"]=S["[object Uint16Array]"]=S["[object Uint32Array]"]=!0,S[a]=S[s]=S[w]=S[o]=S[k]=S[u]=S[c]=S[l]=S[f]=S[d]=S[p]=S[v]=S[y]=S[m]=S[b]=!1;var E="object"==Pa(n)&&n&&n.Object===Object&&n,T="object"==("undefined"==typeof self?"undefined":Pa(self))&&self&&self.Object===Object&&self,R=E||T||Function("return this")(),C=t&&!t.nodeType&&t,I=C&&e&&!e.nodeType&&e,O=I&&I.exports===C,P=O&&E.process,A=function(){try{return P&&P.binding&&P.binding("util")}catch(e){}}(),j=A&&A.isTypedArray;function M(e,t){for(var n=-1,r=null==e?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function L(e,t){return e.has(t)}function N(e){var t=-1,n=Array(e.size);return e.forEach((function(e,r){n[++t]=[r,e]})),n}function U(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n}var D,F,B=Array.prototype,q=Function.prototype,z=Object.prototype,W=R["__core-js_shared__"],G=q.toString,$=z.hasOwnProperty,V=function(){var e=/[^.]+$/.exec(W&&W.keys&&W.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}(),J=z.toString,K=RegExp("^"+G.call($).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),H=O?R.Buffer:void 0,Y=R.Symbol,Q=R.Uint8Array,X=z.propertyIsEnumerable,Z=B.splice,ee=Y?Y.toStringTag:void 0,te=Object.getOwnPropertySymbols,ne=H?H.isBuffer:void 0,re=(D=Object.keys,F=Object,function(e){return D(F(e))}),ie=Ae(R,"DataView"),ae=Ae(R,"Map"),se=Ae(R,"Promise"),oe=Ae(R,"Set"),ue=Ae(R,"WeakMap"),ce=Ae(Object,"create"),le=Ne(ie),fe=Ne(ae),de=Ne(se),pe=Ne(oe),he=Ne(ue),ve=Y?Y.prototype:void 0,ye=ve?ve.valueOf:void 0;function me(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function ge(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function be(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function we(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new be;++t<n;)this.add(e[t])}function ke(e){var t=this.__data__=new ge(e);this.size=t.size}function xe(e,t){var n=Fe(e),r=!n&&De(e),i=!n&&!r&&Be(e),a=!n&&!r&&!i&&$e(e),s=n||r||i||a,o=s?function(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}(e.length,String):[],u=o.length;for(var c in e)!t&&!$.call(e,c)||s&&("length"==c||i&&("offset"==c||"parent"==c)||a&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||Le(c,u))||o.push(c);return o}function _e(e,t){for(var n=e.length;n--;)if(Ue(e[n][0],t))return n;return-1}function Se(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ee&&ee in Object(e)?function(e){var t=$.call(e,ee),n=e[ee];try{e[ee]=void 0;var r=!0}catch(e){}var i=J.call(e);r&&(t?e[ee]=n:delete e[ee]);return i}(e):function(e){return J.call(e)}(e)}function Ee(e){return Ge(e)&&Se(e)==a}function Te(e,t,n,r,i){return e===t||(null==e||null==t||!Ge(e)&&!Ge(t)?e!=e&&t!=t:function(e,t,n,r,i,l){var h=Fe(e),b=Fe(t),x=h?s:Me(e),_=b?s:Me(t),S=(x=x==a?p:x)==p,E=(_=_==a?p:_)==p,T=x==_;if(T&&Be(e)){if(!Be(t))return!1;h=!0,S=!1}if(T&&!S)return l||(l=new ke),h||$e(e)?Ie(e,t,n,r,i,l):function(e,t,n,r,i,a,s){switch(n){case k:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case w:return!(e.byteLength!=t.byteLength||!a(new Q(e),new Q(t)));case o:case u:case d:return Ue(+e,+t);case c:return e.name==t.name&&e.message==t.message;case v:case m:return e==t+"";case f:var l=N;case y:var p=1&r;if(l||(l=U),e.size!=t.size&&!p)return!1;var h=s.get(e);if(h)return h==t;r|=2,s.set(e,t);var b=Ie(l(e),l(t),r,i,a,s);return s.delete(e),b;case g:if(ye)return ye.call(e)==ye.call(t)}return!1}(e,t,x,n,r,i,l);if(!(1&n)){var R=S&&$.call(e,"__wrapped__"),C=E&&$.call(t,"__wrapped__");if(R||C){var I=R?e.value():e,O=C?t.value():t;return l||(l=new ke),i(I,O,n,r,l)}}if(!T)return!1;return l||(l=new ke),function(e,t,n,r,i,a){var s=1&n,o=Oe(e),u=o.length,c=Oe(t).length;if(u!=c&&!s)return!1;var l=u;for(;l--;){var f=o[l];if(!(s?f in t:$.call(t,f)))return!1}var d=a.get(e);if(d&&a.get(t))return d==t;var p=!0;a.set(e,t),a.set(t,e);var h=s;for(;++l<u;){var v=e[f=o[l]],y=t[f];if(r)var m=s?r(y,v,f,t,e,a):r(v,y,f,e,t,a);if(!(void 0===m?v===y||i(v,y,n,r,a):m)){p=!1;break}h||(h="constructor"==f)}if(p&&!h){var g=e.constructor,b=t.constructor;g==b||!("constructor"in e)||!("constructor"in t)||"function"==typeof g&&g instanceof g&&"function"==typeof b&&b instanceof b||(p=!1)}return a.delete(e),a.delete(t),p}(e,t,n,r,i,l)}(e,t,n,r,Te,i))}function Re(e){return!(!We(e)||function(e){return!!V&&V in e}(e))&&(qe(e)?K:x).test(Ne(e))}function Ce(e){if(n=(t=e)&&t.constructor,r="function"==typeof n&&n.prototype||z,t!==r)return re(e);var t,n,r,i=[];for(var a in Object(e))$.call(e,a)&&"constructor"!=a&&i.push(a);return i}function Ie(e,t,n,r,i,a){var s=1&n,o=e.length,u=t.length;if(o!=u&&!(s&&u>o))return!1;var c=a.get(e);if(c&&a.get(t))return c==t;var l=-1,f=!0,d=2&n?new we:void 0;for(a.set(e,t),a.set(t,e);++l<o;){var p=e[l],h=t[l];if(r)var v=s?r(h,p,l,t,e,a):r(p,h,l,e,t,a);if(void 0!==v){if(v)continue;f=!1;break}if(d){if(!M(t,(function(e,t){if(!L(d,t)&&(p===e||i(p,e,n,r,a)))return d.push(t)}))){f=!1;break}}else if(p!==h&&!i(p,h,n,r,a)){f=!1;break}}return a.delete(e),a.delete(t),f}function Oe(e){return function(e,t,n){var r=t(e);return Fe(e)?r:function(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e}(r,n(e))}(e,Ve,je)}function Pe(e,t){var n=e.__data__;return function(e){var t=Pa(e);return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}(t)?n["string"==typeof t?"string":"hash"]:n.map}function Ae(e,t){var n=function(e,t){return null==e?void 0:e[t]}(e,t);return Re(n)?n:void 0}me.prototype.clear=function(){this.__data__=ce?ce(null):{},this.size=0},me.prototype.delete=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},me.prototype.get=function(e){var t=this.__data__;if(ce){var n=t[e];return n===r?void 0:n}return $.call(t,e)?t[e]:void 0},me.prototype.has=function(e){var t=this.__data__;return ce?void 0!==t[e]:$.call(t,e)},me.prototype.set=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=ce&&void 0===t?r:t,this},ge.prototype.clear=function(){this.__data__=[],this.size=0},ge.prototype.delete=function(e){var t=this.__data__,n=_e(t,e);return!(n<0)&&(n==t.length-1?t.pop():Z.call(t,n,1),--this.size,!0)},ge.prototype.get=function(e){var t=this.__data__,n=_e(t,e);return n<0?void 0:t[n][1]},ge.prototype.has=function(e){return _e(this.__data__,e)>-1},ge.prototype.set=function(e,t){var n=this.__data__,r=_e(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this},be.prototype.clear=function(){this.size=0,this.__data__={hash:new me,map:new(ae||ge),string:new me}},be.prototype.delete=function(e){var t=Pe(this,e).delete(e);return this.size-=t?1:0,t},be.prototype.get=function(e){return Pe(this,e).get(e)},be.prototype.has=function(e){return Pe(this,e).has(e)},be.prototype.set=function(e,t){var n=Pe(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this},we.prototype.add=we.prototype.push=function(e){return this.__data__.set(e,r),this},we.prototype.has=function(e){return this.__data__.has(e)},ke.prototype.clear=function(){this.__data__=new ge,this.size=0},ke.prototype.delete=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},ke.prototype.get=function(e){return this.__data__.get(e)},ke.prototype.has=function(e){return this.__data__.has(e)},ke.prototype.set=function(e,t){var n=this.__data__;if(n instanceof ge){var r=n.__data__;if(!ae||r.length<199)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new be(r)}return n.set(e,t),this.size=n.size,this};var je=te?function(e){return null==e?[]:(e=Object(e),function(e,t){for(var n=-1,r=null==e?0:e.length,i=0,a=[];++n<r;){var s=e[n];t(s,n,e)&&(a[i++]=s)}return a}(te(e),(function(t){return X.call(e,t)})))}:function(){return[]},Me=Se;function Le(e,t){return!!(t=null==t?i:t)&&("number"==typeof e||_.test(e))&&e>-1&&e%1==0&&e<t}function Ne(e){if(null!=e){try{return G.call(e)}catch(e){}try{return e+""}catch(e){}}return""}function Ue(e,t){return e===t||e!=e&&t!=t}(ie&&Me(new ie(new ArrayBuffer(1)))!=k||ae&&Me(new ae)!=f||se&&Me(se.resolve())!=h||oe&&Me(new oe)!=y||ue&&Me(new ue)!=b)&&(Me=function(e){var t=Se(e),n=t==p?e.constructor:void 0,r=n?Ne(n):"";if(r)switch(r){case le:return k;case fe:return f;case de:return h;case pe:return y;case he:return b}return t});var De=Ee(function(){return arguments}())?Ee:function(e){return Ge(e)&&$.call(e,"callee")&&!X.call(e,"callee")},Fe=Array.isArray;var Be=ne||function(){return!1};function qe(e){if(!We(e))return!1;var t=Se(e);return t==l||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t}function ze(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=i}function We(e){var t=Pa(e);return null!=e&&("object"==t||"function"==t)}function Ge(e){return null!=e&&"object"==Pa(e)}var $e=j?function(e){return function(t){return e(t)}}(j):function(e){return Ge(e)&&ze(e.length)&&!!S[Se(e)]};function Ve(e){return null!=(t=e)&&ze(t.length)&&!qe(t)?xe(e):Ce(e);var t}e.exports=function(e,t){return Te(e,t)}}(pm,pm.exports);var hm=pm.exports;function vm(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}var ym=If.scope("User"),User=function(e){Oa(User,e);var t,n,r,i,a,s,o,u=vm(User);function User(e,t,n,r){var i;return Ua(this,User),Ma(Ca(i=u.call(this)),"promiseToFetch",null),Ma(Ca(i),"updated","updated"),Ma(Ca(i),"userSubscribed","userSubscribed"),Ma(Ca(i),"userUnsubscribed","userUnsubscribed"),i.services=r,i.subscribed="initializing",i.setMaxListeners(0),i.state={identity:e,entityName:t,friendlyName:null,attributes:{},online:null,notifiable:null},i._initializationPromise=new Promise((function(e){i._resolveInitializationPromise=e})),null!==n&&i._resolveInitialization(n,e,t,!1),i}return Na(User,[{key:"identity",get:function(){return this.state.identity},set:function(e){this.state.identity=e}},{key:"entityName",set:function(e){this.state.entityName=e}},{key:"attributes",get:function(){return this.state.attributes}},{key:"friendlyName",get:function(){return this.state.friendlyName}},{key:"isOnline",get:function(){return this.state.online}},{key:"isNotifiable",get:function(){return this.state.notifiable}},{key:"isSubscribed",get:function(){return"subscribed"==this.subscribed}},{key:"_update",value:(o=Ra(Gc.mark((function e(t,n){var r,i;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._initializationPromise;case 2:r=[],ym.debug("User for",this.state.identity,"updated:",t,n),e.t0=t,e.next="friendlyName"===e.t0?7:"attributes"===e.t0?9:"reachability"===e.t0?12:15;break;case 7:return this.state.friendlyName!==n.value&&(r.push("friendlyName"),this.state.friendlyName=n.value),e.abrupt("break",16);case 9:return i=yh(n.value,"Retrieved malformed attributes from the server for user: ".concat(this.state.identity),ym),hm(this.state.attributes,i)||(this.state.attributes=i,r.push("attributes")),e.abrupt("break",16);case 12:return this.state.online!==n.online&&(this.state.online=n.online,r.push("reachabilityOnline")),this.state.notifiable!==n.notifiable&&(this.state.notifiable=n.notifiable,r.push("reachabilityNotifiable")),e.abrupt("break",16);case 15:return e.abrupt("return");case 16:r.length>0&&this.emit("updated",{user:this,updateReasons:r});case 17:case"end":return e.stop()}}),e,this)}))),function(e,t){return o.apply(this,arguments)})},{key:"_updateReachabilityInfo",value:(s=Ra(Gc.mark((function e(t,n){var r=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._initializationPromise;case 2:if(this.configuration.reachabilityEnabled){e.next=4;break}return e.abrupt("return",Promise.resolve());case 4:return e.abrupt("return",t.get("reachability").then(n).catch((function(e){ym.warn("Failed to get reachability info for ",r.state.identity,e)})));case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return s.apply(this,arguments)})},{key:"_fetch",value:(a=Ra(Gc.mark((function e(){var t=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._initializationPromise;case 2:if(this.state.entityName){e.next=4;break}return e.abrupt("return",this);case 4:return this.promiseToFetch=this.services.syncClient.map({id:this.state.entityName,mode:"open_existing",includeItems:!0}).then((function(e){return t.entity=e,e.on("itemUpdated",(function(e){return ym.debug(t.state.entityName+" ("+t.state.identity+") itemUpdated: "+e.item.key),t._update(e.item.key,e.item.data)})),e.on("itemAdded",(function(e){return ym.debug(t.state.entityName+" ("+t.state.identity+") itemAdded: "+e.item.key),t._update(e.item.key,e.item.data)})),Promise.all([e.get("friendlyName").then((function(e){return t._update(e.key,e.data)})),e.get("attributes").then((function(e){return t._update(e.key,e.data)})),t._updateReachabilityInfo(e,(function(e){return t._update(e.key,e.data)}))])})).then((function(){return ym.debug("Fetched for",t.identity),t.subscribed="subscribed",t.emit("userSubscribed",t),t})).catch((function(e){throw t.promiseToFetch=null,e})),e.abrupt("return",this.promiseToFetch);case 6:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"_ensureFetched",value:(i=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._initializationPromise;case 2:return e.abrupt("return",this.promiseToFetch||this._fetch());case 3:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"updateAttributes",value:(r=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._initializationPromise;case 2:if("unsubscribed"!=this.subscribed){e.next=4;break}throw new Error("Can't modify unsubscribed object");case 4:return e.next=6,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(t)});case 6:return e.abrupt("return",this);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"updateFriendlyName",value:(n=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._initializationPromise;case 2:if("unsubscribed"!=this.subscribed){e.next=4;break}throw new Error("Can't modify unsubscribed object");case 4:return e.next=6,this.services.commandExecutor.mutateResource("post",this.links.self,{friendly_name:t});case 6:return e.abrupt("return",this);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"unsubscribe",value:(t=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._initializationPromise;case 2:if(!this.promiseToFetch){e.next=9;break}return e.next=5,this.promiseToFetch;case 5:this.entity.close(),this.promiseToFetch=null,this.subscribed="unsubscribed",this.emit("userUnsubscribed",this);case 9:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"_resolveInitialization",value:function(e,t,n,r){this.configuration=e,this.identity=t,this.entityName=n,this.links={self:"".concat(this.configuration.links.users,"/").concat(encodeURIComponent(this.identity))},this._resolveInitializationPromise(),r&&this.emit("updated",{user:this,updateReasons:["friendlyName","attributes","reachabilityOnline","reachabilityNotifiable"]})}}]),User}(dm);function mm(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,a=[],s=!0,o=!1;try{for(n=n.call(e);!(s=(r=n.next()).done)&&(a.push(r.value),!t||a.length!==t);s=!0);}catch(e){o=!0,i=e}finally{try{s||null==n.return||n.return()}finally{if(o)throw i}}return a}}(e,t)||Ey(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}Vc([_y(Ry),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Promise)],User.prototype,"updateAttributes",null),Vc([_y(["string"]),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],User.prototype,"updateFriendlyName",null);var gm={exports:{}},bm=!o((function(){return Object.isExtensible(Object.preventExtensions({}))})),wm=Cn,km=ut,xm=E,_m=te,Sm=Ue.f,Em=At,Tm=Tr,Rm=bm,Cm=!1,Im=ie("meta"),Om=0,Pm=Object.isExtensible||function(){return!0},Am=function(e){Sm(e,Im,{value:{objectID:"O"+Om++,weakData:{}}})},jm=gm.exports={enable:function(){jm.enable=function(){},Cm=!0;var e=Em.f,t=[].splice,n={};n[Im]=1,e(n).length&&(Em.f=function(n){for(var r=e(n),i=0,a=r.length;i<a;i++)if(r[i]===Im){t.call(r,i,1);break}return r},wm({target:"Object",stat:!0,forced:!0},{getOwnPropertyNames:Tm.f}))},fastKey:function(e,t){if(!xm(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!_m(e,Im)){if(!Pm(e))return"F";if(!t)return"E";Am(e)}return e[Im].objectID},getWeakData:function(e,t){if(!_m(e,Im)){if(!Pm(e))return!0;if(!t)return!1;Am(e)}return e[Im].weakData},onFreeze:function(e){return Rm&&Cm&&Pm(e)&&!_m(e,Im)&&Am(e),e}};km[Im]=!0;var Mm=Cn,Lm=a,Nm=wn,Um=Ke.exports,Dm=gm.exports,Fm=Ps,Bm=us,qm=E,zm=o,Wm=Bs,Gm=An,$m=xd,Vm=function(e,t,n){var r=-1!==e.indexOf("Map"),i=-1!==e.indexOf("Weak"),a=r?"set":"add",s=Lm[e],o=s&&s.prototype,u=s,c={},l=function(e){var t=o[e];Um(o,e,"add"==e?function(e){return t.call(this,0===e?0:e),this}:"delete"==e?function(e){return!(i&&!qm(e))&&t.call(this,0===e?0:e)}:"get"==e?function(e){return i&&!qm(e)?void 0:t.call(this,0===e?0:e)}:"has"==e?function(e){return!(i&&!qm(e))&&t.call(this,0===e?0:e)}:function(e,n){return t.call(this,0===e?0:e,n),this})};if(Nm(e,"function"!=typeof s||!(i||o.forEach&&!zm((function(){(new s).entries().next()})))))u=n.getConstructor(t,e,r,a),Dm.enable();else if(Nm(e,!0)){var f=new u,d=f[a](i?{}:-0,1)!=f,p=zm((function(){f.has(1)})),h=Wm((function(e){new s(e)})),v=!i&&zm((function(){for(var e=new s,t=5;t--;)e[a](t,t);return!e.has(-0)}));h||((u=t((function(t,n){Bm(t,u,e);var i=$m(new s,t,u);return null!=n&&Fm(n,i[a],{that:i,AS_ENTRIES:r}),i}))).prototype=o,o.constructor=u),(p||v)&&(l("delete"),l("has"),r&&l("get")),(v||d)&&l(a),i&&o.clear&&delete o.clear}return c[e]=u,Mm({global:!0,forced:u!=s},c),Gm(u,e),i||n.setStrong(u,e,r),u},Jm=Ue.f,Km=nr,Hm=Xa,Ym=Fr,Qm=us,Xm=Ps,Zm=pf,eg=os,tg=u,ng=gm.exports.fastKey,rg=_t.set,ig=_t.getterFor,ag={getConstructor:function(e,t,n,r){var i=e((function(e,a){Qm(e,i,t),rg(e,{type:t,index:Km(null),first:void 0,last:void 0,size:0}),tg||(e.size=0),null!=a&&Xm(a,e[r],{that:e,AS_ENTRIES:n})})),a=ig(t),s=function(e,t,n){var r,i,s=a(e),u=o(e,t);return u?u.value=n:(s.last=u={index:i=ng(t,!0),key:t,value:n,previous:r=s.last,next:void 0,removed:!1},s.first||(s.first=u),r&&(r.next=u),tg?s.size++:e.size++,"F"!==i&&(s.index[i]=u)),e},o=function(e,t){var n,r=a(e),i=ng(t);if("F"!==i)return r.index[i];for(n=r.first;n;n=n.next)if(n.key==t)return n};return Hm(i.prototype,{clear:function(){for(var e=a(this),t=e.index,n=e.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete t[n.index],n=n.next;e.first=e.last=void 0,tg?e.size=0:this.size=0},delete:function(e){var t=this,n=a(t),r=o(t,e);if(r){var i=r.next,s=r.previous;delete n.index[r.index],r.removed=!0,s&&(s.next=i),i&&(i.previous=s),n.first==r&&(n.first=i),n.last==r&&(n.last=s),tg?n.size--:t.size--}return!!r},forEach:function(e){for(var t,n=a(this),r=Ym(e,arguments.length>1?arguments[1]:void 0,3);t=t?t.next:n.first;)for(r(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!o(this,e)}}),Hm(i.prototype,n?{get:function(e){var t=o(this,e);return t&&t.value},set:function(e,t){return s(this,0===e?0:e,t)}}:{add:function(e){return s(this,e=0===e?0:e,e)}}),tg&&Jm(i.prototype,"size",{get:function(){return a(this).size}}),i},setStrong:function(e,t,n){var r=t+" Iterator",i=ig(t),a=ig(r);Zm(e,t,(function(e,t){rg(this,{type:r,target:e,state:i(e),kind:t,last:void 0})}),(function(){for(var e=a(this),t=e.kind,n=e.last;n&&n.removed;)n=n.previous;return e.target&&(e.last=n=n?n.next:e.state.first)?"keys"==t?{value:n.key,done:!1}:"values"==t?{value:n.value,done:!1}:{value:[n.key,n.value],done:!1}:(e.target=void 0,{value:void 0,done:!0})}),n?"entries":"values",!n,!0),eg(t)}};Vm("Map",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),ag);var sg={};Object.defineProperty(sg,"__esModule",{value:!0});var og=dv.exports,ug=mv.exports,cg=hv.exports,lg=yv.exports,fg=gv.exports,dg=jy.exports;function pg(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}var hg=pg(pv.exports),vg=pg(og),yg=pg(ug),mg=pg(cg),gg=pg(lg),bg=pg(fg),wg=pg(dg);function kg(){}function xg(){xg.init.call(this)}function _g(e){return void 0===e._maxListeners?xg.defaultMaxListeners:e._maxListeners}function Sg(e,t,n){if(t)e.call(n);else for(var r=e.length,i=Ag(e,r),a=0;a<r;++a)i[a].call(n)}function Eg(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,a=Ag(e,i),s=0;s<i;++s)a[s].call(n,r)}function Tg(e,t,n,r,i){if(t)e.call(n,r,i);else for(var a=e.length,s=Ag(e,a),o=0;o<a;++o)s[o].call(n,r,i)}function Rg(e,t,n,r,i,a){if(t)e.call(n,r,i,a);else for(var s=e.length,o=Ag(e,s),u=0;u<s;++u)o[u].call(n,r,i,a)}function Cg(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,a=Ag(e,i),s=0;s<i;++s)a[s].apply(n,r)}function Ig(e,t,n,r){var i,a,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),s=a[t]):(a=e._events=new kg,e._eventsCount=0),s){if("function"==typeof s?s=a[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),!s.warned&&(i=_g(e))&&i>0&&s.length>i){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,o=u,"function"==typeof console.warn?console.warn(o):console.log(o)}}else s=a[t]=n,++e._eventsCount;return e}function Og(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function Pg(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function Ag(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}function jg(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=bg.default(e);if(t){var i=bg.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return gg.default(this,n)}}kg.prototype=Object.create(null),xg.EventEmitter=xg,xg.usingDomains=!1,xg.prototype.domain=void 0,xg.prototype._events=void 0,xg.prototype._maxListeners=void 0,xg.defaultMaxListeners=10,xg.init=function(){this.domain=null,xg.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new kg,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},xg.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},xg.prototype.getMaxListeners=function(){return _g(this)},xg.prototype.emit=function(e){var t,n,r,i,a,s,o,u="error"===e;if(s=this._events)u=u&&null==s.error;else if(!u)return!1;if(o=this.domain,u){if(t=arguments[1],!o){if(t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=s[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:Sg(n,l,this);break;case 2:Eg(n,l,this,arguments[1]);break;case 3:Tg(n,l,this,arguments[1],arguments[2]);break;case 4:Rg(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),a=1;a<r;a++)i[a-1]=arguments[a];Cg(n,l,this,i)}return!0},xg.prototype.addListener=function(e,t){return Ig(this,e,t,!1)},xg.prototype.on=xg.prototype.addListener,xg.prototype.prependListener=function(e,t){return Ig(this,e,t,!0)},xg.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,Og(this,e,t)),this},xg.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,Og(this,e,t)),this},xg.prototype.removeListener=function(e,t){var n,r,i,a,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new kg:(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new kg,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}(n,i);r.removeListener&&this.emit("removeListener",e,s||t)}return this},xg.prototype.off=function(e,t){return this.removeListener(e,t)},xg.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new kg,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new kg:delete n[e]),this;if(0===arguments.length){for(var r,i=Object.keys(n),a=0;a<i.length;++a)"removeListener"!==(r=i[a])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new kg,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},xg.prototype.listeners=function(e){var t,n,r=this._events;return n=r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},xg.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):Pg.call(e,t)},xg.prototype.listenerCount=Pg,xg.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var Mg=function(e){mg.default(n,e);var t=jg(n);function n(e){var r;return hg.default(this,n),r=t.call(this),wg.default(yg.default(r),"timeout",null),wg.default(yg.default(r),"startTimestamp",-1),r.minDelay=e.min,r.maxDelay=e.max,r.initialDelay=e.initial||0,r.maxAttemptsCount=e.maxAttemptsCount||0,r.maxAttemptsTime=e.maxAttemptsTime||0,r.randomness=e.randomness||0,r.inProgress=!1,r.attemptNum=0,r.prevDelay=0,r.currDelay=0,r}return vg.default(n,[{key:"attempt",value:function(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.attemptNum++,this.emit("attempt",this)}},{key:"nextDelay",value:function(e){if("number"==typeof e)return this.prevDelay=0,this.currDelay=e,e;if(0==this.attemptNum)return this.initialDelay;if(1==this.attemptNum)return this.currDelay=this.minDelay,this.currDelay;this.prevDelay=this.currDelay;var t=this.currDelay+this.prevDelay;return this.maxDelay&&t>this.maxDelay&&(this.currDelay=this.maxDelay,t=this.maxDelay),this.currDelay=t,t}},{key:"randomize",value:function(e){var t=e*this.randomness,n=Math.round(Math.random()*t*2-t);return Math.max(0,e+n)}},{key:"scheduleAttempt",value:function(e){var t=this;if(this.maxAttemptsCount&&this.attemptNum>=this.maxAttemptsCount)return this.cleanup(),void this.emit("failed",new Error("Maximum attempt count limit reached"));var n=this.nextDelay(e);if(n=this.randomize(n),this.maxAttemptsTime&&this.startTimestamp+this.maxAttemptsTime<Date.now()+n)return this.cleanup(),void this.emit("failed",new Error("Maximum attempt time limit reached"));this.timeout=setTimeout((function(){return t.attempt()}),n)}},{key:"cleanup",value:function(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.inProgress=!1,this.attemptNum=0,this.prevDelay=0,this.currDelay=0}},{key:"start",value:function(){if(this.inProgress)throw new Error("Retrier is already in progress");this.inProgress=!0,this.startTimestamp=Date.now(),this.scheduleAttempt(this.initialDelay)}},{key:"cancel",value:function(){this.timeout&&(clearTimeout(this.timeout),this.timeout=null,this.inProgress=!1,this.emit("cancelled"))}},{key:"succeeded",value:function(e){this.emit("succeeded",e)}},{key:"failed",value:function(e,t){if(this.timeout)throw new Error("Retrier attempt is already in progress");this.scheduleAttempt(t)}}]),n}(xg),Lg=function(e){mg.default(n,e);var t=jg(n);function n(e){var r;return hg.default(this,n),r=t.call(this),wg.default(yg.default(r),"resolve",(function(){})),wg.default(yg.default(r),"reject",(function(){})),r.retrier=new Mg(e),r}return vg.default(n,[{key:"run",value:function(e){var t=this;return this.retrier.on("attempt",(function(){e().then((function(e){return t.retrier.succeeded(e)})).catch((function(e){return t.retrier.failed(e)}))})),this.retrier.on("succeeded",(function(e){return t.resolve(e)})),this.retrier.on("cancelled",(function(){return t.reject(new Error("Cancelled"))})),this.retrier.on("failed",(function(e){return t.reject(e)})),new Promise((function(e,n){t.resolve=e,t.reject=n,t.retrier.start()}))}},{key:"cancel",value:function(){this.retrier.cancel()}}]),n}(xg);function Ng(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=bg.default(e);if(t){var i=bg.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return gg.default(this,n)}}function Ug(e){return null!=e}var Dg=function(e){mg.default(n,e);var t=Ng(n);function n(e){var r;hg.default(this,n),r=t.call(this),wg.default(yg.default(r),"backoffDelay",0),wg.default(yg.default(r),"nextBackoffDelay",0),wg.default(yg.default(r),"backoffNumber",0),wg.default(yg.default(r),"timeoutID",null),wg.default(yg.default(r),"maxNumberOfRetry",-1);var i=e=e||{},a=i.initialDelay,s=i.maxDelay,o=i.randomisationFactor,u=i.factor;if(Ug(a)&&a<1)throw new Error("The initial timeout must be equal to or greater than 1.");if(Ug(s)&&s<=1)throw new Error("The maximal timeout must be greater than 1.");if(Ug(o)&&(o<0||o>1))throw new Error("The randomisation factor must be between 0 and 1.");if(Ug(u)&&u<=1)throw new Error("Exponential factor should be greater than 1.");if(r.initialDelay=a||100,r.maxDelay=s||1e4,r.maxDelay<=r.initialDelay)throw new Error("The maximal backoff delay must be greater than the initial backoff delay.");return r.randomisationFactor=o||0,r.factor=u||2,r.reset(),r}return vg.default(n,[{key:"backoff",value:function(e){null==this.timeoutID&&(this.backoffNumber===this.maxNumberOfRetry?(this.emit("fail",e),this.reset()):(this.backoffDelay=this.next(),this.timeoutID=setTimeout(this.onBackoff.bind(this),this.backoffDelay),this.emit("backoff",this.backoffNumber,this.backoffDelay,e)))}},{key:"reset",value:function(){this.backoffDelay=0,this.nextBackoffDelay=this.initialDelay,this.backoffNumber=0,this.timeoutID&&clearTimeout(this.timeoutID),this.timeoutID=null}},{key:"failAfter",value:function(e){if(e<=0)throw new Error("Expected a maximum number of retry greater than 0 but got ".concat(e));this.maxNumberOfRetry=e}},{key:"next",value:function(){this.backoffDelay=Math.min(this.nextBackoffDelay,this.maxDelay),this.nextBackoffDelay=this.backoffDelay*this.factor;var e=1+Math.random()*this.randomisationFactor;return Math.min(this.maxDelay,Math.round(this.backoffDelay*e))}},{key:"onBackoff",value:function(){this.timeoutID=null,this.emit("ready",this.backoffNumber,this.backoffDelay),this.backoffNumber++}}],[{key:"exponential",value:function(e){return new n(e)}}]),n}(xg),Fg=sg.AsyncRetrier=Lg;sg.Backoff=Dg;var Bg=sg.Retrier=Mg;function qg(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return zg(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return zg(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function zg(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var Wg=function(){function e(t,n){Ua(this,e),this.configuration=t,this.services=n,this.cache=new Map,this.cacheLifetime=100*this.configuration.httpCacheInterval,this.cleanupCache()}return Na(e,[{key:"isExpired",value:function(e){return!this.cacheLifetime||Date.now()-e>this.cacheLifetime}},{key:"cleanupCache",value:function(){var e,t=qg(this.cache);try{for(t.s();!(e=t.n()).done;){var n=mm(e.value,2),r=n[0],i=n[1];this.isExpired(i.timestamp)&&this.cache.delete(r)}}catch(e){t.e(e)}finally{t.f()}0===this.cache.size&&clearInterval(this.timer)}},{key:"pokeTimer",value:function(){var e=this;this.timer=this.timer||setInterval((function(){return e.cleanupCache()}),2*this.cacheLifetime)}},{key:"executeWithRetry",value:function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Promise((function(r,i){var a=[502,503,504];n&&a.push(429);var s=new Bg(t.configuration.backoffConfiguration);s.on("attempt",(function(){e().then((function(e){return s.succeeded(e)})).catch((function(e){a.indexOf(e.status)>-1||"Twilsock disconnected"===e.message?s.failed(e):(s.removeAllListeners(),s.cancel(),i(e))}))})),s.on("succeeded",(function(e){r(e)})),s.on("cancelled",(function(e){return i(e)})),s.on("failed",(function(e){return i(e)})),s.start()}))}},{key:"get",value:function(){var e=Ra(Gc.mark((function e(t){var n,r,i,a=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(n=this.cache.get(t))||this.isExpired(n.timestamp)){e.next=3;break}return e.abrupt("return",n.response);case 3:return r={},e.next=6,this.executeWithRetry((function(){return a.services.transport.get(t,r,a.configuration.productId)}),this.configuration.retryWhenThrottled);case 6:return i=e.sent,this.cache.set(t,{response:i,timestamp:Date.now()}),this.pokeTimer(),e.abrupt("return",i);case 10:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()}]),e}(),Gg=Na((function e(){Ua(this,e)}));Ma(Gg,"TYPING_INDICATOR","twilio.ipmsg.typing_indicator"),Ma(Gg,"NEW_MESSAGE","twilio.conversations.new_message"),Ma(Gg,"ADDED_TO_CONVERSATION","twilio.conversations.added_to_conversation"),Ma(Gg,"REMOVED_FROM_CONVERSATION","twilio.conversations.removed_from_conversation"),Ma(Gg,"CONSUMPTION_UPDATE","twilio.channel.consumption_update");var $g={},Vg={exports:{}};!function(e){function t(e,t,n,r,i,a,s){try{var o=e[a](s),u=o.value}catch(e){return void n(e)}o.done?t(u):Promise.resolve(u).then(r,i)}e.exports=function(e){return function(){var n=this,r=arguments;return new Promise((function(i,a){var s=e.apply(n,r);function o(e){t(s,i,a,o,u,"next",e)}function u(e){t(s,i,a,o,u,"throw",e)}o(void 0)}))}},e.exports.__esModule=!0,e.exports.default=e.exports}(Vg);var Jg=r($c),Kg=Ke.exports,Hg=Fe,Yg=Er,Qg=o,Xg=tp,Zg="toString",eb=RegExp.prototype,tb=eb.toString,nb=Qg((function(){return"/a/b"!=tb.call({source:"a",flags:"b"})})),rb=tb.name!=Zg;(nb||rb)&&Kg(RegExp.prototype,Zg,(function(){var e=Hg(this),t=Yg(e.source),n=e.flags;return"/"+t+"/"+Yg(void 0===n&&e instanceof RegExp&&!("flags"in eb)?Xg.call(e):n)}),{unsafe:!0}),Vm("Set",(function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}}),ag);var ib={exports:{}};!function(e,t){var n;n=function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=5)}([function(e,t,n){e.exports=function(e,t){var n,r,i;for(n=1;n<arguments.length;n++)for(i in r=arguments[n])r.hasOwnProperty(i)&&(e[i]=r[i]);return e}},function(e,t,n){var r=n(0);e.exports={build:function(e,t){var n,i,a,s=t.plugins;for(n=0,i=s.length;n<i;n++)(a=s[n]).methods&&r(e,a.methods),a.properties&&Object.defineProperties(e,a.properties)},hook:function(e,t,n){var r,i,a,s,o=e.config.plugins,u=[e.context];for(n&&(u=u.concat(n)),r=0,i=o.length;r<i;r++)s=o[r],(a=o[r][t])&&a.apply(s,u)}}},function(e,t,n){function r(e){if(0===e.length)return e;var t,n,r=e.split(/[_-]/);if(1===r.length&&r[0][0].toLowerCase()===r[0][0])return e;for(n=r[0].toLowerCase(),t=1;t<r.length;t++)n=n+r[t].charAt(0).toUpperCase()+r[t].substring(1).toLowerCase();return n}r.prepended=function(e,t){return e+(t=r(t))[0].toUpperCase()+t.substring(1)},e.exports=r},function(e,t,n){var r=n(0),i=n(2);function a(e,t){e=e||{},this.options=e,this.defaults=t.defaults,this.states=[],this.transitions=[],this.map={},this.lifecycle=this.configureLifecycle(),this.init=this.configureInitTransition(e.init),this.data=this.configureData(e.data),this.methods=this.configureMethods(e.methods),this.map[this.defaults.wildcard]={},this.configureTransitions(e.transitions||[]),this.plugins=this.configurePlugins(e.plugins,t.plugin)}r(a.prototype,{addState:function(e){this.map[e]||(this.states.push(e),this.addStateLifecycleNames(e),this.map[e]={})},addStateLifecycleNames:function(e){this.lifecycle.onEnter[e]=i.prepended("onEnter",e),this.lifecycle.onLeave[e]=i.prepended("onLeave",e),this.lifecycle.on[e]=i.prepended("on",e)},addTransition:function(e){this.transitions.indexOf(e)<0&&(this.transitions.push(e),this.addTransitionLifecycleNames(e))},addTransitionLifecycleNames:function(e){this.lifecycle.onBefore[e]=i.prepended("onBefore",e),this.lifecycle.onAfter[e]=i.prepended("onAfter",e),this.lifecycle.on[e]=i.prepended("on",e)},mapTransition:function(e){var t=e.name,n=e.from,r=e.to;return this.addState(n),"function"!=typeof r&&this.addState(r),this.addTransition(t),this.map[n][t]=e,e},configureLifecycle:function(){return{onBefore:{transition:"onBeforeTransition"},onAfter:{transition:"onAfterTransition"},onEnter:{state:"onEnterState"},onLeave:{state:"onLeaveState"},on:{transition:"onTransition"}}},configureInitTransition:function(e){return"string"==typeof e?this.mapTransition(r({},this.defaults.init,{to:e,active:!0})):"object"===Pa(e)?this.mapTransition(r({},this.defaults.init,e,{active:!0})):(this.addState(this.defaults.init.from),this.defaults.init)},configureData:function(e){return"function"==typeof e?e:"object"===Pa(e)?function(){return e}:function(){return{}}},configureMethods:function(e){return e||{}},configurePlugins:function(e,t){var n,r,i;for(n=0,r=(e=e||[]).length;n<r;n++)"function"==typeof(i=e[n])&&(e[n]=i=i()),i.configure&&i.configure(this);return e},configureTransitions:function(e){var t,n,r,i,a,s=this.defaults.wildcard;for(n=0;n<e.length;n++)for(r=e[n],i=Array.isArray(r.from)?r.from:[r.from||s],a=r.to||s,t=0;t<i.length;t++)this.mapTransition({name:r.name,from:i[t],to:a})},transitionFor:function(e,t){var n=this.defaults.wildcard;return this.map[e][t]||this.map[n][t]},transitionsFor:function(e){var t=this.defaults.wildcard;return Object.keys(this.map[e]).concat(Object.keys(this.map[t]))},allStates:function(){return this.states},allTransitions:function(){return this.transitions}}),e.exports=a},function(e,t,n){var r=n(0),i=n(6),a=n(1),s=[null,[]];function o(e,t){this.context=e,this.config=t,this.state=t.init.from,this.observers=[e]}r(o.prototype,{init:function(e){if(r(this.context,this.config.data.apply(this.context,e)),a.hook(this,"init"),this.config.init.active)return this.fire(this.config.init.name,[])},is:function(e){return Array.isArray(e)?e.indexOf(this.state)>=0:this.state===e},isPending:function(){return this.pending},can:function(e){return!this.isPending()&&!!this.seek(e)},cannot:function(e){return!this.can(e)},allStates:function(){return this.config.allStates()},allTransitions:function(){return this.config.allTransitions()},transitions:function(){return this.config.transitionsFor(this.state)},seek:function(e,t){var n=this.config.defaults.wildcard,r=this.config.transitionFor(this.state,e),i=r&&r.to;return"function"==typeof i?i.apply(this.context,t):i===n?this.state:i},fire:function(e,t){return this.transit(e,this.state,this.seek(e,t),t)},transit:function(e,t,n,r){var i=this.config.lifecycle,a=this.config.options.observeUnchangedState||t!==n;return n?this.isPending()?this.context.onPendingTransition(e,t,n):(this.config.addState(n),this.beginTransit(),r.unshift({transition:e,from:t,to:n,fsm:this.context}),this.observeEvents([this.observersForEvent(i.onBefore.transition),this.observersForEvent(i.onBefore[e]),a?this.observersForEvent(i.onLeave.state):s,a?this.observersForEvent(i.onLeave[t]):s,this.observersForEvent(i.on.transition),a?["doTransit",[this]]:s,a?this.observersForEvent(i.onEnter.state):s,a?this.observersForEvent(i.onEnter[n]):s,a?this.observersForEvent(i.on[n]):s,this.observersForEvent(i.onAfter.transition),this.observersForEvent(i.onAfter[e]),this.observersForEvent(i.on[e])],r)):this.context.onInvalidTransition(e,t,n)},beginTransit:function(){this.pending=!0},endTransit:function(e){return this.pending=!1,e},failTransit:function(e){throw this.pending=!1,e},doTransit:function(e){this.state=e.to},observe:function(e){if(2===e.length){var t={};t[e[0]]=e[1],this.observers.push(t)}else this.observers.push(e[0])},observersForEvent:function(e){for(var t,n=0,r=this.observers.length,i=[];n<r;n++)(t=this.observers[n])[e]&&i.push(t);return[e,i,!0]},observeEvents:function(e,t,n,r){if(0===e.length)return this.endTransit(void 0===r||r);var i=e[0][0],s=e[0][1],o=e[0][2];if(t[0].event=i,i&&o&&i!==n&&a.hook(this,"lifecycle",t),0===s.length)return e.shift(),this.observeEvents(e,t,i,r);var u=s.shift(),c=u[i].apply(u,t);return c&&"function"==typeof c.then?c.then(this.observeEvents.bind(this,e,t,i)).catch(this.failTransit.bind(this)):!1===c?this.endTransit(!1):this.observeEvents(e,t,i,c)},onInvalidTransition:function(e,t,n){throw new i("transition is invalid in current state",e,t,n,this.state)},onPendingTransition:function(e,t,n){throw new i("transition is invalid while previous transition is still in progress",e,t,n,this.state)}}),e.exports=o},function(e,t,n){var r=n(0),i=n(2),a=n(1),s=n(3),o=n(4),u={is:function(e){return this._fsm.is(e)},can:function(e){return this._fsm.can(e)},cannot:function(e){return this._fsm.cannot(e)},observe:function(){return this._fsm.observe(arguments)},transitions:function(){return this._fsm.transitions()},allTransitions:function(){return this._fsm.allTransitions()},allStates:function(){return this._fsm.allStates()},onInvalidTransition:function(e,t,n){return this._fsm.onInvalidTransition(e,t,n)},onPendingTransition:function(e,t,n){return this._fsm.onPendingTransition(e,t,n)}},c={state:{configurable:!1,enumerable:!0,get:function(){return this._fsm.state},set:function(e){throw Error("use transitions to change state")}}};function l(e){return f(this||{},e)}function f(e,t){return d(e,new s(t,l)),e._fsm(),e}function d(e,t){if("object"!==Pa(e)||Array.isArray(e))throw Error("StateMachine can only be applied to objects");a.build(e,t),Object.defineProperties(e,c),r(e,u),r(e,t.methods),t.allTransitions().forEach((function(t){e[i(t)]=function(){return this._fsm.fire(t,[].slice.call(arguments))}})),e._fsm=function(){this._fsm=new o(this,t),this._fsm.init(arguments)}}l.version="3.0.1",l.factory=function(){var e,t;"function"==typeof arguments[0]?(e=arguments[0],t=arguments[1]||{}):(e=function(){this._fsm.apply(this,arguments)},t=arguments[0]||{});var n=new s(t,l);return d(e.prototype,n),e.prototype._fsm.config=n,e},l.apply=f,l.defaults={wildcard:"*",init:{name:"init",from:"none"}},e.exports=l},function(e,t,n){e.exports=function(e,t,n,r,i){this.message=e,this.transition=t,this.from=n,this.to=r,this.current=i}}])},e.exports=n()}(ib);var ab={exports:{}},sb="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(sb){var ob=new Uint8Array(16);ab.exports=function(){return sb(ob),ob}}else{var ub=new Array(16);ab.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),ub[t]=e>>>((3&t)<<3)&255;return ub}}for(var cb=[],lb=0;lb<256;++lb)cb[lb]=(lb+256).toString(16).substr(1);var fb,db,pb=function(e,t){var n=t||0,r=cb;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++]]].join("")},hb=ab.exports,vb=pb,yb=0,mb=0;var gb=function(e,t,n){var r=t&&n||0,i=t||[],a=(e=e||{}).node||fb,s=void 0!==e.clockseq?e.clockseq:db;if(null==a||null==s){var o=hb();null==a&&(a=fb=[1|o[0],o[1],o[2],o[3],o[4],o[5]]),null==s&&(s=db=16383&(o[6]<<8|o[7]))}var u=void 0!==e.msecs?e.msecs:(new Date).getTime(),c=void 0!==e.nsecs?e.nsecs:mb+1,l=u-yb+(c-mb)/1e4;if(l<0&&void 0===e.clockseq&&(s=s+1&16383),(l<0||u>yb)&&void 0===e.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");yb=u,mb=c,db=s;var f=(1e4*(268435455&(u+=122192928e5))+c)%4294967296;i[r++]=f>>>24&255,i[r++]=f>>>16&255,i[r++]=f>>>8&255,i[r++]=255&f;var d=u/4294967296*1e4&268435455;i[r++]=d>>>8&255,i[r++]=255&d,i[r++]=d>>>24&15|16,i[r++]=d>>>16&255,i[r++]=s>>>8|128,i[r++]=255&s;for(var p=0;p<6;++p)i[r+p]=a[p];return t||vb(i)},bb=ab.exports,wb=pb;var kb=function(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||bb)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var a=0;a<16;++a)t[r+a]=i[a];return t||wb(i)},xb=gb,_b=kb,Sb=_b;Sb.v1=xb,Sb.v4=_b;var Eb,Tb,Rb,Cb=Sb,Ib={exports:{}},Ob="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Pb=Ob,Ab=u,jb=a,Mb=E,Lb=te,Nb=Ga,Ub=Je,Db=Ke.exports,Fb=Ue.f,Bb=Nl,qb=ns,zb=he,Wb=ie,Gb=jb.Int8Array,$b=Gb&&Gb.prototype,Vb=jb.Uint8ClampedArray,Jb=Vb&&Vb.prototype,Kb=Gb&&Bb(Gb),Hb=$b&&Bb($b),Yb=Object.prototype,Qb=Yb.isPrototypeOf,Xb=zb("toStringTag"),Zb=Wb("TYPED_ARRAY_TAG"),ew=Wb("TYPED_ARRAY_CONSTRUCTOR"),tw=Pb&&!!qb&&"Opera"!==Nb(jb.opera),nw=!1,rw={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},iw={BigInt64Array:8,BigUint64Array:8},aw=function(e){if(!Mb(e))return!1;var t=Nb(e);return Lb(rw,t)||Lb(iw,t)};for(Eb in rw)(Rb=(Tb=jb[Eb])&&Tb.prototype)?Ub(Rb,ew,Tb):tw=!1;for(Eb in iw)(Rb=(Tb=jb[Eb])&&Tb.prototype)&&Ub(Rb,ew,Tb);if((!tw||"function"!=typeof Kb||Kb===Function.prototype)&&(Kb=function(){throw TypeError("Incorrect invocation")},tw))for(Eb in rw)jb[Eb]&&qb(jb[Eb],Kb);if((!tw||!Hb||Hb===Yb)&&(Hb=Kb.prototype,tw))for(Eb in rw)jb[Eb]&&qb(jb[Eb].prototype,Hb);if(tw&&Bb(Jb)!==Hb&&qb(Jb,Hb),Ab&&!Lb(Hb,Xb))for(Eb in nw=!0,Fb(Hb,Xb,{get:function(){return Mb(this)?this[Zb]:void 0}}),rw)jb[Eb]&&Ub(jb[Eb],Zb,Eb);var sw={NATIVE_ARRAY_BUFFER_VIEWS:tw,TYPED_ARRAY_CONSTRUCTOR:ew,TYPED_ARRAY_TAG:nw&&Zb,aTypedArray:function(e){if(aw(e))return e;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(e){if(qb&&!Qb.call(Kb,e))throw TypeError("Target is not a typed array constructor");return e},exportTypedArrayMethod:function(e,t,n){if(Ab){if(n)for(var r in rw){var i=jb[r];if(i&&Lb(i.prototype,e))try{delete i.prototype[e]}catch(e){}}Hb[e]&&!n||Db(Hb,e,n?t:tw&&$b[e]||t)}},exportTypedArrayStaticMethod:function(e,t,n){var r,i;if(Ab){if(qb){if(n)for(r in rw)if((i=jb[r])&&Lb(i,e))try{delete i[e]}catch(e){}if(Kb[e]&&!n)return;try{return Db(Kb,e,n?t:tw&&Kb[e]||t)}catch(e){}}for(r in rw)!(i=jb[r])||i[e]&&!n||Db(i,e,t)}},isView:function(e){if(!Mb(e))return!1;var t=Nb(e);return"DataView"===t||Lb(rw,t)||Lb(iw,t)},isTypedArray:aw,TypedArray:Kb,TypedArrayPrototype:Hb},ow=a,uw=o,cw=Bs,lw=sw.NATIVE_ARRAY_BUFFER_VIEWS,fw=ow.ArrayBuffer,dw=ow.Int8Array,pw=!lw||!uw((function(){dw(1)}))||!uw((function(){new dw(-1)}))||!cw((function(e){new dw,new dw(null),new dw(1.5),new dw(e)}),!0)||uw((function(){return 1!==new dw(new fw(2),1,void 0).length})),hw=Lt,vw=Dt,yw=function(e){if(void 0===e)return 0;var t=hw(e),n=vw(t);if(t!==n)throw RangeError("Wrong length or index");return n},mw=Math.abs,gw=Math.pow,bw=Math.floor,ww=Math.log,kw=Math.LN2,xw=X,_w=zt,Sw=Dt,Ew=function(e){for(var t=xw(this),n=Sw(t.length),r=arguments.length,i=_w(r>1?arguments[1]:void 0,n),a=r>2?arguments[2]:void 0,s=void 0===a?n:_w(a,n);s>i;)t[i++]=e;return t},Tw=a,Rw=u,Cw=Ob,Iw=Je,Ow=Xa,Pw=o,Aw=us,jw=Lt,Mw=Dt,Lw=yw,Nw={pack:function(e,t,n){var r,i,a,s=new Array(n),o=8*n-t-1,u=(1<<o)-1,c=u>>1,l=23===t?gw(2,-24)-gw(2,-77):0,f=e<0||0===e&&1/e<0?1:0,d=0;for((e=mw(e))!=e||e===1/0?(i=e!=e?1:0,r=u):(r=bw(ww(e)/kw),e*(a=gw(2,-r))<1&&(r--,a*=2),(e+=r+c>=1?l/a:l*gw(2,1-c))*a>=2&&(r++,a/=2),r+c>=u?(i=0,r=u):r+c>=1?(i=(e*a-1)*gw(2,t),r+=c):(i=e*gw(2,c-1)*gw(2,t),r=0));t>=8;s[d++]=255&i,i/=256,t-=8);for(r=r<<t|i,o+=t;o>0;s[d++]=255&r,r/=256,o-=8);return s[--d]|=128*f,s},unpack:function(e,t){var n,r=e.length,i=8*r-t-1,a=(1<<i)-1,s=a>>1,o=i-7,u=r-1,c=e[u--],l=127&c;for(c>>=7;o>0;l=256*l+e[u],u--,o-=8);for(n=l&(1<<-o)-1,l>>=-o,o+=t;o>0;n=256*n+e[u],u--,o-=8);if(0===l)l=1-s;else{if(l===a)return n?NaN:c?-1/0:1/0;n+=gw(2,t),l-=s}return(c?-1:1)*n*gw(2,l-t)}},Uw=Nl,Dw=ns,Fw=At.f,Bw=Ue.f,qw=Ew,zw=An,Ww=_t.get,Gw=_t.set,$w="ArrayBuffer",Vw="DataView",Jw="Wrong index",Kw=Tw.ArrayBuffer,Hw=Kw,Yw=Tw.DataView,Qw=Yw&&Yw.prototype,Xw=Object.prototype,Zw=Tw.RangeError,ek=Nw.pack,tk=Nw.unpack,nk=function(e){return[255&e]},rk=function(e){return[255&e,e>>8&255]},ik=function(e){return[255&e,e>>8&255,e>>16&255,e>>24&255]},ak=function(e){return e[3]<<24|e[2]<<16|e[1]<<8|e[0]},sk=function(e){return ek(e,23,4)},ok=function(e){return ek(e,52,8)},uk=function(e,t){Bw(e.prototype,t,{get:function(){return Ww(this)[t]}})},ck=function(e,t,n,r){var i=Lw(n),a=Ww(e);if(i+t>a.byteLength)throw Zw(Jw);var s=Ww(a.buffer).bytes,o=i+a.byteOffset,u=s.slice(o,o+t);return r?u:u.reverse()},lk=function(e,t,n,r,i,a){var s=Lw(n),o=Ww(e);if(s+t>o.byteLength)throw Zw(Jw);for(var u=Ww(o.buffer).bytes,c=s+o.byteOffset,l=r(+i),f=0;f<t;f++)u[c+f]=l[a?f:t-f-1]};if(Cw){if(!Pw((function(){Kw(1)}))||!Pw((function(){new Kw(-1)}))||Pw((function(){return new Kw,new Kw(1.5),new Kw(NaN),Kw.name!=$w}))){for(var fk,dk=(Hw=function(e){return Aw(this,Hw),new Kw(Lw(e))}).prototype=Kw.prototype,pk=Fw(Kw),hk=0;pk.length>hk;)(fk=pk[hk++])in Hw||Iw(Hw,fk,Kw[fk]);dk.constructor=Hw}Dw&&Uw(Qw)!==Xw&&Dw(Qw,Xw);var vk=new Yw(new Hw(2)),yk=Qw.setInt8;vk.setInt8(0,2147483648),vk.setInt8(1,2147483649),!vk.getInt8(0)&&vk.getInt8(1)||Ow(Qw,{setInt8:function(e,t){yk.call(this,e,t<<24>>24)},setUint8:function(e,t){yk.call(this,e,t<<24>>24)}},{unsafe:!0})}else Hw=function(e){Aw(this,Hw,$w);var t=Lw(e);Gw(this,{bytes:qw.call(new Array(t),0),byteLength:t}),Rw||(this.byteLength=t)},Yw=function(e,t,n){Aw(this,Yw,Vw),Aw(e,Hw,Vw);var r=Ww(e).byteLength,i=jw(t);if(i<0||i>r)throw Zw("Wrong offset");if(i+(n=void 0===n?r-i:Mw(n))>r)throw Zw("Wrong length");Gw(this,{buffer:e,byteLength:n,byteOffset:i}),Rw||(this.buffer=e,this.byteLength=n,this.byteOffset=i)},Rw&&(uk(Hw,"byteLength"),uk(Yw,"buffer"),uk(Yw,"byteLength"),uk(Yw,"byteOffset")),Ow(Yw.prototype,{getInt8:function(e){return ck(this,1,e)[0]<<24>>24},getUint8:function(e){return ck(this,1,e)[0]},getInt16:function(e){var t=ck(this,2,e,arguments.length>1?arguments[1]:void 0);return(t[1]<<8|t[0])<<16>>16},getUint16:function(e){var t=ck(this,2,e,arguments.length>1?arguments[1]:void 0);return t[1]<<8|t[0]},getInt32:function(e){return ak(ck(this,4,e,arguments.length>1?arguments[1]:void 0))},getUint32:function(e){return ak(ck(this,4,e,arguments.length>1?arguments[1]:void 0))>>>0},getFloat32:function(e){return tk(ck(this,4,e,arguments.length>1?arguments[1]:void 0),23)},getFloat64:function(e){return tk(ck(this,8,e,arguments.length>1?arguments[1]:void 0),52)},setInt8:function(e,t){lk(this,1,e,nk,t)},setUint8:function(e,t){lk(this,1,e,nk,t)},setInt16:function(e,t){lk(this,2,e,rk,t,arguments.length>2?arguments[2]:void 0)},setUint16:function(e,t){lk(this,2,e,rk,t,arguments.length>2?arguments[2]:void 0)},setInt32:function(e,t){lk(this,4,e,ik,t,arguments.length>2?arguments[2]:void 0)},setUint32:function(e,t){lk(this,4,e,ik,t,arguments.length>2?arguments[2]:void 0)},setFloat32:function(e,t){lk(this,4,e,sk,t,arguments.length>2?arguments[2]:void 0)},setFloat64:function(e,t){lk(this,8,e,ok,t,arguments.length>2?arguments[2]:void 0)}});zw(Hw,$w),zw(Yw,Vw);var mk={ArrayBuffer:Hw,DataView:Yw},gk=Lt,bk=function(e){var t=gk(e);if(t<0)throw RangeError("The argument can't be less than 0");return t},wk=function(e,t){var n=bk(e);if(n%t)throw RangeError("Wrong offset");return n},kk=X,xk=Dt,_k=ws,Sk=ms,Ek=ps,Tk=Fr,Rk=sw.aTypedArrayConstructor,Ck=Cn,Ik=a,Ok=u,Pk=pw,Ak=sw,jk=mk,Mk=us,Lk=v,Nk=Je,Uk=_v,Dk=Dt,Fk=yw,Bk=wk,qk=xe,zk=te,Wk=Ga,Gk=E,$k=z,Vk=nr,Jk=ns,Kk=At.f,Hk=function(e){var t,n,r,i,a,s,o=kk(e),u=arguments.length,c=u>1?arguments[1]:void 0,l=void 0!==c,f=Sk(o);if(null!=f&&!Ek(f))for(s=(a=_k(o,f)).next,o=[];!(i=s.call(a)).done;)o.push(i.value);for(l&&u>2&&(c=Tk(c,arguments[2],2)),n=xk(o.length),r=new(Rk(this))(n),t=0;n>t;t++)r[t]=l?c(o[t],t):o[t];return r},Yk=Xr.forEach,Qk=os,Xk=Ue,Zk=s,ex=xd,tx=_t.get,nx=_t.set,rx=Xk.f,ix=Zk.f,ax=Math.round,sx=Ik.RangeError,ox=jk.ArrayBuffer,ux=jk.DataView,cx=Ak.NATIVE_ARRAY_BUFFER_VIEWS,lx=Ak.TYPED_ARRAY_CONSTRUCTOR,fx=Ak.TYPED_ARRAY_TAG,dx=Ak.TypedArray,px=Ak.TypedArrayPrototype,hx=Ak.aTypedArrayConstructor,vx=Ak.isTypedArray,yx="BYTES_PER_ELEMENT",mx="Wrong length",gx=function(e,t){for(var n=0,r=t.length,i=new(hx(e))(r);r>n;)i[n]=t[n++];return i},bx=function(e,t){rx(e,t,{get:function(){return tx(this)[t]}})},wx=function(e){var t;return e instanceof ox||"ArrayBuffer"==(t=Wk(e))||"SharedArrayBuffer"==t},kx=function(e,t){return vx(e)&&!$k(t)&&t in e&&Uk(+t)&&t>=0},xx=function(e,t){return t=qk(t),kx(e,t)?Lk(2,e[t]):ix(e,t)},_x=function(e,t,n){return t=qk(t),!(kx(e,t)&&Gk(n)&&zk(n,"value"))||zk(n,"get")||zk(n,"set")||n.configurable||zk(n,"writable")&&!n.writable||zk(n,"enumerable")&&!n.enumerable?rx(e,t,n):(e[t]=n.value,e)};Ok?(cx||(Zk.f=xx,Xk.f=_x,bx(px,"buffer"),bx(px,"byteOffset"),bx(px,"byteLength"),bx(px,"length")),Ck({target:"Object",stat:!0,forced:!cx},{getOwnPropertyDescriptor:xx,defineProperty:_x}),Ib.exports=function(e,t,n){var r=e.match(/\d+$/)[0]/8,i=e+(n?"Clamped":"")+"Array",a="get"+e,s="set"+e,o=Ik[i],u=o,c=u&&u.prototype,l={},f=function(e,t){rx(e,t,{get:function(){return function(e,t){var n=tx(e);return n.view[a](t*r+n.byteOffset,!0)}(this,t)},set:function(e){return function(e,t,i){var a=tx(e);n&&(i=(i=ax(i))<0?0:i>255?255:255&i),a.view[s](t*r+a.byteOffset,i,!0)}(this,t,e)},enumerable:!0})};cx?Pk&&(u=t((function(e,t,n,a){return Mk(e,u,i),ex(Gk(t)?wx(t)?void 0!==a?new o(t,Bk(n,r),a):void 0!==n?new o(t,Bk(n,r)):new o(t):vx(t)?gx(u,t):Hk.call(u,t):new o(Fk(t)),e,u)})),Jk&&Jk(u,dx),Yk(Kk(o),(function(e){e in u||Nk(u,e,o[e])})),u.prototype=c):(u=t((function(e,t,n,a){Mk(e,u,i);var s,o,c,l=0,d=0;if(Gk(t)){if(!wx(t))return vx(t)?gx(u,t):Hk.call(u,t);s=t,d=Bk(n,r);var p=t.byteLength;if(void 0===a){if(p%r)throw sx(mx);if((o=p-d)<0)throw sx(mx)}else if((o=Dk(a)*r)+d>p)throw sx(mx);c=o/r}else c=Fk(t),s=new ox(o=c*r);for(nx(e,{buffer:s,byteOffset:d,byteLength:o,length:c,view:new ux(s)});l<c;)f(e,l++)})),Jk&&Jk(u,dx),c=u.prototype=Vk(px)),c.constructor!==u&&Nk(c,"constructor",u),Nk(c,lx,u),fx&&Nk(c,fx,i),l[i]=u,Ck({global:!0,forced:u!=o,sham:!cx},l),yx in u||Nk(u,yx,r),yx in c||Nk(c,yx,r),Qk(i)}):Ib.exports=function(){},(0,Ib.exports)("Uint8",(function(e){return function(t,n,r){return e(this,t,n,r)}}));var Sx=X,Ex=zt,Tx=Dt,Rx=Math.min,Cx=[].copyWithin||function(e,t){var n=Sx(this),r=Tx(n.length),i=Ex(e,r),a=Ex(t,r),s=arguments.length>2?arguments[2]:void 0,o=Rx((void 0===s?r:Ex(s,r))-a,r-i),u=1;for(a<i&&i<a+o&&(u=-1,a+=o-1,i+=o-1);o-- >0;)a in n?n[i]=n[a]:delete n[i],i+=u,a+=u;return n},Ix=Cx,Ox=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("copyWithin",(function(e,t){return Ix.call(Ox(this),e,t,arguments.length>2?arguments[2]:void 0)}));var Px=Xr.every,Ax=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("every",(function(e){return Px(Ax(this),e,arguments.length>1?arguments[1]:void 0)}));var jx=Ew,Mx=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("fill",(function(e){return jx.apply(Mx(this),arguments)}));var Lx=Gs,Nx=sw.TYPED_ARRAY_CONSTRUCTOR,Ux=sw.aTypedArrayConstructor,Dx=function(e){return Ux(Lx(e,e[Nx]))},Fx=function(e,t){for(var n=0,r=t.length,i=new e(r);r>n;)i[n]=t[n++];return i},Bx=Dx,qx=Xr.filter,zx=function(e,t){return Fx(Bx(e),t)},Wx=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("filter",(function(e){var t=qx(Wx(this),e,arguments.length>1?arguments[1]:void 0);return zx(this,t)}));var Gx=Xr.find,$x=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("find",(function(e){return Gx($x(this),e,arguments.length>1?arguments[1]:void 0)}));var Vx=Xr.findIndex,Jx=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("findIndex",(function(e){return Vx(Jx(this),e,arguments.length>1?arguments[1]:void 0)}));var Kx=Xr.forEach,Hx=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("forEach",(function(e){Kx(Hx(this),e,arguments.length>1?arguments[1]:void 0)}));var Yx=Jt.includes,Qx=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("includes",(function(e){return Yx(Qx(this),e,arguments.length>1?arguments[1]:void 0)}));var Xx=Jt.indexOf,Zx=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("indexOf",(function(e){return Xx(Zx(this),e,arguments.length>1?arguments[1]:void 0)}));var e_=a,t_=sw,n_=ed,r_=he("iterator"),i_=e_.Uint8Array,a_=n_.values,s_=n_.keys,o_=n_.entries,u_=t_.aTypedArray,c_=t_.exportTypedArrayMethod,l_=i_&&i_.prototype[r_],f_=!!l_&&("values"==l_.name||null==l_.name),d_=function(){return a_.call(u_(this))};c_("entries",(function(){return o_.call(u_(this))})),c_("keys",(function(){return s_.call(u_(this))})),c_("values",d_,!f_),c_(r_,d_,!f_);var p_=sw.aTypedArray,h_=[].join;(0,sw.exportTypedArrayMethod)("join",(function(e){return h_.apply(p_(this),arguments)}));var v_=S,y_=Lt,m_=Dt,g_=ic,b_=Math.min,w_=[].lastIndexOf,k_=!!w_&&1/[1].lastIndexOf(1,-0)<0,x_=g_("lastIndexOf"),__=k_||!x_?function(e){if(k_)return w_.apply(this,arguments)||0;var t=v_(this),n=m_(t.length),r=n-1;for(arguments.length>1&&(r=b_(r,y_(arguments[1]))),r<0&&(r=n+r);r>=0;r--)if(r in t&&t[r]===e)return r||0;return-1}:w_,S_=__,E_=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("lastIndexOf",(function(e){return S_.apply(E_(this),arguments)}));var T_=Xr.map,R_=Dx,C_=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("map",(function(e){return T_(C_(this),e,arguments.length>1?arguments[1]:void 0,(function(e,t){return new(R_(e))(t)}))}));var I_=Nn,O_=X,P_=w,A_=Dt,j_=function(e){return function(t,n,r,i){I_(n);var a=O_(t),s=P_(a),o=A_(a.length),u=e?o-1:0,c=e?-1:1;if(r<2)for(;;){if(u in s){i=s[u],u+=c;break}if(u+=c,e?u<0:o<=u)throw TypeError("Reduce of empty array with no initial value")}for(;e?u>=0:o>u;u+=c)u in s&&(i=n(i,s[u],u,a));return i}},M_={left:j_(!1),right:j_(!0)},L_=M_.left,N_=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("reduce",(function(e){return L_(N_(this),e,arguments.length,arguments.length>1?arguments[1]:void 0)}));var U_=M_.right,D_=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("reduceRight",(function(e){return U_(D_(this),e,arguments.length,arguments.length>1?arguments[1]:void 0)}));var F_=sw.aTypedArray,B_=sw.exportTypedArrayMethod,q_=Math.floor;B_("reverse",(function(){for(var e,t=this,n=F_(t).length,r=q_(n/2),i=0;i<r;)e=t[i],t[i++]=t[--n],t[n]=e;return t}));var z_=Dt,W_=wk,G_=X,$_=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("set",(function(e){$_(this);var t=W_(arguments.length>1?arguments[1]:void 0,1),n=this.length,r=G_(e),i=z_(r.length),a=0;if(i+t>n)throw RangeError("Wrong length");for(;a<i;)this[t+a]=r[a++]}),o((function(){new Int8Array(1).set({})})));var V_=Dx,J_=sw.aTypedArray,K_=[].slice;(0,sw.exportTypedArrayMethod)("slice",(function(e,t){for(var n=K_.call(J_(this),e,t),r=V_(this),i=0,a=n.length,s=new r(a);a>i;)s[i]=n[i++];return s}),o((function(){new Int8Array(1).slice()})));var H_=Xr.some,Y_=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("some",(function(e){return H_(Y_(this),e,arguments.length>1?arguments[1]:void 0)}));var Q_=Math.floor,X_=function(e,t){var n=e.length,r=Q_(n/2);return n<8?Z_(e,t):eS(X_(e.slice(0,r),t),X_(e.slice(r),t),t)},Z_=function(e,t){for(var n,r,i=e.length,a=1;a<i;){for(r=a,n=e[a];r&&t(e[r-1],n)>0;)e[r]=e[--r];r!==a++&&(e[r]=n)}return e},eS=function(e,t,n){for(var r=e.length,i=t.length,a=0,s=0,o=[];a<r||s<i;)a<r&&s<i?o.push(n(e[a],t[s])<=0?e[a++]:t[s++]):o.push(a<r?e[a++]:t[s++]);return o},tS=X_,nS=I.match(/firefox\/(\d+)/i),rS=!!nS&&+nS[1],iS=/MSIE|Trident/.test(I),aS=I.match(/AppleWebKit\/(\d+)\./),sS=!!aS&&+aS[1],oS=o,uS=Nn,cS=Dt,lS=tS,fS=rS,dS=iS,pS=N,hS=sS,vS=sw.aTypedArray,yS=sw.exportTypedArrayMethod,mS=a.Uint16Array,gS=mS&&mS.prototype.sort,bS=!!gS&&!oS((function(){var e=new mS(2);e.sort(null),e.sort({})})),wS=!!gS&&!oS((function(){if(pS)return pS<74;if(fS)return fS<67;if(dS)return!0;if(hS)return hS<602;var e,t,n=new mS(516),r=Array(516);for(e=0;e<516;e++)t=e%4,n[e]=515-e,r[e]=e-2*t+3;for(n.sort((function(e,t){return(e/4|0)-(t/4|0)})),e=0;e<516;e++)if(n[e]!==r[e])return!0}));yS("sort",(function(e){var t=this;if(void 0!==e&&uS(e),wS)return gS.call(t,e);vS(t);var n,r=cS(t.length),i=Array(r);for(n=0;n<r;n++)i[n]=t[n];for(i=lS(t,function(e){return function(t,n){return void 0!==e?+e(t,n)||0:n!=n?-1:t!=t?1:0===t&&0===n?1/t>0&&1/n<0?1:-1:t>n}}(e)),n=0;n<r;n++)t[n]=i[n];return t}),!wS||bS);var kS=Dt,xS=zt,_S=Dx,SS=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("subarray",(function(e,t){var n=SS(this),r=n.length,i=xS(e,r);return new(_S(n))(n.buffer,n.byteOffset+i*n.BYTES_PER_ELEMENT,kS((void 0===t?r:xS(t,r))-i))}));var ES=sw,TS=o,RS=a.Int8Array,CS=ES.aTypedArray,IS=ES.exportTypedArrayMethod,OS=[].toLocaleString,PS=[].slice,AS=!!RS&&TS((function(){OS.call(new RS(1))}));IS("toLocaleString",(function(){return OS.apply(AS?PS.call(CS(this)):CS(this),arguments)}),TS((function(){return[1,2].toLocaleString()!=new RS([1,2]).toLocaleString()}))||!TS((function(){RS.prototype.toLocaleString.call([1,2])})));var jS=sw.exportTypedArrayMethod,MS=o,LS=a.Uint8Array,NS=LS&&LS.prototype||{},US=[].toString,DS=[].join;MS((function(){US.call({})}))&&(US=function(){return DS.call(this)});var FS=NS.toString!=US;jS("toString",US,FS);var BS=E,qS=m,zS=he("match"),WS=function(e){var t;return BS(e)&&(void 0!==(t=e[zS])?!!t:"RegExp"==qS(e))},GS=Lp,$S=WS,VS=Fe,JS=k,KS=Gs,HS=Up,YS=Dt,QS=Er,XS=$p,ZS=Rp,eE=o,tE=np.UNSUPPORTED_Y,nE=[].push,rE=Math.min,iE=4294967295,aE=!eE((function(){var e=/(?:)/,t=e.exec;e.exec=function(){return t.apply(this,arguments)};var n="ab".split(e);return 2!==n.length||"a"!==n[0]||"b"!==n[1]}));GS("split",(function(e,t,n){var r;return r="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(e,n){var r=QS(JS(this)),i=void 0===n?iE:n>>>0;if(0===i)return[];if(void 0===e)return[r];if(!$S(e))return t.call(r,e,i);for(var a,s,o,u=[],c=(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.unicode?"u":"")+(e.sticky?"y":""),l=0,f=new RegExp(e.source,c+"g");(a=ZS.call(f,r))&&!((s=f.lastIndex)>l&&(u.push(r.slice(l,a.index)),a.length>1&&a.index<r.length&&nE.apply(u,a.slice(1)),o=a[0].length,l=s,u.length>=i));)f.lastIndex===a.index&&f.lastIndex++;return l===r.length?!o&&f.test("")||u.push(""):u.push(r.slice(l)),u.length>i?u.slice(0,i):u}:"0".split(void 0,0).length?function(e,n){return void 0===e&&0===n?[]:t.call(this,e,n)}:t,[function(t,n){var i=JS(this),a=null==t?void 0:t[e];return void 0!==a?a.call(t,i,n):r.call(QS(i),t,n)},function(e,i){var a=VS(this),s=QS(e),o=n(r,a,s,i,r!==t);if(o.done)return o.value;var u=KS(a,RegExp),c=a.unicode,l=(a.ignoreCase?"i":"")+(a.multiline?"m":"")+(a.unicode?"u":"")+(tE?"g":"y"),f=new u(tE?"^(?:"+a.source+")":a,l),d=void 0===i?iE:i>>>0;if(0===d)return[];if(0===s.length)return null===XS(f,s)?[s]:[];for(var p=0,h=0,v=[];h<s.length;){f.lastIndex=tE?0:h;var y,m=XS(f,tE?s.slice(h):s);if(null===m||(y=rE(YS(f.lastIndex+(tE?h:0)),s.length))===p)h=HS(s,h,c);else{if(v.push(s.slice(p,h)),v.length===d)return v;for(var g=1;g<=m.length-1;g++)if(v.push(m[g]),v.length===d)return v;h=p=y}}return v.push(s.slice(p)),v}]}),!aE,tE);var sE={exports:{}},oE={exports:{}};!function(e){e.exports=function(e){return-1!==Function.toString.call(e).indexOf("[native code]")},e.exports.__esModule=!0,e.exports.default=e.exports}(oE);var uE={exports:{}},cE={exports:{}};!function(e){e.exports=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}},e.exports.__esModule=!0,e.exports.default=e.exports}(cE),function(e){var t=vv.exports,n=cE.exports;function r(i,a,s){return n()?(e.exports=r=Reflect.construct,e.exports.__esModule=!0,e.exports.default=e.exports):(e.exports=r=function(e,n,r){var i=[null];i.push.apply(i,n);var a=new(Function.bind.apply(e,i));return r&&t(a,r.prototype),a},e.exports.__esModule=!0,e.exports.default=e.exports),r.apply(null,arguments)}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(uE),function(e){var t=gv.exports,n=vv.exports,r=oE.exports,i=uE.exports;function a(s){var o="function"==typeof Map?new Map:void 0;return e.exports=a=function(e){if(null===e||!r(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==o){if(o.has(e))return o.get(e);o.set(e,a)}function a(){return i(e,arguments,t(this).constructor)}return a.prototype=Object.create(e.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),n(a,e)},e.exports.__esModule=!0,e.exports.default=e.exports,a(s)}e.exports=a,e.exports.__esModule=!0,e.exports.default=e.exports}(sE);var lE={exports:{}};!function(e,t){(function(){var r={function:!0,object:!0}["undefined"==typeof window?"undefined":Pa(window)]&&window||this,i=t,a=e&&!e.nodeType&&e,s=i&&a&&"object"==Pa(n)&&n;!s||s.global!==s&&s.window!==s&&s.self!==s||(r=s);var o=Math.pow(2,53)-1,u=/\bOpera/,c=Object.prototype,l=c.hasOwnProperty,f=c.toString;function d(e){return(e=String(e)).charAt(0).toUpperCase()+e.slice(1)}function p(e){return e=g(e),/^(?:webOS|i(?:OS|P))/.test(e)?e:d(e)}function h(e,t){for(var n in e)l.call(e,n)&&t(e[n],n,e)}function v(e){return null==e?d(e):f.call(e).slice(8,-1)}function y(e){return String(e).replace(/([ -])(?!$)/g,"$1?")}function m(e,t){var n=null;return function(e,t){var n=-1,r=e?e.length:0;if("number"==typeof r&&r>-1&&r<=o)for(;++n<r;)t(e[n],n,e);else h(e,t)}(e,(function(r,i){n=t(n,r,i,e)})),n}function g(e){return String(e).replace(/^ +| +$/g,"")}var b=function e(t){var n=r,i=t&&"object"==Pa(t)&&"String"!=v(t);i&&(n=t,t=null);var a=n.navigator||{},s=a.userAgent||"";t||(t=s);var o,c,l=i?!!a.likeChrome:/\bChrome\b/.test(t)&&!/internal|\n/i.test(f.toString()),d="Object",b=i?d:"ScriptBridgingProxyObject",w=i?d:"Environment",k=i&&n.java?"JavaPackage":v(n.java),x=i?d:"RuntimeObject",_=/\bJava/.test(k)&&n.java,S=_&&v(n.environment)==w,E=_?"a":"α",T=_?"b":"β",R=n.document||{},C=n.operamini||n.opera,I=u.test(I=i&&C?C["[[Class]]"]:v(C))?I:C=null,O=t,P=[],A=null,j=t==s,M=j&&C&&"function"==typeof C.version&&C.version(),L=m([{label:"EdgeHTML",pattern:"Edge"},"Trident",{label:"WebKit",pattern:"AppleWebKit"},"iCab","Presto","NetFront","Tasman","KHTML","Gecko"],(function(e,n){return e||RegExp("\\b"+(n.pattern||y(n))+"\\b","i").exec(t)&&(n.label||n)})),N=function(e){return m(e,(function(e,n){return e||RegExp("\\b"+(n.pattern||y(n))+"\\b","i").exec(t)&&(n.label||n)}))}(["Adobe AIR","Arora","Avant Browser","Breach","Camino","Electron","Epiphany","Fennec","Flock","Galeon","GreenBrowser","iCab","Iceweasel","K-Meleon","Konqueror","Lunascape","Maxthon",{label:"Microsoft Edge",pattern:"(?:Edge|Edg|EdgA|EdgiOS)"},"Midori","Nook Browser","PaleMoon","PhantomJS","Raven","Rekonq","RockMelt",{label:"Samsung Internet",pattern:"SamsungBrowser"},"SeaMonkey",{label:"Silk",pattern:"(?:Cloud9|Silk-Accelerated)"},"Sleipnir","SlimBrowser",{label:"SRWare Iron",pattern:"Iron"},"Sunrise","Swiftfox","Vivaldi","Waterfox","WebPositive",{label:"Yandex Browser",pattern:"YaBrowser"},{label:"UC Browser",pattern:"UCBrowser"},"Opera Mini",{label:"Opera Mini",pattern:"OPiOS"},"Opera",{label:"Opera",pattern:"OPR"},"Chromium","Chrome",{label:"Chrome",pattern:"(?:HeadlessChrome)"},{label:"Chrome Mobile",pattern:"(?:CriOS|CrMo)"},{label:"Firefox",pattern:"(?:Firefox|Minefield)"},{label:"Firefox for iOS",pattern:"FxiOS"},{label:"IE",pattern:"IEMobile"},{label:"IE",pattern:"MSIE"},"Safari"]),U=B([{label:"BlackBerry",pattern:"BB10"},"BlackBerry",{label:"Galaxy S",pattern:"GT-I9000"},{label:"Galaxy S2",pattern:"GT-I9100"},{label:"Galaxy S3",pattern:"GT-I9300"},{label:"Galaxy S4",pattern:"GT-I9500"},{label:"Galaxy S5",pattern:"SM-G900"},{label:"Galaxy S6",pattern:"SM-G920"},{label:"Galaxy S6 Edge",pattern:"SM-G925"},{label:"Galaxy S7",pattern:"SM-G930"},{label:"Galaxy S7 Edge",pattern:"SM-G935"},"Google TV","Lumia","iPad","iPod","iPhone","Kindle",{label:"Kindle Fire",pattern:"(?:Cloud9|Silk-Accelerated)"},"Nexus","Nook","PlayBook","PlayStation Vita","PlayStation","TouchPad","Transformer",{label:"Wii U",pattern:"WiiU"},"Wii","Xbox One",{label:"Xbox 360",pattern:"Xbox"},"Xoom"]),D=function(e){return m(e,(function(e,n,r){return e||(n[U]||n[/^[a-z]+(?: +[a-z]+\b)*/i.exec(U)]||RegExp("\\b"+y(r)+"(?:\\b|\\w*\\d)","i").exec(t))&&r}))}({Apple:{iPad:1,iPhone:1,iPod:1},Alcatel:{},Archos:{},Amazon:{Kindle:1,"Kindle Fire":1},Asus:{Transformer:1},"Barnes & Noble":{Nook:1},BlackBerry:{PlayBook:1},Google:{"Google TV":1,Nexus:1},HP:{TouchPad:1},HTC:{},Huawei:{},Lenovo:{},LG:{},Microsoft:{Xbox:1,"Xbox One":1},Motorola:{Xoom:1},Nintendo:{"Wii U":1,Wii:1},Nokia:{Lumia:1},Oppo:{},Samsung:{"Galaxy S":1,"Galaxy S2":1,"Galaxy S3":1,"Galaxy S4":1},Sony:{PlayStation:1,"PlayStation Vita":1},Xiaomi:{Mi:1,Redmi:1}}),F=function(e){return m(e,(function(e,n){var r=n.pattern||y(n);return!e&&(e=RegExp("\\b"+r+"(?:/[\\d.]+|[ \\w.]*)","i").exec(t))&&(e=function(e,t,n){var r={"10.0":"10",6.4:"10 Technical Preview",6.3:"8.1",6.2:"8",6.1:"Server 2008 R2 / 7","6.0":"Server 2008 / Vista",5.2:"Server 2003 / XP 64-bit",5.1:"XP",5.01:"2000 SP1","5.0":"2000","4.0":"NT","4.90":"ME"};return t&&n&&/^Win/i.test(e)&&!/^Windows Phone /i.test(e)&&(r=r[/[\d.]+$/.exec(e)])&&(e="Windows "+r),e=String(e),t&&n&&(e=e.replace(RegExp(t,"i"),n)),p(e.replace(/ ce$/i," CE").replace(/\bhpw/i,"web").replace(/\bMacintosh\b/,"Mac OS").replace(/_PowerPC\b/i," OS").replace(/\b(OS X) [^ \d]+/i,"$1").replace(/\bMac (OS X)\b/,"$1").replace(/\/(\d)/," $1").replace(/_/g,".").replace(/(?: BePC|[ .]*fc[ \d.]+)$/i,"").replace(/\bx86\.64\b/gi,"x86_64").replace(/\b(Windows Phone) OS\b/,"$1").replace(/\b(Chrome OS \w+) [\d.]+\b/,"$1").split(" on ")[0])}(e,r,n.label||n)),e}))}(["Windows Phone","KaiOS","Android","CentOS",{label:"Chrome OS",pattern:"CrOS"},"Debian",{label:"DragonFly BSD",pattern:"DragonFly"},"Fedora","FreeBSD","Gentoo","Haiku","Kubuntu","Linux Mint","OpenBSD","Red Hat","SuSE","Ubuntu","Xubuntu","Cygwin","Symbian OS","hpwOS","webOS ","webOS","Tablet OS","Tizen","Linux","Mac OS X","Macintosh","Mac","Windows 98;","Windows "]);function B(e){return m(e,(function(e,n){var r=n.pattern||y(n);return!e&&(e=RegExp("\\b"+r+" *\\d+[.\\w_]*","i").exec(t)||RegExp("\\b"+r+" *\\w+-[\\w]*","i").exec(t)||RegExp("\\b"+r+"(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)","i").exec(t))&&((e=String(n.label&&!RegExp(r,"i").test(n.label)?n.label:e).split("/"))[1]&&!/[\d.]+/.test(e[0])&&(e[0]+=" "+e[1]),n=n.label||n,e=p(e[0].replace(RegExp(r,"i"),n).replace(RegExp("; *(?:"+n+"[_-])?","i")," ").replace(RegExp("("+n+")[-_.]?(\\w)","i"),"$1 $2"))),e}))}function q(e){return m(e,(function(e,n){return e||(RegExp(n+"(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)","i").exec(t)||0)[1]||null}))}if(L&&(L=[L]),/\bAndroid\b/.test(F)&&!U&&(o=/\bAndroid[^;]*;(.*?)(?:Build|\) AppleWebKit)\b/i.exec(t))&&(U=g(o[1]).replace(/^[a-z]{2}-[a-z]{2};\s*/i,"")||null),D&&!U?U=B([D]):D&&U&&(U=U.replace(RegExp("^("+y(D)+")[-_.\\s]","i"),D+" ").replace(RegExp("^("+y(D)+")[-_.]?(\\w)","i"),D+" $2")),(o=/\bGoogle TV\b/.exec(U))&&(U=o[0]),/\bSimulator\b/i.test(t)&&(U=(U?U+" ":"")+"Simulator"),"Opera Mini"==N&&/\bOPiOS\b/.test(t)&&P.push("running in Turbo/Uncompressed mode"),"IE"==N&&/\blike iPhone OS\b/.test(t)?(D=(o=e(t.replace(/like iPhone OS/,""))).manufacturer,U=o.product):/^iP/.test(U)?(N||(N="Safari"),F="iOS"+((o=/ OS ([\d_]+)/i.exec(t))?" "+o[1].replace(/_/g,"."):"")):"Konqueror"==N&&/^Linux\b/i.test(F)?F="Kubuntu":D&&"Google"!=D&&(/Chrome/.test(N)&&!/\bMobile Safari\b/i.test(t)||/\bVita\b/.test(U))||/\bAndroid\b/.test(F)&&/^Chrome/.test(N)&&/\bVersion\//i.test(t)?(N="Android Browser",F=/\bAndroid\b/.test(F)?F:"Android"):"Silk"==N?(/\bMobi/i.test(t)||(F="Android",P.unshift("desktop mode")),/Accelerated *= *true/i.test(t)&&P.unshift("accelerated")):"UC Browser"==N&&/\bUCWEB\b/.test(t)?P.push("speed mode"):"PaleMoon"==N&&(o=/\bFirefox\/([\d.]+)\b/.exec(t))?P.push("identifying as Firefox "+o[1]):"Firefox"==N&&(o=/\b(Mobile|Tablet|TV)\b/i.exec(t))?(F||(F="Firefox OS"),U||(U=o[1])):!N||(o=!/\bMinefield\b/i.test(t)&&/\b(?:Firefox|Safari)\b/.exec(N))?(N&&!U&&/[\/,]|^[^(]+?\)/.test(t.slice(t.indexOf(o+"/")+8))&&(N=null),(o=U||D||F)&&(U||D||/\b(?:Android|Symbian OS|Tablet OS|webOS)\b/.test(F))&&(N=/[a-z]+(?: Hat)?/i.exec(/\bAndroid\b/.test(F)?F:o)+" Browser")):"Electron"==N&&(o=(/\bChrome\/([\d.]+)\b/.exec(t)||0)[1])&&P.push("Chromium "+o),M||(M=q(["(?:Cloud9|CriOS|CrMo|Edge|Edg|EdgA|EdgiOS|FxiOS|HeadlessChrome|IEMobile|Iron|Opera ?Mini|OPiOS|OPR|Raven|SamsungBrowser|Silk(?!/[\\d.]+$)|UCBrowser|YaBrowser)","Version",y(N),"(?:Firefox|Minefield|NetFront)"])),(o=("iCab"==L&&parseFloat(M)>3?"WebKit":/\bOpera\b/.test(N)&&(/\bOPR\b/.test(t)?"Blink":"Presto"))||/\b(?:Midori|Nook|Safari)\b/i.test(t)&&!/^(?:Trident|EdgeHTML)$/.test(L)&&"WebKit"||!L&&/\bMSIE\b/i.test(t)&&("Mac OS"==F?"Tasman":"Trident")||"WebKit"==L&&/\bPlayStation\b(?! Vita\b)/i.test(N)&&"NetFront")&&(L=[o]),"IE"==N&&(o=(/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(t)||0)[1])?(N+=" Mobile",F="Windows Phone "+(/\+$/.test(o)?o:o+".x"),P.unshift("desktop mode")):/\bWPDesktop\b/i.test(t)?(N="IE Mobile",F="Windows Phone 8.x",P.unshift("desktop mode"),M||(M=(/\brv:([\d.]+)/.exec(t)||0)[1])):"IE"!=N&&"Trident"==L&&(o=/\brv:([\d.]+)/.exec(t))&&(N&&P.push("identifying as "+N+(M?" "+M:"")),N="IE",M=o[1]),j){if(function(e,t){var n=null!=e?Pa(e[t]):"number";return!(/^(?:boolean|number|string|undefined)$/.test(n)||"object"==n&&!e[t])}(n,"global"))if(_&&(O=(o=_.lang.System).getProperty("os.arch"),F=F||o.getProperty("os.name")+" "+o.getProperty("os.version")),S){try{M=n.require("ringo/engine").version.join("."),N="RingoJS"}catch(e){(o=n.system)&&o.global.system==n.system&&(N="Narwhal",F||(F=o[0].os||null))}N||(N="Rhino")}else"object"==Pa(n.process)&&!n.process.browser&&(o=n.process)&&("object"==Pa(o.versions)&&("string"==typeof o.versions.electron?(P.push("Node "+o.versions.node),N="Electron",M=o.versions.electron):"string"==typeof o.versions.nw&&(P.push("Chromium "+M,"Node "+o.versions.node),N="NW.js",M=o.versions.nw)),N||(N="Node.js",O=o.arch,F=o.platform,M=(M=/[\d.]+/.exec(o.version))?M[0]:null));else v(o=n.runtime)==b?(N="Adobe AIR",F=o.flash.system.Capabilities.os):v(o=n.phantom)==x?(N="PhantomJS",M=(o=o.version||null)&&o.major+"."+o.minor+"."+o.patch):"number"==typeof R.documentMode&&(o=/\bTrident\/(\d+)/i.exec(t))?(M=[M,R.documentMode],(o=+o[1]+4)!=M[1]&&(P.push("IE "+M[1]+" mode"),L&&(L[1]=""),M[1]=o),M="IE"==N?String(M[1].toFixed(1)):M[0]):"number"==typeof R.documentMode&&/^(?:Chrome|Firefox)\b/.test(N)&&(P.push("masking as "+N+" "+M),N="IE",M="11.0",L=["Trident"],F="Windows");F=F&&p(F)}if(M&&(o=/(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(M)||/(?:alpha|beta)(?: ?\d)?/i.exec(t+";"+(j&&a.appMinorVersion))||/\bMinefield\b/i.test(t)&&"a")&&(A=/b/i.test(o)?"beta":"alpha",M=M.replace(RegExp(o+"\\+?$"),"")+("beta"==A?T:E)+(/\d+\+?/.exec(o)||"")),"Fennec"==N||"Firefox"==N&&/\b(?:Android|Firefox OS|KaiOS)\b/.test(F))N="Firefox Mobile";else if("Maxthon"==N&&M)M=M.replace(/\.[\d.]+/,".x");else if(/\bXbox\b/i.test(U))"Xbox 360"==U&&(F=null),"Xbox 360"==U&&/\bIEMobile\b/.test(t)&&P.unshift("mobile mode");else if(!/^(?:Chrome|IE|Opera)$/.test(N)&&(!N||U||/Browser|Mobi/.test(N))||"Windows CE"!=F&&!/Mobi/i.test(t))if("IE"==N&&j)try{null===n.external&&P.unshift("platform preview")}catch(e){P.unshift("embedded")}else(/\bBlackBerry\b/.test(U)||/\bBB10\b/.test(t))&&(o=(RegExp(U.replace(/ +/g," *")+"/([.\\d]+)","i").exec(t)||0)[1]||M)?(F=((o=[o,/BB10/.test(t)])[1]?(U=null,D="BlackBerry"):"Device Software")+" "+o[0],M=null):this!=h&&"Wii"!=U&&(j&&C||/Opera/.test(N)&&/\b(?:MSIE|Firefox)\b/i.test(t)||"Firefox"==N&&/\bOS X (?:\d+\.){2,}/.test(F)||"IE"==N&&(F&&!/^Win/.test(F)&&M>5.5||/\bWindows XP\b/.test(F)&&M>8||8==M&&!/\bTrident\b/.test(t)))&&!u.test(o=e.call(h,t.replace(u,"")+";"))&&o.name&&(o="ing as "+o.name+((o=o.version)?" "+o:""),u.test(N)?(/\bIE\b/.test(o)&&"Mac OS"==F&&(F=null),o="identify"+o):(o="mask"+o,N=I?p(I.replace(/([a-z])([A-Z])/g,"$1 $2")):"Opera",/\bIE\b/.test(o)&&(F=null),j||(M=null)),L=["Presto"],P.push(o));else N+=" Mobile";(o=(/\bAppleWebKit\/([\d.]+\+?)/i.exec(t)||0)[1])&&(o=[parseFloat(o.replace(/\.(\d)$/,".0$1")),o],"Safari"==N&&"+"==o[1].slice(-1)?(N="WebKit Nightly",A="alpha",M=o[1].slice(0,-1)):M!=o[1]&&M!=(o[2]=(/\bSafari\/([\d.]+\+?)/i.exec(t)||0)[1])||(M=null),o[1]=(/\b(?:Headless)?Chrome\/([\d.]+)/i.exec(t)||0)[1],537.36==o[0]&&537.36==o[2]&&parseFloat(o[1])>=28&&"WebKit"==L&&(L=["Blink"]),j&&(l||o[1])?(L&&(L[1]="like Chrome"),o=o[1]||((o=o[0])<530?1:o<532?2:o<532.05?3:o<533?4:o<534.03?5:o<534.07?6:o<534.1?7:o<534.13?8:o<534.16?9:o<534.24?10:o<534.3?11:o<535.01?12:o<535.02?"13+":o<535.07?15:o<535.11?16:o<535.19?17:o<536.05?18:o<536.1?19:o<537.01?20:o<537.11?"21+":o<537.13?23:o<537.18?24:o<537.24?25:o<537.36?26:"Blink"!=L?"27":"28")):(L&&(L[1]="like Safari"),o=(o=o[0])<400?1:o<500?2:o<526?3:o<533?4:o<534?"4+":o<535?5:o<537?6:o<538?7:o<601?8:o<602?9:o<604?10:o<606?11:o<608?12:"12"),L&&(L[1]+=" "+(o+="number"==typeof o?".x":/[.+]/.test(o)?"":"+")),"Safari"==N&&(!M||parseInt(M)>45)?M=o:"Chrome"==N&&/\bHeadlessChrome/i.test(t)&&P.unshift("headless")),"Opera"==N&&(o=/\bzbov|zvav$/.exec(F))?(N+=" ",P.unshift("desktop mode"),"zvav"==o?(N+="Mini",M=null):N+="Mobile",F=F.replace(RegExp(" *"+o+"$"),"")):"Safari"==N&&/\bChrome\b/.exec(L&&L[1])?(P.unshift("desktop mode"),N="Chrome Mobile",M=null,/\bOS X\b/.test(F)?(D="Apple",F="iOS 4.3+"):F=null):/\bSRWare Iron\b/.test(N)&&!M&&(M=q("Chrome")),M&&0==M.indexOf(o=/[\d.]+$/.exec(F))&&t.indexOf("/"+o+"-")>-1&&(F=g(F.replace(o,""))),F&&-1!=F.indexOf(N)&&!RegExp(N+" OS").test(F)&&(F=F.replace(RegExp(" *"+y(N)+" *"),"")),L&&!/\b(?:Avant|Nook)\b/.test(N)&&(/Browser|Lunascape|Maxthon/.test(N)||"Safari"!=N&&/^iOS/.test(F)&&/\bSafari\b/.test(L[1])||/^(?:Adobe|Arora|Breach|Midori|Opera|Phantom|Rekonq|Rock|Samsung Internet|Sleipnir|SRWare Iron|Vivaldi|Web)/.test(N)&&L[1])&&(o=L[L.length-1])&&P.push(o),P.length&&(P=["("+P.join("; ")+")"]),D&&U&&U.indexOf(D)<0&&P.push("on "+D),U&&P.push((/^on /.test(P[P.length-1])?"":"on ")+U),F&&(o=/ ([\d.+]+)$/.exec(F),c=o&&"/"==F.charAt(F.length-o[0].length-1),F={architecture:32,family:o&&!c?F.replace(o[0],""):F,version:o?o[1]:null,toString:function(){var e=this.version;return this.family+(e&&!c?" "+e:"")+(64==this.architecture?" 64-bit":"")}}),(o=/\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(O))&&!/\bi686\b/i.test(O)?(F&&(F.architecture=64,F.family=F.family.replace(RegExp(" *"+o),"")),N&&(/\bWOW64\b/i.test(t)||j&&/\w(?:86|32)$/.test(a.cpuClass||a.platform)&&!/\bWin64; x64\b/i.test(t))&&P.unshift("32-bit")):F&&/^OS X/.test(F.family)&&"Chrome"==N&&parseFloat(M)>=39&&(F.architecture=64),t||(t=null);var z={};return z.description=t,z.layout=L&&L[0],z.manufacturer=D,z.name=N,z.prerelease=A,z.product=U,z.ua=t,z.version=N&&M,z.os=F||{architecture:null,family:null,version:null,toString:function(){return"null"}},z.parse=e,z.toString=function(){return this.description||""},z.version&&P.unshift(M),z.name&&P.unshift(N),F&&N&&(F!=String(F).split(" ")[0]||F!=N.split(" ")[0]&&!U)&&P.push(U?"("+F+")":"on "+F),P.length&&(z.description=P.join(" ")),z}();i&&a?h(b,(function(e,t){i[t]=e})):r.platform=b}).call(n)}(lE,lE.exports);var fE=Fe,dE=Dt,pE=Er,hE=k,vE=Up,yE=$p;Lp("match",(function(e,t,n){return[function(t){var n=hE(this),r=null==t?void 0:t[e];return void 0!==r?r.call(t,n):new RegExp(t)[e](pE(n))},function(e){var r=fE(this),i=pE(e),a=n(t,r,i);if(a.done)return a.value;if(!r.global)return yE(r,i);var s=r.unicode;r.lastIndex=0;for(var o,u=[],c=0;null!==(o=yE(r,i));){var l=pE(o[0]);u[c]=l,""===l&&(r.lastIndex=vE(i,dE(r.lastIndex),s)),c++}return 0===c?null:u}]}));var mE=Object.is||function(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t},gE=Fe,bE=k,wE=mE,kE=Er,xE=$p;Lp("search",(function(e,t,n){return[function(t){var n=bE(this),r=null==t?void 0:t[e];return void 0!==r?r.call(t,n):new RegExp(t)[e](kE(n))},function(e){var r=gE(this),i=kE(e),a=n(t,r,i);if(a.done)return a.value;var s=r.lastIndex;wE(s,0)||(r.lastIndex=0);var o=xE(r,i);return wE(r.lastIndex,s)||(r.lastIndex=s),null===o?-1:o.index}]}));var _E=Cn,SE=zt,EE=Lt,TE=Dt,RE=X,CE=Gr,IE=ka,OE=la("splice"),PE=Math.max,AE=Math.min,jE=9007199254740991,ME="Maximum allowed length exceeded";_E({target:"Array",proto:!0,forced:!OE},{splice:function(e,t){var n,r,i,a,s,o,u=RE(this),c=TE(u.length),l=SE(e,c),f=arguments.length;if(0===f?n=r=0:1===f?(n=0,r=c-l):(n=f-2,r=AE(PE(EE(t),0),c-l)),c+n-r>jE)throw TypeError(ME);for(i=CE(u,r),a=0;a<r;a++)(s=l+a)in u&&IE(i,a,u[s]);if(i.length=r,n<r){for(a=l;a<c-r;a++)o=a+n,(s=a+r)in u?u[o]=u[s]:delete u[o];for(a=c;a>c-r+n;a--)delete u[a-1]}else if(n>r)for(a=c-r;a>l;a--)o=a+n-1,(s=a+r-1)in u?u[o]=u[s]:delete u[o];for(a=0;a<n;a++)u[a+l]=arguments[a+2];return u.length=c-r+n,i}}),function(e){var t=void 0!==t?t:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};Object.defineProperty(e,"__esModule",{value:!0});var n=Vg.exports,r=dv.exports,i=mv.exports,a=Py.exports,s=hv.exports,o=yv.exports,u=gv.exports,c=pv.exports,l=jy.exports,f=Jg,d=Hh.exports,p=gh,h=Sf.exports,v=ib.exports,y=Cb,m=sE.exports,g=sg,b=lE.exports;function w(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}function k(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var x=w(n),_=w(r),S=w(i),E=w(a),T=w(s),R=w(o),C=w(u),I=w(c),O=w(l),P=w(f),A=w(d),j=k(h),M=k(v),L=w(m),N=k(b);function U(){}function D(){D.init.call(this)}function F(e){return void 0===e._maxListeners?D.defaultMaxListeners:e._maxListeners}function B(e,t,n){if(t)e.call(n);else for(var r=e.length,i=K(e,r),a=0;a<r;++a)i[a].call(n)}function q(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,a=K(e,i),s=0;s<i;++s)a[s].call(n,r)}function z(e,t,n,r,i){if(t)e.call(n,r,i);else for(var a=e.length,s=K(e,a),o=0;o<a;++o)s[o].call(n,r,i)}function W(e,t,n,r,i,a){if(t)e.call(n,r,i,a);else for(var s=e.length,o=K(e,s),u=0;u<s;++u)o[u].call(n,r,i,a)}function G(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,a=K(e,i),s=0;s<i;++s)a[s].apply(n,r)}function $(e,t,n,r){var i,a,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),s=a[t]):(a=e._events=new U,e._eventsCount=0),s){if("function"==typeof s?s=a[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),!s.warned&&(i=F(e))&&i>0&&s.length>i){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,o=u,"function"==typeof console.warn?console.warn(o):console.log(o)}}else s=a[t]=n,++e._eventsCount;return e}function V(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function J(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function K(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}U.prototype=Object.create(null),D.EventEmitter=D,D.usingDomains=!1,D.prototype.domain=void 0,D.prototype._events=void 0,D.prototype._maxListeners=void 0,D.defaultMaxListeners=10,D.init=function(){this.domain=null,D.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new U,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},D.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},D.prototype.getMaxListeners=function(){return F(this)},D.prototype.emit=function(e){var t,n,r,i,a,s,o,u="error"===e;if(s=this._events)u=u&&null==s.error;else if(!u)return!1;if(o=this.domain,u){if(t=arguments[1],!o){if(t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=s[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:B(n,l,this);break;case 2:q(n,l,this,arguments[1]);break;case 3:z(n,l,this,arguments[1],arguments[2]);break;case 4:W(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),a=1;a<r;a++)i[a-1]=arguments[a];G(n,l,this,i)}return!0},D.prototype.addListener=function(e,t){return $(this,e,t,!1)},D.prototype.on=D.prototype.addListener,D.prototype.prependListener=function(e,t){return $(this,e,t,!0)},D.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,V(this,e,t)),this},D.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,V(this,e,t)),this},D.prototype.removeListener=function(e,t){var n,r,i,a,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new U:(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new U,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}(n,i);r.removeListener&&this.emit("removeListener",e,s||t)}return this},D.prototype.off=function(e,t){return this.removeListener(e,t)},D.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new U,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new U:delete n[e]),this;if(0===arguments.length){for(var r,i=Object.keys(n),a=0;a<i.length;++a)"removeListener"!==(r=i[a])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new U,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},D.prototype.listeners=function(e){var t,n,r=this._events;return n=r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},D.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):J.call(e,t)},D.prototype.listenerCount=J,D.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var H=j.getLogger("twilsock");function Y(e,t){return["".concat((new Date).toISOString()," Twilsock ").concat(e,":")].concat(Array.from(t))}var Q=function(){function e(t){I.default(this,e),O.default(this,"prefix",""),this.prefix=null!=t&&t.length>0?" "+t+":":""}return _.default(e,[{key:"setLevel",value:function(e){H.setLevel(e)}},{key:"trace",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.trace.apply(null,Y("T",t))}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.debug.apply(null,Y("D",t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.info.apply(null,Y("I",t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.warn.apply(null,Y("W",t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.error.apply(null,Y("E",t))}}],[{key:"setLevel",value:function(e){H.setLevel(e)}},{key:"trace",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.trace.apply(null,Y("T",t))}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.debug.apply(null,Y("D",t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.info.apply(null,Y("I",t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.warn.apply(null,Y("W",t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];H.error.apply(null,Y("E",t))}}]),e}(),X=new Q(""),Z="0.12.2",ee=function(){function e(t,n,r){I.default(this,e),O.default(this,"confirmedCapabilities",new Set),this.activeGrant=n,this._token=t;var i=r.region||"us1",a="wss://tsock.".concat(i,".twilio.com/v3/wsconnect"),s=r.twilsock||r.Twilsock||{};this.url=s.uri||a,this._continuationToken=r.continuationToken?r.continuationToken:null,this.logLevel=r.logLevel?r.logLevel:"error",this.retryPolicy=r.retryPolicy?r.retryPolicy:{min:1e3,max:12e4,randomness:.2},this.clientMetadata=r.clientMetadata?r.clientMetadata:{},this.clientMetadata.ver=Z,this.initRegistrations=r.initRegistrations?r.initRegistrations:null,this.tweaks=r.tweaks?r.tweaks:null}return _.default(e,[{key:"token",get:function(){return this._token}},{key:"continuationToken",get:function(){return this._continuationToken}},{key:"updateToken",value:function(e){this._token=e}},{key:"updateContinuationToken",value:function(e){this._continuationToken=e}}]),e}(),te=function e(t){I.default(this,e),this.id=t||"TM".concat(y.v4())};function ne(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var re=function(e){T.default(n,e);var t=ne(n);function n(e,r,i,a,s){var o;return I.default(this,n),o=t.call(this),O.default(S.default(o),"method","init"),o.token=e,o.continuation_token=r,o.metadata=i,o.registrations=a,o.tweaks=s,o.capabilities=["client_update","offline_storage","telemetry.v1"],o}return n}(te);function ie(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var ae=function(e){T.default(n,e);var t=ie(n);function n(e,r,i,a,s,o,u){var c;return I.default(this,n),(c=t.call(this,e)).continuationToken=r,c.continuationTokenStatus=a,c.offlineStorage=s,c.initRegistrations=o,c.debugInfo=u,c.confirmedCapabilities=i,c}return n}(te);function se(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var oe=function(e){T.default(n,e);var t=se(n);function n(e){var r;return I.default(this,n),r=t.call(this),O.default(S.default(r),"method","update"),r.token=e,r}return n}(te);function ue(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Message=function(e){T.default(Message,e);var t=ue(Message);function Message(e,n,r){var i;return I.default(this,Message),i=t.call(this),O.default(S.default(i),"method","message"),i.active_grant=e,i.payload_type=n,i.http_request=r,i}return Message}(te);function ce(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var le=function(e){T.default(n,e);var t=ce(n);function n(e){var r;return I.default(this,n),r=t.call(this,e),O.default(S.default(r),"method","reply"),O.default(S.default(r),"payload_type","application/json"),O.default(S.default(r),"status",{code:200,status:"OK"}),r}return n}(te);function fe(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var de=function(e){T.default(n,e);var t=fe(n);function n(){var e;return I.default(this,n),e=t.call(this),O.default(S.default(e),"method","close"),e}return n}(te);function pe(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var he=function e(t,n,r,i,a,s){I.default(this,e),this.start=t,this.end=n,this.title=r,this.details=i,this.id=a,this.type=s},ve=function(e){T.default(n,e);var t=pe(n);function n(e){var r;return I.default(this,n),r=t.call(this),O.default(S.default(r),"method","telemetry.v1"),r.events=e,r}return n}(te);function ye(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode(Number("0x"+t))})).length}function me(e){var t=encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode(Number("0x"+t))})),n=new Uint8Array(t.length);return Array.prototype.forEach.call(t,(function(e,t){n[t]=e.charCodeAt(0)})),n}function ge(e){var t=Array.prototype.map.call(e,(function(e){return String.fromCharCode(e)})).join("").replace(/(.)/g,(function(e,t){var n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n="0"+n),"%"+n}));return decodeURIComponent(t)}function be(e){return JSON.parse(ge(e))}var we=function(){function e(){I.default(this,e)}return _.default(e,null,[{key:"parse",value:function(e){var t,n,r=new Uint8Array(e),i=function(e){for(var t="",n=0;n<e.length;++n){var r=String.fromCharCode(e[n]);if(t+=r,"\r"===r){n+=2;break}}var i=t.split(" ");return{size:n,protocol:i[0],version:i[1],headerSize:Number(i[2])}}(r);if("TWILSOCK"!==i.protocol||"V3.0"!==i.version)return X.error("unsupported protocol: ".concat(i.protocol," ver ").concat(i.version)),null;try{t=be(r.subarray(i.size,i.size+i.headerSize))}catch(t){return X.error("failed to parse message header",t,e),null}if(X.debug("message received: ",t.method),X.trace("message received: ",t),t.payload_size>0){var a=2+i.size+i.headerSize,s=t.payload_size;if(t.hasOwnProperty("payload_type")&&0!==t.payload_type.indexOf("application/json"))0===t.payload_type.indexOf("text/plain")&&(n=ge(r.subarray(a,a+s)));else try{n=be(r.subarray(a,a+s))}catch(t){return X.error("failed to parse message body",t,e),null}}return{method:t.method,header:t,payload:n}}},{key:"createPacket",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";e.payload_size=ye(t);var n=JSON.stringify(e),r="TWILSOCK V3.0 "+ye(n);X.debug("send request:",r+n+t);var i=me(r+"\r\n"+n+"\r\n"+t);return i.buffer}}]),e}();function ke(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var xe=function(e){T.default(n,e);var t=ke(n);function n(e){return I.default(this,n),t.call(this,e)}return n}(L.default(Error));function _e(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Se=function(e){T.default(n,e);var t=_e(n);function n(e,r){var i;return I.default(this,n),(i=t.call(this,e)).reply=r,i}return n}(xe);function Ee(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 Te(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Ee(Object(n),!0).forEach((function(t){O.default(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ee(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Re(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Ce=function(e){T.default(n,e);var t=Re(n);function n(e){var r;return I.default(this,n),r=t.call(this),O.default(S.default(r),"newBackoff",null),O.default(S.default(r),"usedBackoff",null),O.default(S.default(r),"retrier",null),r.options=e?Te({},e):{},r}return _.default(n,[{key:"inProgress",get:function(){return!!this.retrier}},{key:"start",value:function(){if(this.inProgress)throw new Error("Already waiting for next attempt, call finishAttempt(success : boolean) to finish it");this.createRetrier()}},{key:"stop",value:function(){this.cleanRetrier(),this.newBackoff=null,this.usedBackoff=null}},{key:"modifyBackoff",value:function(e){this.newBackoff=e}},{key:"attemptFailed",value:function(){if(!this.inProgress)throw new Error("No attempt is in progress");var e,t;this.newBackoff?!this.usedBackoff||this.usedBackoff<this.newBackoff?this.createRetrier():null===(e=this.retrier)||void 0===e||e.failed(new Error):null===(t=this.retrier)||void 0===t||t.failed(new Error)}},{key:"cancel",value:function(){var e;null===(e=this.retrier)||void 0===e||e.cancel()}},{key:"cleanRetrier",value:function(){var e,t;null===(e=this.retrier)||void 0===e||e.removeAllListeners(),null===(t=this.retrier)||void 0===t||t.cancel(),this.retrier=null}},{key:"getRetryPolicy",value:function(){var e=Te({},this.options);return this.newBackoff&&(e.min=this.newBackoff,e.max=this.options.max&&this.options.max>this.newBackoff?this.options.max:this.newBackoff),e.maxAttemptsCount=this.options.maxAttemptsCount?this.options.maxAttemptsCount+1:void 0,e}},{key:"createRetrier",value:function(){var e=this;this.cleanRetrier();var t=this.getRetryPolicy();this.retrier=new g.Retrier(t),this.retrier.once("attempt",(function(){var t,n;null===(t=e.retrier)||void 0===t||t.on("attempt",(function(){return e.emit("attempt")})),null===(n=e.retrier)||void 0===n||n.failed(new Error("Skipping first attempt"))})),this.retrier.on("failed",(function(t){return e.emit("failed",t)})),this.usedBackoff=this.newBackoff,this.newBackoff=null,this.retrier.start()}}]),n}(D);function Ie(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Oe=function(e){T.default(i,e);var t,n,r=Ie(i);function i(e,t,n){var a;I.default(this,i),a=r.call(this),O.default(S.default(a),"disconnectingTimer",null),O.default(S.default(a),"disconnectedPromiseResolve",null),O.default(S.default(a),"terminalStates",["disconnected","rejected"]),O.default(S.default(a),"tokenExpiredSasCode",20104),O.default(S.default(a),"terminationReason","Connection is not initialized"),a.websocket=e,a.websocket.on("connected",(function(){return a.fsm.socketConnected()})),a.websocket.on("disconnected",(function(){return a.fsm.socketClosed()})),a.websocket.on("message",(function(e){return a.onIncomingMessage(e)})),a.websocket.on("socketError",(function(e){return a.emit("connectionError",{terminal:!1,message:"Socket error: ".concat(e.message),httpStatusCode:null,errorCode:null})})),a.transport=t,a.config=n,a.retrier=new Ce(n.retryPolicy),a.retrier.on("attempt",(function(){return a.retry()})),a.retrier.on("failed",(function(e){X.warn("Retrying failed: ".concat(e.message)),a.disconnect()})),"undefined"!=typeof window&&void 0!==window.addEventListener&&(window.addEventListener("online",(function(){X.debug("Browser reported connectivity state: online"),a.resetBackoff(),a.fsm.systemOnline()})),window.addEventListener("offline",(function(){X.debug("Browser reported connectivity state: offline"),a.websocket.close(),a.fsm.socketClosed()})));var s=M.factory({init:"disconnected",transitions:[{name:"userConnect",from:["disconnected","rejected"],to:"connecting"},{name:"userConnect",from:["connecting","connected"]},{name:"userDisconnect",from:["connecting","initialising","connected","updating","retrying","rejected","waitSocketClosed","waitOffloadSocketClosed"],to:"disconnecting"},{name:"userRetry",from:["retrying"],to:"connecting"},{name:"socketConnected",from:["connecting"],to:"initialising"},{name:"socketClosed",from:["connecting","initialising","connected","updating","error","waitOffloadSocketClosed"],to:"retrying"},{name:"socketClosed",from:["disconnecting"],to:"disconnected"},{name:"socketClosed",from:["waitSocketClosed"],to:"disconnected"},{name:"socketClosed",from:["rejected"],to:"rejected"},{name:"initSuccess",from:["initialising"],to:"connected"},{name:"initError",from:["initialising"],to:"error"},{name:"tokenRejected",from:["initialising","updating"],to:"rejected"},{name:"protocolError",from:["initialising","connected","updating"],to:"error"},{name:"receiveClose",from:["initialising","connected","updating"],to:"waitSocketClosed"},{name:"receiveOffload",from:["initialising","connected","updating"],to:"waitOffloadSocketClosed"},{name:"unsupportedProtocol",from:["initialising","connected","updating"],to:"unsupported"},{name:"receiveFatalClose",from:["initialising","connected","updating"],to:"unsupported"},{name:"userUpdateToken",from:["disconnected","rejected","connecting","retrying"],to:"connecting"},{name:"userUpdateToken",from:["connected"],to:"updating"},{name:"updateSuccess",from:["updating"],to:"connected"},{name:"updateError",from:["updating"],to:"error"},{name:"userSend",from:["connected"],to:"connected"},{name:"systemOnline",from:["retrying"],to:"connecting"}],methods:{onConnecting:function(){a.setupSocket(),a.emit("connecting")},onEnterInitialising:function(){a.sendInit()},onLeaveInitialising:function(){a.cancelInit()},onEnterUpdating:function(){a.sendUpdate()},onLeaveUpdating:function(){a.cancelUpdate()},onEnterRetrying:function(){a.initRetry(),a.emit("connecting")},onEnterConnected:function(){a.resetBackoff(),a.onConnected()},onUserUpdateToken:function(){a.resetBackoff()},onTokenRejected:function(){a.resetBackoff(),a.closeSocket(!0),a.finalizeSocket()},onUserDisconnect:function(){a.closeSocket(!0)},onEnterDisconnecting:function(){a.startDisconnectTimer()},onLeaveDisconnecting:function(){a.cancelDisconnectTimer()},onEnterWaitSocketClosed:function(){a.startDisconnectTimer()},onLeaveWaitSocketClosed:function(){a.cancelDisconnectTimer()},onEnterWaitOffloadSocketClosed:function(){a.startDisconnectTimer()},onLeaveWaitOffloadSocketClosed:function(){a.cancelDisconnectTimer()},onDisconnected:function(){a.resetBackoff(),a.finalizeSocket()},onReceiveClose:function(){a.onCloseReceived()},onReceiveOffload:function(e,t){X.debug("onreceiveoffload: ",t),a.modifyBackoff(t.body),a.onCloseReceived()},onUnsupported:function(){a.closeSocket(!0),a.finalizeSocket()},onError:function(e,t){a.closeSocket(t),a.finalizeSocket()},onEnterState:function(e){"none"!==e.from&&a.changeState(e)},onInvalidTransition:function(e,t,n){X.warn("FSM: unexpected transition",t,n)}}});return a.fsm=new s,a}return _.default(i,[{key:"changeState",value:function(e){X.debug("FSM: ".concat(e.transition,": ").concat(e.from," --\x3e ").concat(e.to)),this.lastEmittedState!==this.state&&(this.lastEmittedState=this.state,this.emit("stateChanged",this.state))}},{key:"resetBackoff",value:function(){X.trace("resetBackoff"),this.retrier.stop()}},{key:"modifyBackoff",value:function(e){X.trace("modifyBackoff",e);var t=e?e.backoff_policy:null;t&&"number"==typeof t.reconnect_min_ms&&this.retrier.modifyBackoff(t.reconnect_min_ms)}},{key:"startDisconnectTimer",value:function(){var e=this;X.trace("startDisconnectTimer"),this.disconnectingTimer&&(clearTimeout(this.disconnectingTimer),this.disconnectingTimer=null),this.disconnectingTimer=setTimeout((function(){X.debug("disconnecting is timed out"),e.closeSocket(!0)}),3e3)}},{key:"cancelDisconnectTimer",value:function(){X.trace("cancelDisconnectTimer"),this.disconnectingTimer&&(clearTimeout(this.disconnectingTimer),this.disconnectingTimer=null)}},{key:"isConnected",get:function(){return"connected"===this.state&&this.websocket.isConnected}},{key:"state",get:function(){switch(this.fsm.state){case"connecting":case"initialising":case"retrying":case"error":return"connecting";case"updating":case"connected":return"connected";case"rejected":return"denied";case"disconnecting":case"waitSocketClosed":case"waitOffloadSocketClosed":return"disconnecting";default:return"disconnected"}}},{key:"initRetry",value:function(){X.debug("initRetry"),this.retrier.inProgress?this.retrier.attemptFailed():this.retrier.start()}},{key:"retry",value:function(){"connecting"!=this.fsm.state?(X.trace("retry"),this.websocket.close(),this.fsm.userRetry()):X.trace("can\t retry as already connecting")}},{key:"onConnected",value:function(){this.emit("connected")}},{key:"finalizeSocket",value:function(){X.trace("finalizeSocket"),this.websocket.close(),this.emit("disconnected"),this.disconnectedPromiseResolve&&(this.disconnectedPromiseResolve(),this.disconnectedPromiseResolve=null)}},{key:"setupSocket",value:function(){X.trace("setupSocket:",this.config.token),this.emit("beforeConnect"),this.websocket.connect()}},{key:"onIncomingMessage",value:function(e){var t=we.parse(e);if(t){var n=t.method,r=t.header,i=t.payload;if("reply"!==n&&this.confirmReceiving(r),"notification"===n)this.emit("message",r.message_type,i);else if("reply"===r.method)this.transport.processReply({id:r.id,status:r.status,header:r,body:i});else if("client_update"===r.method)"token_about_to_expire"===r.client_update_type&&this.emit("tokenAboutToExpire");else if("close"===r.method)if(308===r.status.code)X.debug("Connection has been offloaded"),this.fsm.receiveOffload({status:r.status.status,body:i});else if(406===r.status.code){var a="Server closed connection because can't parse protocol: ".concat(JSON.stringify(r.status));this.emitReplyConnectionError(a,r,!0),X.error(a),this.fsm.receiveFatalClose()}else 417===r.status.code?(X.error("Server closed connection because can't parse client reply: ".concat(JSON.stringify(r.status))),this.fsm.receiveFatalClose(r.status.status)):410===r.status.code?(X.warn("Server closed connection: ".concat(JSON.stringify(r.status))),this.fsm.receiveClose(r.status.status),this.emit("tokenExpired")):401===r.status.code?(X.error("Server closed connection: ".concat(JSON.stringify(r.status))),this.fsm.receiveClose(r.status.status)):(X.warn("unexpected message: ",r.status),this.fsm.receiveOffload({status:r.status.status,body:null}))}}},{key:"sendInit",value:(n=x.default(P.default.mark((function e(){var t,n;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return X.trace("sendInit"),e.prev=1,this.emit("beforeSendInit"),e.next=5,this.transport.sendInit();case 5:t=e.sent,this.config.updateContinuationToken(t.continuationToken),this.config.confirmedCapabilities=t.confirmedCapabilities,this.fsm.initSuccess(t),this.emit("initialized",t),this.emit("tokenUpdated"),e.next=17;break;case 13:e.prev=13,e.t0=e.catch(1),e.t0 instanceof Se?(n=!1,X.warn("Init rejected by server: ".concat(JSON.stringify(e.t0.reply.status))),this.emit("sendInitFailed"),401===e.t0.reply.status.code||403===e.t0.reply.status.code?(n=!0,this.fsm.tokenRejected(e.t0.reply.status),e.t0.reply.status.errorCode===this.tokenExpiredSasCode&&this.emit("tokenExpired")):429===e.t0.reply.status.code?(this.modifyBackoff(e.t0.reply.body),this.fsm.initError(!0)):500===e.t0.reply.status.code?this.fsm.initError(!1):this.fsm.initError(!0),this.emitReplyConnectionError(e.t0.message,e.t0.reply,n)):(this.terminationReason=e.t0.message,this.emit("connectionError",{terminal:!0,message:"Unknown error during connection initialisation: ".concat(e.t0.message,"\n").concat(JSON.stringify(e.t0,null,2)),httpStatusCode:null,errorCode:null}),this.fsm.initError(!0)),this.emit("tokenUpdated",e.t0);case 17:case"end":return e.stop()}}),e,this,[[1,13]])}))),function(){return n.apply(this,arguments)})},{key:"sendUpdate",value:(t=x.default(P.default.mark((function e(){var t,n,r;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return X.trace("sendUpdate"),t=new oe(this.config.token),e.prev=2,e.next=5,this.transport.sendWithReply(t);case 5:n=e.sent,this.fsm.updateSuccess(n.body),this.emit("tokenUpdated"),e.next=14;break;case 10:e.prev=10,e.t0=e.catch(2),e.t0 instanceof Se?(r=!1,X.warn("Token update rejected by server: ".concat(JSON.stringify(e.t0.reply.status))),401===e.t0.reply.status.code||403===e.t0.reply.status.code?(r=!0,this.fsm.tokenRejected(e.t0.reply.status),e.t0.reply.status.errorCode===this.tokenExpiredSasCode&&this.emit("tokenExpired")):429===e.t0.reply.status.code?(this.modifyBackoff(e.t0.reply.body),this.fsm.updateError(e.t0.reply.status)):this.fsm.updateError(e.t0.reply.status),this.emitReplyConnectionError(e.t0.message,e.t0.reply,r)):(this.emit("error",!1,e.t0.message,null,null),this.fsm.updateError(e.t0)),this.emit("tokenUpdated",e.t0);case 14:case"end":return e.stop()}}),e,this,[[2,10]])}))),function(){return t.apply(this,arguments)})},{key:"emitReplyConnectionError",value:function(e,t,n){var r=t.status&&t.status.description?t.status.description:e,i=t.status.code,a=t.status&&t.status.errorCode?t.status.errorCode:null;n&&(this.terminationReason=r),this.emit("connectionError",{terminal:n,message:"Connection error: ".concat(r),httpStatusCode:i,errorCode:a})}},{key:"cancelInit",value:function(){X.trace("cancelInit")}},{key:"cancelUpdate",value:function(){X.trace("cancelUpdate")}},{key:"confirmReceiving",value:function(e){X.trace("confirmReceiving");try{this.transport.send(new le(e.id))}catch(e){X.debug("failed to confirm packet receiving",e)}}},{key:"closeSocket",value:function(e){var t=this;X.trace("closeSocket (graceful: ".concat(e,")")),e&&this.transport.isConnected&&this.transport.sendClose(),this.websocket.close(),setTimeout((function(){return t.fsm.socketClosed()}),0)}},{key:"connect",value:function(){X.trace("connect"),this.fsm.userConnect()}},{key:"disconnect",value:function(){var e=this;return X.trace("disconnect"),this.fsm.is("disconnected")?Promise.resolve():new Promise((function(t){e.disconnectedPromiseResolve=t,e.fsm.userDisconnect()}))}},{key:"updateToken",value:function(e){var t=this;return X.trace("updateToken:",e),new Promise((function(e,n){t.once("tokenUpdated",(function(t){t?n(t):e()})),t.fsm.userUpdateToken()}))}},{key:"isTerminalState",get:function(){return-1!==this.terminalStates.indexOf(this.fsm.state)}},{key:"getTerminationReason",get:function(){return this.terminationReason}},{key:"onCloseReceived",value:function(){this.websocket.close()}}]),i}(D),Pe=function(){function e(){I.default(this,e)}return _.default(e,null,[{key:"getMetadata",value:function(e){var t,n,r,i,a,s,o,u,c=e&&e.clientMetadata?e.clientMetadata:{},l={env:null!==(t=N.name)&&void 0!==t?t:"unknown",envv:null!==(n=N.version)&&void 0!==n?n:"unknown",os:null!==(r=null===(i=N.os)||void 0===i?void 0:i.family)&&void 0!==r?r:"unknown",osv:null!==(a=null===(s=N.os)||void 0===s?void 0:s.version)&&void 0!==a?a:"unknown",osa:null!==(o=null===(u=N.os)||void 0===u?void 0:u.architecture)&&void 0!==o?o:"unknown",sdk:"js-default"},f={};return["ver","env","envv","os","osv","osa","type","sdk","sdkv","dev","devv","devt","app","appv"].filter((function(e){return e in c||e in l})).forEach((function(e){return f[e]=e in c?c[e]:l[e]})),f}}]),e}();var Ae=function(){function e(t,n){var r=this;I.default(this,e),this.config=n,this.activeRequests=new Map,this.channel=t,this.channel.on("reply",(function(e){return r.processReply(e)})),this.channel.on("disconnected",(function(){r.activeRequests.forEach((function(e){clearTimeout(e.timeout),e.reject(new xe("disconnected"))})),r.activeRequests.clear()}))}var t;return _.default(e,[{key:"isConnected",get:function(){return this.channel.isConnected}},{key:"processReply",value:function(e){var t,n=this.activeRequests.get(e.id);n&&(clearTimeout(n.timeout),this.activeRequests.delete(e.id),(t=e.status.code)>=200&&t<300?n.resolve(e):(n.reject(new Se("Transport failure: "+e.status.status,e)),X.trace("message rejected")))}},{key:"storeRequest",value:function(e,t,n){var r={resolve:t,reject:n,timeout:setTimeout((function(){X.trace("request",e,"is timed out"),n(new xe("Twilsock: request timeout: "+e))}),3e4)};this.activeRequests.set(e,r)}},{key:"shutdown",value:function(){this.activeRequests.forEach((function(e){clearTimeout(e.timeout),e.reject(new xe("Twilsock: request cancelled by user"))})),this.activeRequests.clear()}},{key:"sendInit",value:(t=x.default(P.default.mark((function e(){var t,n,r;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return X.trace("sendInit"),t=Pe.getMetadata(this.config),n=new re(this.config.token,this.config.continuationToken,t,this.config.initRegistrations,this.config.tweaks),e.next=5,this.sendWithReply(n);case 5:return r=e.sent,e.abrupt("return",new ae(r.id,r.header.continuation_token,new Set(r.header.capabilities),r.header.continuation_token_status,r.header.offline_storage,r.header.init_registrations,r.header.debug_info));case 7:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"sendClose",value:function(){var e=new de;this.send(e)}},{key:"sendWithReply",value:function(e,t){var n=this;return new Promise((function(r,i){var a=n.send(e,t);n.storeRequest(a,r,i)}))}},{key:"send",value:function(e,t){e.id=e.id||"TM".concat(y.v4());var n=we.createPacket(e,function(e){switch(A.default(e)){case"undefined":return"";case"object":return JSON.stringify(e);default:return e}}(t));try{return this.channel.send(n),e.id}catch(t){throw X.debug("failed to send ",e,t),X.trace(t.stack),t}}}]),e}();function je(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Me=function(e){T.default(r,e);var n=je(r);function r(e){var i;return I.default(this,r),i=n.call(this),O.default(S.default(i),"socket",null),i.url=e,i.url=e,i.WebSocket=t.WebSocket||t.MozWebSocket||{},i}return _.default(r,[{key:"isConnected",get:function(){return!!this.socket&&1===this.socket.readyState}},{key:"connect",value:function(){var e,t=this;X.trace("connecting to socket");try{e=new this.WebSocket(this.url)}catch(e){return X.debug("Socket error: ".concat(this.url)),void this.emit("socketError",e)}e.binaryType="arraybuffer",e.onopen=function(){X.debug("socket opened ".concat(t.url)),t.emit("connected")},e.onclose=function(e){X.debug("socket closed",e),t.emit("disconnected",e)},e.onerror=function(e){X.debug("Socket error:",e),t.emit("socketError",e)},e.onmessage=function(e){t.emit("message",e.data)},this.socket=e}},{key:"send",value:function(e){return this.socket&&this.socket.send(e)}},{key:"close",value:function(){if(X.trace("closing socket"),this.socket){this.socket.onopen=null,this.socket.onclose=null,this.socket.onerror=null,this.socket.onmessage=null;try{this.socket.close()}finally{}}}}]),r}(D);function Le(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Ne=function(e){T.default(u,e);var t,n,r,i,a,s,o=Le(u);function u(e){var t;return I.default(this,u),(t=o.call(this)).transport=e,t.registrations=new Map,t.registrationsInProgress=new Map,t}return _.default(u,[{key:"putNotificationContext",value:(s=x.default(P.default.mark((function e(t,n){var r;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={method:"put_notification_ctx",notification_ctx_id:t},e.next=3,this.transport.sendWithReply(r,n);case 3:case"end":return e.stop()}}),e,this)}))),function(e,t){return s.apply(this,arguments)})},{key:"deleteNotificationContext",value:(a=x.default(P.default.mark((function e(t){var n;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={method:"delete_notification_ctx",notification_ctx_id:t},e.next=3,this.transport.sendWithReply(n);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"updateRegistration",value:(i=x.default(P.default.mark((function e(t,n){var r,i;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return X.debug("update registration for context",t),(r=this.registrationsInProgress.get(t))||(r=new Set,this.registrationsInProgress.set(t,r)),i=y.v4(),r.add(i),e.prev=5,e.next=8,this.putNotificationContext(t,n);case 8:X.debug("registration attempt succeeded for context",n),r.delete(i),0===r.size&&(this.registrationsInProgress.delete(t),this.emit("registered",t)),e.next=19;break;case 13:e.prev=13,e.t0=e.catch(5),X.warn("registration attempt failed for context",n),X.debug(e.t0),r.delete(i),0===r.size&&(this.registrationsInProgress.delete(t),this.emit("registrationFailed",t,e.t0));case 19:case"end":return e.stop()}}),e,this,[[5,13]])}))),function(e,t){return i.apply(this,arguments)})},{key:"updateRegistrations",value:(r=x.default(P.default.mark((function e(){var t,n=this;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return X.trace("refreshing ".concat(this.registrations.size," registrations")),t=[],this.registrations.forEach((function(e,r){t.push(n.updateRegistration(r,e))})),e.next=5,Promise.all(t);case 5:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"setNotificationsContext",value:(n=x.default(P.default.mark((function e(t,n){return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t&&n){e.next=2;break}throw new xe("Invalid arguments provided");case 2:return this.registrations.set(t,n),e.next=5,this.updateRegistration(t,n);case 5:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"removeNotificationsContext",value:(t=x.default(P.default.mark((function e(t){return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.registrations.has(t)){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,this.deleteNotificationContext(t);case 4:this.transport.isConnected&&this.registrations.delete(t);case 5:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),u}(D);function Ue(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var De=function(e){T.default(n,e);var t=Ue(n);function n(e,r,i){var a;return I.default(this,n),(a=t.call(this,r)).status=e,a.description=r,a.body=i,a}return n}(xe);function Fe(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Be=function(e){T.default(n,e);var t=Fe(n);function n(e){return I.default(this,n),t.call(this,e)}return n}(xe);function qe(e,t){var n=function(e){var t=e.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);if(t){var n={protocol:t[1],host:t[2],hostname:t[3],port:t[4],pathname:t[5],search:t[6],hash:t[7],params:{}};if(n.search.length>0){var r=n.search.substring(1);n.params=r.split("&").map((function(e){return e.split("=")})).reduce((function(e,t){return e.hasOwnProperty(t[0])?Array.isArray(e[t[0]])?e[t[0]].push(t[1]):e[t[0]]=[e[t[0]],t[1]]:e[t[0]]=t[1],e}),{})}return n}throw new xe("Incorrect URI: "+e)}(t),r={method:e,host:n.host,path:n.pathname};return n.params&&(r.params=n.params),r}function ze(e,t,n,r,i){return{to:qe(e,t),headers:n,body:r,grant:i}}var We=function(){function e(t,n,r){I.default(this,e),this.config=r,this.transport=t,this.pendingMessages=[],this.twilsock=n}var t;return _.default(e,[{key:"saveMessage",value:function(e){var t=this;return new Promise((function(n,r){var i={message:e,resolve:n,reject:r,alreadyRejected:!1,timeout:setTimeout((function(){X.debug("request is timed out"),r(new xe("request '".concat(e.to.method,"' to '").concat(e.to.host,"' timed out"))),i.alreadyRejected=!0}),2e4)};t.pendingMessages.push(i)}))}},{key:"sendPendingMessages",value:function(){for(var e=this,t=function(){var t=e.pendingMessages[0];if(!t.alreadyRejected)try{var n=t.message;e.actualSend(n).then((function(e){return t.resolve(e)})).catch((function(e){return t.reject(e)})),clearTimeout(t.timeout)}catch(e){return X.debug("Failed to send pending message",e),"break"}e.pendingMessages.splice(0,1)};this.pendingMessages.length>0;){if("break"===t())break}}},{key:"rejectPendingMessages",value:function(){var e=this;this.pendingMessages.forEach((function(t){t.reject(new Be("Unable to connect: "+e.twilsock.getTerminationReason)),t.alreadyRejected=!0,clearTimeout(t.timeout)})),this.pendingMessages.splice(0,this.pendingMessages.length)}},{key:"actualSend",value:(t=x.default(P.default.mark((function e(t){var n,r,i,a,s,o,u,c;return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.to,i=t.headers,a=t.body,s=null!==(n=t.grant)&&void 0!==n?n:this.config.activeGrant,o={host:r.host,path:r.path,method:r.method,params:r.params,headers:i},u=new Message(s,i["Content-Type"]||"application/json",o),X.trace("Sending upstream message",u),e.next=9,this.transport.sendWithReply(u,a);case 9:if(c=e.sent,X.trace("Received upstream message response",c),!((f=c)&&f.header&&f.header.http_status)||(l=c.header.http_status.code)>=200&&l<300){e.next=13;break}throw new De(c.header.http_status.code,c.header.http_status.status,c.body);case 13:return e.abrupt("return",{status:c.header.http_status,headers:c.header.http_headers,body:c.body});case 14:case"end":return e.stop()}var l,f}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"send",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;if(this.twilsock.isTerminalState)return Promise.reject(new Be("Unable to connect: "+this.twilsock.getTerminationReason));var a=ze(e,t,n,r,i);return this.twilsock.isConnected?this.actualSend(a):this.saveMessage(a)}}]),e}(),Ge=function(){function e(){var t=this;I.default(this,e),this._promise=new Promise((function(e,n){t._resolve=e,t._reject=n}))}return _.default(e,[{key:"promise",get:function(){return this._promise}},{key:"update",value:function(e){this._resolve(e)}},{key:"set",value:function(e){this._resolve(e)}},{key:"fail",value:function(e){this._reject(e)}}]),e}(),$e=function(){function e(t){I.default(this,e),this.id=t}return _.default(e,null,[{key:"create",value:function(t){if(t instanceof Object&&"storage_id"in t)return new e(t.storage_id);throw new xe('Field "storage_id" is missing')}}]),e}(),Ve=function(){function e(){return I.default(this,e),O.default(this,"initializedFlag","twilio_twilsock_token_storage"),O.default(this,"tokenStoragePrefix","twilio_continuation_token_"),e._instance||(this.initialize(),e._instance=this),e._instance}return _.default(e,[{key:"sessionStorage",value:function(){try{return t.sessionStorage}catch(e){return null}}},{key:"window",value:function(){try{return t.window}catch(e){return null}}},{key:"storeToken",value:function(e,t){this.canStore()&&this.sessionStorage.setItem(this.getKeyName(t),e)}},{key:"getStoredToken",value:function(e){return this.canStore()?this.sessionStorage.getItem(this.getKeyName(e)):null}},{key:"initialize",value:function(){var e=this;if(this.canStore()){this.sessionStorage.getItem(this.initializedFlag)&&this.clear(),this.sessionStorage.setItem(this.initializedFlag,"true");var t=this.sessionStorage.removeItem;this.window.addEventListener("unload",(function(){t(e.initializedFlag)}))}}},{key:"clear",value:function(){if(this.canStore()){for(var e=[],t=0;t<this.sessionStorage.length;t++){var n=this.sessionStorage.key(t);n&&0===n.indexOf(this.tokenStoragePrefix)&&e.push(n)}var r=this.sessionStorage.removeItem;e.forEach((function(e){return r(e)})),r(this.initializedFlag)}}},{key:"getKeyName",value:function(e){return"".concat(this.tokenStoragePrefix).concat(e)}},{key:"canStore",value:function(){return!!(this.sessionStorage&&this.sessionStorage.length&&this.window)}}]),e}();O.default(Ve,"_instance",null);var Je,Ke,He=new Ve,Ye=function(){function e(t,n,r,i,a,s){I.default(this,e),this.title=t,this.details=n,this.start=r,this.type=a,this.id=s,this.end=i}return _.default(e,[{key:"toTelemetryEvent",value:function(){var e=new Date,t=this.start,n=this.end?this.end:e;if(n<t){var r=n;n=t,t=r}var i=t.getTime()-e.getTime(),a=n.getTime()-e.getTime();return new he(i,a,this.title,this.details,this.id,this.type)}}]),e}();e.TelemetryPoint=void 0,(Je=e.TelemetryPoint||(e.TelemetryPoint={}))[Je.Start=0]="Start",Je[Je.End=1]="End",e.EventSendingLimitation=void 0,(Ke=e.EventSendingLimitation||(e.EventSendingLimitation={}))[Ke.MinEventsPortion=0]="MinEventsPortion",Ke[Ke.AnyEvents=1]="AnyEvents",Ke[Ke.AnyEventsIncludingUnfinished=2]="AnyEventsIncludingUnfinished";var Qe=function(){function t(e,n){I.default(this,t),O.default(this,"minEventsPortionToSend",50),O.default(this,"maxEventsPortionToSend",100),O.default(this,"pendingEvents",new Map),O.default(this,"readyEvents",[]),O.default(this,"hasInitializationFinished",!1),O.default(this,"_canSendTelemetry",!1),this.config=e,this.packetInterface=n}return _.default(t,[{key:"isTelemetryEnabled",get:function(){return this.config.confirmedCapabilities.has("telemetry.v1")}},{key:"canSendTelemetry",get:function(){return this._canSendTelemetry&&this.isTelemetryEnabled},set:function(t){X.debug("TelemetryTracker.canSendTelemetry: ".concat(t," TelemetryTracker.isTelemetryEnabled: ").concat(this.isTelemetryEnabled)),this._canSendTelemetry&&!t&&(this.pendingEvents.clear(),this.readyEvents=[]),this._canSendTelemetry=t,t&&this.sendTelemetry(e.EventSendingLimitation.AnyEvents),t&&!this.hasInitializationFinished&&(this.hasInitializationFinished=!0)}},{key:"addTelemetryEvent",value:function(e){!this.canSendTelemetry&&this.hasInitializationFinished||this.readyEvents.push(e)}},{key:"addPartialEvent",value:function(t,n,r){X.debug("Adding ".concat(r===e.TelemetryPoint.Start?"starting":"ending"," timepoint for '").concat(n,"' event"));var i=this.pendingEvents.has(n);if(r===e.TelemetryPoint.Start)i&&X.debug("Overwriting starting point for '".concat(n,"' event")),this.pendingEvents.set(n,t);else{if(!i)return void X.info("Could not find started event for '".concat(n,"' event"));this.addTelemetryEvent(this.merge(this.pendingEvents.get(n),t)),this.pendingEvents.delete(n)}}},{key:"getTelemetryToSend",value:function(t){return this.canSendTelemetry&&0!=this.readyEvents.length?t==e.EventSendingLimitation.MinEventsPortion&&this.readyEvents.length<this.minEventsPortionToSend?[]:this.getTelemetryPortion(t==e.EventSendingLimitation.AnyEventsIncludingUnfinished):[]}},{key:"getTelemetryPortion",value:function(e){var t=this,n=Math.min(this.readyEvents.length,this.maxEventsPortionToSend),r=this.readyEvents.splice(0,n);return e&&r.length<this.maxEventsPortionToSend&&this.pendingEvents.forEach((function(e,n){if(!(r.length>=t.maxEventsPortionToSend)){var i=t.pendingEvents.get(n);t.pendingEvents.delete(n),r.push(new Ye("[UNFINISHED] ".concat(i.title),i.details,i.start,null,i.type,i.id))}})),r}},{key:"merge",value:function(e,t){return new Ye(t.title?t.title:e.title,t.details?t.details:e.details,e.start,t.end,t.type?t.type:e.type,t.id?t.id:e.id)}},{key:"sendTelemetryIfMinimalPortionCollected",value:function(){this.sendTelemetry(e.EventSendingLimitation.MinEventsPortion)}},{key:"sendTelemetry",value:function(e){var t=this.getTelemetryToSend(e);if(0!==t.length)try{this.packetInterface.send(new ve(t.map((function(e){return e.toTelemetryEvent()}))))}catch(e){X.debug("Error while sending ".concat(t.length," telemetry events due to ").concat(e,"; they will be resubmitted")),this.readyEvents=this.readyEvents.concat(t)}}}]),t}();function Xe(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=C.default(e);if(t){var i=C.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return R.default(this,n)}}var Ze=function e(){I.default(this,e)};O.default(Ze,"TWILSOCK_CONNECT","twilsock.sdk.connect"),O.default(Ze,"TWILSOCK_INIT","twilsock.sdk.init"),e.TwilsockClient=function(t){T.default(f,t);var n,r,i,a,s,o,u,c,l=Xe(f);function f(t,n,r){var i;I.default(this,f),i=l.call(this),O.default(S.default(i),"version",Z),O.default(S.default(i),"offlineStorageDeferred",new Ge),r.continuationToken=r.continuationToken?r.continuationToken:He.getStoredToken(n);var a=i.config=new ee(t,n,r);X.setLevel(a.logLevel);var s=new Me(a.url),o=new Ae(s,a);return i.channel=new Oe(s,o,a),i.registrations=new Ne(o),i.upstream=new We(o,i.channel,a),i.telemetryTracker=new Qe(a,o),i.channel.on("initialized",(function(){return i.telemetryTracker.canSendTelemetry=!0})),s.on("disconnected",(function(){return i.telemetryTracker.canSendTelemetry=!1})),i.registrations.on("registered",(function(e){return i.emit("registered",e)})),i.channel.on("message",(function(e,t){return setTimeout((function(){return i.emit("message",e,t)}),0)})),i.channel.on("stateChanged",(function(e){return setTimeout((function(){return i.emit("stateChanged",e)}),0)})),i.channel.on("connectionError",(function(e){return setTimeout((function(){return i.emit("connectionError",e)}),0)})),i.channel.on("tokenAboutToExpire",(function(){return setTimeout((function(){return i.emit("tokenAboutToExpire")}),0)})),i.channel.on("tokenExpired",(function(){return setTimeout((function(){return i.emit("tokenExpired")}),0)})),i.channel.on("connected",(function(){return i.registrations.updateRegistrations()})),i.channel.on("connected",(function(){return i.upstream.sendPendingMessages()})),i.channel.on("connected",(function(){return setTimeout((function(){return i.emit("connected")}),0)})),i.channel.on("beforeConnect",(function(){return i.telemetryTracker.addPartialEvent(new Ye("Establish WebSocket connection","",new Date),Ze.TWILSOCK_CONNECT,e.TelemetryPoint.Start)})),i.channel.on("connected",(function(){return i.telemetryTracker.addPartialEvent(new Ye("Establish WebSocket connection","",new Date,new Date),Ze.TWILSOCK_CONNECT,e.TelemetryPoint.End)})),i.channel.on("beforeSendInit",(function(){return i.telemetryTracker.addPartialEvent(new Ye("Send Twilsock init","",new Date),Ze.TWILSOCK_INIT,e.TelemetryPoint.Start)})),i.channel.on("initialized",(function(){return i.telemetryTracker.addPartialEvent(new Ye("Send Twilsock init","Succeeded",new Date,new Date),Ze.TWILSOCK_INIT,e.TelemetryPoint.End)})),i.channel.on("sendInitFailed",(function(){return i.telemetryTracker.addPartialEvent(new Ye("Send Twilsock init","Failed",new Date,new Date),Ze.TWILSOCK_INIT,e.TelemetryPoint.End)})),i.channel.on("initialized",(function(e){i.handleStorageId(n,e),He.storeToken(e.continuationToken,n),setTimeout((function(){return i.emit("initialized",e)}),0)})),i.channel.on("disconnected",(function(){return setTimeout((function(){return i.emit("disconnected")}),0)})),i.channel.on("disconnected",(function(){return i.upstream.rejectPendingMessages()})),i.channel.on("disconnected",(function(){return i.offlineStorageDeferred.fail(new xe("Client disconnected"))})),i.offlineStorageDeferred.promise.catch((function(){})),i}return _.default(f,[{key:"emit",value:function(e){for(var t,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return X.debug("Emitting ".concat(e.toString(),"(").concat(r.map((function(e){return JSON.stringify(e)})).join(", "),")")),(t=E.default(C.default(f.prototype),"emit",this)).call.apply(t,[this,e].concat(r))}},{key:"handleStorageId",value:function(e,t){if(t.offlineStorage)if(t.offlineStorage.hasOwnProperty(e))try{this.offlineStorageDeferred.set($e.create(t.offlineStorage[e])),X.debug("Offline storage for '".concat(e,"' product: ").concat(JSON.stringify(t.offlineStorage[e]),"."))}catch(n){this.offlineStorageDeferred.fail(new xe("Failed to parse offline storage for ".concat(e," ").concat(JSON.stringify(t.offlineStorage[e]),". ").concat(n,".")))}else this.offlineStorageDeferred.fail(new xe("No offline storage id for '".concat(e,"' product: ").concat(JSON.stringify(t.offlineStorage))));else this.offlineStorageDeferred.fail(new xe("No offline storage id"))}},{key:"storageId",value:function(){return this.offlineStorageDeferred.promise}},{key:"isConnected",get:function(){return this.channel.isConnected}},{key:"state",get:function(){return this.channel.state}},{key:"updateToken",value:(c=x.default(P.default.mark((function e(t){return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(X.trace("updating token '".concat(t,"'")),this.config.token!==t){e.next=3;break}return e.abrupt("return");case 3:return this.config.updateToken(t),e.next=6,this.channel.updateToken(t);case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"setNotificationsContext",value:(u=x.default(P.default.mark((function e(t,n){return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.registrations.setNotificationsContext(t,n);case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return u.apply(this,arguments)})},{key:"removeNotificationsContext",value:(o=x.default(P.default.mark((function e(t){return P.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.registrations.removeNotificationsContext(t);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"connect",value:function(){return this.channel.connect()}},{key:"disconnect",value:(s=x.default(P.default.mark((function t(){return P.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEventsIncludingUnfinished),t.next=3,this.channel.disconnect();case 3:return t.abrupt("return",t.sent);case 4:case"end":return t.stop()}}),t,this)}))),function(){return s.apply(this,arguments)})},{key:"get",value:(a=x.default(P.default.mark((function t(n,r,i){return P.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),t.next=3,this.upstream.send("GET",n,r,void 0,i);case 3:return t.abrupt("return",t.sent);case 4:case"end":return t.stop()}}),t,this)}))),function(e,t,n){return a.apply(this,arguments)})},{key:"post",value:(i=x.default(P.default.mark((function t(n,r,i,a){return P.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),t.next=3,this.upstream.send("POST",n,r,i,a);case 3:return t.abrupt("return",t.sent);case 4:case"end":return t.stop()}}),t,this)}))),function(e,t,n,r){return i.apply(this,arguments)})},{key:"put",value:(r=x.default(P.default.mark((function t(n,r,i,a){return P.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),t.next=3,this.upstream.send("PUT",n,r,i,a);case 3:return t.abrupt("return",t.sent);case 4:case"end":return t.stop()}}),t,this)}))),function(e,t,n,i){return r.apply(this,arguments)})},{key:"delete",value:(n=x.default(P.default.mark((function t(n,r,i,a){return P.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return this.telemetryTracker.sendTelemetry(e.EventSendingLimitation.AnyEvents),t.next=3,this.upstream.send("DELETE",n,r,i,a);case 3:return t.abrupt("return",t.sent);case 4:case"end":return t.stop()}}),t,this)}))),function(e,t,r,i){return n.apply(this,arguments)})},{key:"addTelemetryEvent",value:function(e){this.telemetryTracker.addTelemetryEvent(e),this.telemetryTracker.sendTelemetryIfMinimalPortionCollected()}},{key:"addPartialTelemetryEvent",value:function(t,n,r){this.telemetryTracker.addPartialEvent(t,n,r),r===e.TelemetryPoint.End&&this.telemetryTracker.sendTelemetryIfMinimalPortionCollected()}}]),f}(D),e.TwilsockClient=function(e,t,n,r){var i,a=arguments.length,s=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"===("undefined"==typeof Reflect?"undefined":A.default(Reflect))&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(s=(a<3?i(s):a>3?i(t,n,s):i(t,n))||s);return a>3&&s&&Object.defineProperty(t,n,s),s}([p.validateConstructorTypes(p.nonEmptyString,p.nonEmptyString,[p.pureObject,"undefined",p.literal(null)]),function(e,t){if("object"===("undefined"==typeof Reflect?"undefined":A.default(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:paramtypes",[String,String,Object])],e.TwilsockClient);var et=function(){function e(t){I.default(this,e),this.product=t,this.type="ers",this.notification_protocol_version=0,this.message_types=[]}return _.default(e,[{key:"populateInitRegistrations",value:function(e){var t=new Set(this.message_types);for(var n in e)t.add(e[n]);this.message_types=Array.from(t)}}]),e}();e.InitRegistration=et,e.TelemetryEventDescription=Ye,e.TelemetryTracker=Qe,e.TransportUnavailableError=Be,e.Twilsock=e.TwilsockClient,e.TwilsockError=xe}($g);var LE={},NE=u,UE=o,DE=Fn,FE=nn,BE=c,qE=X,zE=w,WE=Object.assign,GE=Object.defineProperty,$E=!WE||UE((function(){if(NE&&1!==WE({b:1},WE(GE({},"a",{enumerable:!0,get:function(){GE(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach((function(e){t[e]=e})),7!=WE({},e)[n]||DE(WE({},t)).join("")!=r}))?function(e,t){for(var n=qE(e),r=arguments.length,i=1,a=FE.f,s=BE.f;r>i;)for(var o,u=zE(arguments[i++]),c=a?DE(u).concat(a(u)):DE(u),l=c.length,f=0;l>f;)o=c[f++],NE&&!s.call(u,o)||(n[o]=u[o]);return n}:WE,VE=$E;Cn({target:"Object",stat:!0,forced:Object.assign!==VE},{assign:VE}),function(e){Object.defineProperty(e,"__esModule",{value:!0});var t=Vg.exports,n=pv.exports,r=dv.exports,i=hv.exports,a=yv.exports,s=gv.exports,o=Jg,u=Hh.exports,c=$g,l=mv.exports,f=jy.exports,d=sg,p=nv.exports,h=uv.exports,v=Sf.exports,y=Cb,m=gh;function g(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}function b(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var w=g(t),k=g(n),x=g(r),_=g(i),S=g(a),E=g(s),T=g(o),R=g(u),C=g(l),I=g(f),O=g(p),P=g(h),A=b(v),j=b(y);function M(e,t,n,r){var i,a=arguments.length,s=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"===("undefined"==typeof Reflect?"undefined":R.default(Reflect))&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(s=(a<3?i(s):a>3?i(t,n,s):i(t,n))||s);return a>3&&s&&Object.defineProperty(t,n,s),s}function L(e,t){if("object"===("undefined"==typeof Reflect?"undefined":R.default(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function N(){}function U(){U.init.call(this)}function D(e){return void 0===e._maxListeners?U.defaultMaxListeners:e._maxListeners}function F(e,t,n){if(t)e.call(n);else for(var r=e.length,i=J(e,r),a=0;a<r;++a)i[a].call(n)}function B(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,a=J(e,i),s=0;s<i;++s)a[s].call(n,r)}function q(e,t,n,r,i){if(t)e.call(n,r,i);else for(var a=e.length,s=J(e,a),o=0;o<a;++o)s[o].call(n,r,i)}function z(e,t,n,r,i,a){if(t)e.call(n,r,i,a);else for(var s=e.length,o=J(e,s),u=0;u<s;++u)o[u].call(n,r,i,a)}function W(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,a=J(e,i),s=0;s<i;++s)a[s].apply(n,r)}function G(e,t,n,r){var i,a,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),s=a[t]):(a=e._events=new N,e._eventsCount=0),s){if("function"==typeof s?s=a[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),!s.warned&&(i=D(e))&&i>0&&s.length>i){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,o=u,"function"==typeof console.warn?console.warn(o):console.log(o)}}else s=a[t]=n,++e._eventsCount;return e}function $(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function V(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function J(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}N.prototype=Object.create(null),U.EventEmitter=U,U.usingDomains=!1,U.prototype.domain=void 0,U.prototype._events=void 0,U.prototype._maxListeners=void 0,U.defaultMaxListeners=10,U.init=function(){this.domain=null,U.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new N,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},U.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},U.prototype.getMaxListeners=function(){return D(this)},U.prototype.emit=function(e){var t,n,r,i,a,s,o,u="error"===e;if(s=this._events)u=u&&null==s.error;else if(!u)return!1;if(o=this.domain,u){if(t=arguments[1],!o){if(t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=s[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:F(n,l,this);break;case 2:B(n,l,this,arguments[1]);break;case 3:q(n,l,this,arguments[1],arguments[2]);break;case 4:z(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),a=1;a<r;a++)i[a-1]=arguments[a];W(n,l,this,i)}return!0},U.prototype.addListener=function(e,t){return G(this,e,t,!1)},U.prototype.on=U.prototype.addListener,U.prototype.prependListener=function(e,t){return G(this,e,t,!0)},U.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,$(this,e,t)),this},U.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,$(this,e,t)),this},U.prototype.removeListener=function(e,t){var n,r,i,a,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new N:(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new N,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}(n,i);r.removeListener&&this.emit("removeListener",e,s||t)}return this},U.prototype.off=function(e,t){return this.removeListener(e,t)},U.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new N,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new N:delete n[e]),this;if(0===arguments.length){for(var r,i=Object.keys(n),a=0;a<i.length;++a)"removeListener"!==(r=i[a])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new N,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},U.prototype.listeners=function(e){var t,n,r=this._events;return n=r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},U.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):V.call(e,t)},U.prototype.listenerCount=V,U.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var K=A.getLogger("twilio-notificatiions");function H(e,t){return["".concat((new Date).toISOString()," Twilio.Notifications ").concat(e,":")].concat(Array.from(t))}var Y=function(){function e(){k.default(this,e)}return x.default(e,[{key:"setLevel",value:function(e){K.setLevel(e)}},{key:"trace",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];K.trace.apply(null,H("T",t))}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];K.debug.apply(null,H("D",t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];K.info.apply(null,H("I",t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];K.warn.apply(null,H("W",t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];K.error.apply(null,H("E",t))}}]),e}(),Q=new Y;function X(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=E.default(e);if(t){var i=E.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return S.default(this,n)}}var Z=x.default((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:new Set;k.default(this,e),this.token=t,this.notificationId=n,this.messageTypes=r}));function ee(e,t){var n=new Set;return e.notificationId!==t.notificationId&&n.add("notificationId"),e.token!==t.token&&n.add("token"),function(e,t){return[].concat(P.default(P.default(e).filter((function(e){return!t.has(e)}))),P.default(P.default(t).filter((function(t){return!e.has(t)}))))}(e.messageTypes,t.messageTypes).length>0&&n.add("messageType"),[n.size>0,n]}var te=function(e){_.default(r,e);var t,n=X(r);function r(e){var t;return k.default(this,r),t=n.call(this),I.default(C.default(t),"desiredState",new Z),I.default(C.default(t),"currentState",new Z),I.default(C.default(t),"_hasActiveAttempt",!1),t.channelType=e,t}return x.default(r,[{key:"setNotificationId",value:function(e){this.desiredState.notificationId=e}},{key:"isActive",value:function(){return""!==this.desiredState.notificationId}},{key:"subscribe",value:function(e){this.desiredState.messageTypes.has(e)?Q.debug("message type '".concat(e,"' for channel ").concat(this.channelType," is already registered")):this.desiredState.messageTypes.add(e)}},{key:"unsubscribe",value:function(e){this.desiredState.messageTypes.has(e)&&this.desiredState.messageTypes.delete(e)}},{key:"updateToken",value:function(e){this.desiredState.token=e}},{key:"commitChanges",value:(t=w.default(T.default.mark((function e(){var t,n,r,i,a,s;return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._hasActiveAttempt){e.next=3;break}throw Q.error("One registration attempt is already in progress"),new Error("One registration attempt is already in progress");case 3:if(t=ee(this.desiredState,this.currentState),n=O.default(t,2),r=n[0],i=n[1],r){e.next=6;break}return e.abrupt("return");case 6:if(this.currentState.notificationId||i.delete("notificationId"),Q.trace("Persisting ".concat(this.channelType," registration"),i,this.desiredState),e.prev=8,this._hasActiveAttempt=!0,(a=new Z).token=this.desiredState.token,a.notificationId=this.desiredState.notificationId,a.messageTypes=new Set(this.desiredState.messageTypes),!(a.messageTypes.size>0)){e.next=24;break}return e.next=17,this.updateRegistration(a,i);case 17:s=e.sent,this.currentState.token=s.token,this.currentState.notificationId=s.notificationId,this.currentState.messageTypes=new Set(s.messageTypes),this.emit("stateChanged",this.channelType,"registered",this.currentState),e.next=30;break;case 24:return e.next=26,this.removeRegistration();case 26:this.currentState.token=a.token,this.currentState.notificationId=a.notificationId,this.currentState.messageTypes.clear(),this.emit("stateChanged",this.channelType,"unregistered",this.currentState);case 30:e.next=35;break;case 32:throw e.prev=32,e.t0=e.catch(8),e.t0;case 35:return e.prev=35,this._hasActiveAttempt=!1,e.finish(35);case 38:case"end":return e.stop()}}),e,this,[[8,32,35,38]])}))),function(){return t.apply(this,arguments)})}]),r}(U);function ne(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=E.default(e);if(t){var i=E.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return S.default(this,n)}}var re={min:2e3,max:12e4,randomness:.2},ie=function(e){_.default(a,e);var t,n,r,i=ne(a);function a(e,t,n,r){var s;return k.default(this,a),s=i.call(this,e),I.default(C.default(s),"registrationId",null),s.context=t,s.twilsock=n,s.registrarUrl=r,s}return x.default(a,[{key:"updateRegistration",value:(r=w.default(T.default.mark((function e(t,n){var r,i,a,s,o,u=this;return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!n.has("notificationId")){e.next=3;break}return e.next=3,this.removeRegistration();case 3:if(t.notificationId&&t.notificationId.length){e.next=6;break}throw Q.error("No push notification ID for registration"),new Error("No push notification ID for registration");case 6:return Q.trace("Registering",this.channelType,t),r={endpoint_platform:this.context.platform,channel_type:this.channelType,version:this.context.protocolVersion.toString(),message_types:Array.from(t.messageTypes),data:{registration_id:t.notificationId}},i=this.context.productId,a="".concat(this.registrarUrl,"?productId=").concat(i),s={"Content-Type":"application/json"},Q.trace("Creating registration for channel ".concat(this.channelType)),e.prev=12,e.next=15,new d.AsyncRetrier(re).run((function(){return u.twilsock.post(a,s,r,i)}));case 15:o=e.sent,this.registrationId=o.body.id,Q.debug("Registration created: ",o),e.next=24;break;case 20:throw e.prev=20,e.t0=e.catch(12),Q.error("Registration failed: ",e.t0),e.t0;case 24:return e.abrupt("return",t);case 25:case"end":return e.stop()}}),e,this,[[12,20]])}))),function(e,t){return r.apply(this,arguments)})},{key:"removeRegistration",value:(n=w.default(T.default.mark((function e(){var t,n,r,i=this;return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.registrationId){e.next=2;break}return e.abrupt("return");case 2:return t=this.context.productId,n="".concat(this.registrarUrl,"/").concat(this.registrationId,"?productId=").concat(t),r={"Content-Type":"application/json"},Q.trace("Removing registration for ".concat(this.channelType)),e.prev=6,e.next=9,new d.AsyncRetrier(Object.assign(re,{maxAttemptsCount:3})).run((function(){return i.twilsock.delete(n,r,{},t)}));case 9:this.registrationId=null,this.currentState.notificationId="",Q.debug("Registration removed for ".concat(this.channelType)),e.next=18;break;case 14:throw e.prev=14,e.t0=e.catch(6),Q.error("Failed to remove registration ",this.channelType,e.t0),e.t0;case 18:case"end":return e.stop()}}),e,this,[[6,14]])}))),function(){return n.apply(this,arguments)})},{key:"sendDeviceRemoveRequest",value:(t=w.default(T.default.mark((function e(t){var n,r,i,a,s=this;return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(""!==t){e.next=2;break}throw new Error("Empty registration ID");case 2:return n=this.context.productId,r="".concat(this.registrarUrl,"?productId=").concat(n),i={"Content-Type":"application/json"},a={binding_type:this.channelType,address:t},e.prev=6,Q.trace("Removing old registrations for ".concat(this.channelType)),e.next=10,new d.AsyncRetrier(Object.assign(re,{maxAttemptsCount:3})).run((function(){return s.twilsock.delete(r,i,a,n)}));case 10:this.registrationId=null,this.currentState.notificationId="",Q.debug("Registration removed for ".concat(this.channelType)),e.next=19;break;case 15:throw e.prev=15,e.t0=e.catch(6),Q.error("Failed to remove registration ",this.channelType,e.t0),e.t0;case 19:case"end":return e.stop()}}),e,this,[[6,15]])}))),function(e){return t.apply(this,arguments)})}]),a}(te);function ae(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=E.default(e);if(t){var i=E.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return S.default(this,n)}}var se,oe=function(e){_.default(a,e);var t,n,r,i=ae(a);function a(e,t,n){var r;return k.default(this,a),r=i.call(this,"twilsock"),I.default(C.default(r),"contextId",j.v4()),r.productId=e,r.platform=t,r.twilsock=n,r}return x.default(a,[{key:"updateRegistration",value:(r=w.default(T.default.mark((function e(t,n){var r,i;return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n.has("messageType")){e.next=2;break}return e.abrupt("return",t);case 2:return r=Array.from(t.messageTypes),i={product_id:this.productId,notification_protocol_version:4,endpoint_platform:this.platform,message_types:r},e.prev=4,e.next=7,this.twilsock.setNotificationsContext(this.contextId,i);case 7:e.next=13;break;case 9:throw e.prev=9,e.t0=e.catch(4),Q.error("Failed to update twilsock notification context: ".concat(e.t0)),e.t0;case 13:return e.abrupt("return",t);case 14:case"end":return e.stop()}}),e,this,[[4,9]])}))),function(e,t){return r.apply(this,arguments)})},{key:"removeRegistration",value:(n=w.default(T.default.mark((function e(){return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this.twilsock.removeNotificationsContext(this.contextId);case 3:e.next=9;break;case 5:throw e.prev=5,e.t0=e.catch(0),Q.error("Failed to remove twilsock notification context: ".concat(e.t0)),e.t0;case 9:case"end":return e.stop()}}),e,this,[[0,5]])}))),function(){return n.apply(this,arguments)})},{key:"sendDeviceRemoveRequest",value:(t=w.default(T.default.mark((function e(t){return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)}))),function(e){return t.apply(this,arguments)})}]),a}(te);function ue(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=E.default(e);if(t){var i=E.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return S.default(this,n)}}var ce=m.literal("apn","fcm","twilsock");e.Notifications=se=function(e){_.default(Client,e);var t,n,r,i=ue(Client);function Client(e){var t,n,r,a,s,o,u,l=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};k.default(this,Client),u=i.call(this),l.logLevel=null!==(t=l.logLevel)&&void 0!==t?t:"error",Q.setLevel(l.logLevel);var f=null!==(n=l.productId)&&void 0!==n?n:"notifications",d=!l.twilsockClient,p=l.twilsockClient=null!==(r=l.twilsockClient)&&void 0!==r?r:new c.TwilsockClient(e,f,l),h=null!==(a=l.notifications)&&void 0!==a?a:{},v=null!==(s=null!==(o=h.region)&&void 0!==o?o:l.region)&&void 0!==s?s:"us1",y="https://ers.".concat(v,".twilio.com/v1/registrations"),m=h.ersUrl||y;u.connectors=new Map;var g=se._detectPlatform();return u.connectors.set("apn",new ie("apn",{protocolVersion:4,productId:f,platform:g},p,m)),u.connectors.set("fcm",new ie("fcm",{protocolVersion:3,productId:f,platform:g},p,m)),u.connectors.set("twilsock",new oe(f,g,p)),p.on("stateChanged",(function(e){return u.emit("transportState",e)})),u._connector("twilsock").on("stateChanged",(function(e,t,n){return u.emit("stateChanged",e,t,n)})),u._connector("apn").on("stateChanged",(function(e,t,n){return u.emit("stateChanged",e,t,n)})),u._connector("fcm").on("stateChanged",(function(e,t,n){return u.emit("stateChanged",e,t,n)})),p.on("message",(function(e,t){return u._routeMessage(e,t)})),u.updateToken(e),d&&(p.connect(),u.twilsock=p),u}return x.default(Client,[{key:"shutdown",value:(r=w.default(T.default.mark((function e(){return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.connectors.clear(),!this.twilsock){e.next=4;break}return e.next=4,this.twilsock.disconnect();case 4:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"setPushRegistrationId",value:function(e,t){Q.debug("Set ".concat(e," push registration id '").concat(t,"'")),this._connector(e).setNotificationId(t)}},{key:"subscribe",value:function(e,t){Q.debug("Add ".concat(e," subscriptions for message type ").concat(t)),this._connector(e).subscribe(t)}},{key:"unsubscribe",value:function(e,t){Q.debug("Remove ".concat(e," subscriptions for message type ").concat(t)),this._connector(e).unsubscribe(t)}},{key:"updateToken",value:function(e){this.connectors.forEach((function(t){return t.updateToken(e)}))}},{key:"commitChanges",value:(n=w.default(T.default.mark((function e(){var t;return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=[],this.connectors.forEach((function(e){e.isActive()&&t.push(e.commitChanges())})),e.next=4,Promise.all(t);case 4:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"removeRegistrations",value:(t=w.default(T.default.mark((function e(t,n){return T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._connector(t).sendDeviceRemoveRequest(n);case 2:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})},{key:"handlePushNotification",value:function(e){return{messageType:e.twi_message_type,payload:e.payload}}},{key:"_routeMessage",value:function(e,t){Q.debug("Notification message arrived: ",e,t),this.emit("message",e,t)}},{key:"_connector",value:function(e){var t=this.connectors.get(e);if(!t)throw new Error("Unknown channel type: ".concat(e));return t}}],[{key:"_detectPlatform",value:function(){var e="";return"undefined"!=typeof navigator?(e="unknown",void 0!==navigator.product&&(e=navigator.product),void 0!==navigator.userAgent&&(e=navigator.userAgent)):e="web",e.substring(0,128)}}]),Client}(U),M([m.validateTypes(ce,m.nonEmptyString),L("design:type",Function),L("design:paramtypes",[String,String]),L("design:returntype",void 0)],e.Notifications.prototype,"setPushRegistrationId",null),M([m.validateTypes(ce,m.nonEmptyString),L("design:type",Function),L("design:paramtypes",[String,String]),L("design:returntype",void 0)],e.Notifications.prototype,"subscribe",null),M([m.validateTypes(ce,m.nonEmptyString),L("design:type",Function),L("design:paramtypes",[String,String]),L("design:returntype",void 0)],e.Notifications.prototype,"unsubscribe",null),M([m.validateTypes(m.nonEmptyString),L("design:type",Function),L("design:paramtypes",[String]),L("design:returntype",void 0)],e.Notifications.prototype,"updateToken",null),M([m.validateTypesAsync(ce,m.nonEmptyString),L("design:type",Function),L("design:paramtypes",[String,String]),L("design:returntype",Promise)],e.Notifications.prototype,"removeRegistrations",null),e.Notifications=se=M([m.validateConstructorTypes(m.nonEmptyString,[m.pureObject,"undefined",m.literal(null)]),L("design:paramtypes",[String,Object])],e.Notifications)}(LE);var JE={};Object.defineProperty(JE,"__esModule",{value:!0});var KE=Vg.exports,HE=pv.exports,YE=dv.exports,QE=mv.exports,XE=hv.exports,ZE=yv.exports,eT=gv.exports,tT=jy.exports,nT=Jg,rT=Hh.exports,iT=gh,aT=$g,sT=sE.exports,oT=Sf.exports,uT=nv.exports,cT=sg,lT=Cb,fT=Py.exports,dT=lE.exports;function pT(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}function hT(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var vT=pT(KE),yT=pT(HE),mT=pT(YE),gT=pT(QE),bT=pT(XE),wT=pT(ZE),kT=pT(eT),xT=pT(tT),_T=pT(nT),ST=pT(rT),ET=pT(sT),TT=hT(oT),RT=pT(uT),CT=hT(lT),IT=pT(fT),OT=hT(dT);function PT(e,t,n,r){var i,a=arguments.length,s=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"===("undefined"==typeof Reflect?"undefined":ST.default(Reflect))&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(s=(a<3?i(s):a>3?i(t,n,s):i(t,n))||s);return a>3&&s&&Object.defineProperty(t,n,s),s}function AT(e,t){if("object"===("undefined"==typeof Reflect?"undefined":ST.default(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function jT(){}function MT(){MT.init.call(this)}function LT(e){return void 0===e._maxListeners?MT.defaultMaxListeners:e._maxListeners}function NT(e,t,n){if(t)e.call(n);else for(var r=e.length,i=GT(e,r),a=0;a<r;++a)i[a].call(n)}function UT(e,t,n,r){if(t)e.call(n,r);else for(var i=e.length,a=GT(e,i),s=0;s<i;++s)a[s].call(n,r)}function DT(e,t,n,r,i){if(t)e.call(n,r,i);else for(var a=e.length,s=GT(e,a),o=0;o<a;++o)s[o].call(n,r,i)}function FT(e,t,n,r,i,a){if(t)e.call(n,r,i,a);else for(var s=e.length,o=GT(e,s),u=0;u<s;++u)o[u].call(n,r,i,a)}function BT(e,t,n,r){if(t)e.apply(n,r);else for(var i=e.length,a=GT(e,i),s=0;s<i;++s)a[s].apply(n,r)}function qT(e,t,n,r){var i,a,s,o;if("function"!=typeof n)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),a=e._events),s=a[t]):(a=e._events=new jT,e._eventsCount=0),s){if("function"==typeof s?s=a[t]=r?[n,s]:[s,n]:r?s.unshift(n):s.push(n),!s.warned&&(i=LT(e))&&i>0&&s.length>i){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,o=u,"function"==typeof console.warn?console.warn(o):console.log(o)}}else s=a[t]=n,++e._eventsCount;return e}function zT(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function WT(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function GT(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}jT.prototype=Object.create(null),MT.EventEmitter=MT,MT.usingDomains=!1,MT.prototype.domain=void 0,MT.prototype._events=void 0,MT.prototype._maxListeners=void 0,MT.defaultMaxListeners=10,MT.init=function(){this.domain=null,MT.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new jT,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},MT.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},MT.prototype.getMaxListeners=function(){return LT(this)},MT.prototype.emit=function(e){var t,n,r,i,a,s,o,u="error"===e;if(s=this._events)u=u&&null==s.error;else if(!u)return!1;if(o=this.domain,u){if(t=arguments[1],!o){if(t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=o,t.domainThrown=!1,o.emit("error",t),!1}if(!(n=s[e]))return!1;var l="function"==typeof n;switch(r=arguments.length){case 1:NT(n,l,this);break;case 2:UT(n,l,this,arguments[1]);break;case 3:DT(n,l,this,arguments[1],arguments[2]);break;case 4:FT(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),a=1;a<r;a++)i[a-1]=arguments[a];BT(n,l,this,i)}return!0},MT.prototype.addListener=function(e,t){return qT(this,e,t,!1)},MT.prototype.on=MT.prototype.addListener,MT.prototype.prependListener=function(e,t){return qT(this,e,t,!0)},MT.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,zT(this,e,t)),this},MT.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,zT(this,e,t)),this},MT.prototype.removeListener=function(e,t){var n,r,i,a,s;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(r=this._events))return this;if(!(n=r[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new jT:(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,a=n.length;a-- >0;)if(n[a]===t||n[a].listener&&n[a].listener===t){s=n[a].listener,i=a;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new jT,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r<i;n+=1,r+=1)e[n]=e[r];e.pop()}(n,i);r.removeListener&&this.emit("removeListener",e,s||t)}return this},MT.prototype.off=function(e,t){return this.removeListener(e,t)},MT.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0===arguments.length?(this._events=new jT,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new jT:delete n[e]),this;if(0===arguments.length){for(var r,i=Object.keys(n),a=0;a<i.length;++a)"removeListener"!==(r=i[a])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=new jT,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do{this.removeListener(e,t[t.length-1])}while(t[0]);return this},MT.prototype.listeners=function(e){var t,n,r=this._events;return n=r&&(t=r[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[],n},MT.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):WT.call(e,t)},MT.prototype.listenerCount=WT,MT.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};var $T=function(){function e(t){yT.default(this,e),this.base=t,this.args=new Array,this.paths=new Array}return mT.default(e,[{key:"pathSegment",value:function(e){return this.paths.push(encodeURIComponent(e)),this}},{key:"queryParam",value:function(e,t){return void 0!==t&&this.args.push(encodeURIComponent(e)+"="+encodeURIComponent(t)),this}},{key:"build",value:function(){var e=this.base;return this.paths.length&&(e+="/"+this.paths.join("/")),this.args.length&&(e+="?"+this.args.join("&")),e}}]),e}();function VT(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}var SyncError=function(e){bT.default(SyncError,e);var t=VT(SyncError);function SyncError(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return yT.default(this,SyncError),(n=t.call(this)).name=n.constructor.name,n.message="".concat(e," (status: ").concat(r,", code: ").concat(i,")"),n.status=r,n.code=i,n}return SyncError}(ET.default(Error)),JT=function(e){bT.default(n,e);var t=VT(n);function n(e){var r,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=arguments.length>3?arguments[3]:void 0;return yT.default(this,n),(r=t.call(this,e,i,a)).body=s,r}return n}(SyncError);function KT(e){return JSON.parse(JSON.stringify(e))}function HT(e){if(!(void 0===e||YT(e)))throw new SyncError("Invalid pageSize parameter. Expected a positive integer, was '".concat(e,"'."),400,20007)}function YT(e){return function(e){return!isNaN(parseInt(e))&&isFinite(e)}(e)&&e>0}var QT=TT.getLogger("twilio-sync");function XT(e,t){return["".concat((new Date).toISOString()," Sync ").concat(e,":")].concat(Array.from(t))}var ZT=function(e){QT.setLevel(e)},eR=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];QT.trace.apply(null,XT("T",t))},tR=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];QT.debug.apply(null,XT("D",t))},nR=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];QT.warn.apply(null,XT("W",t))},rR=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];QT.error.apply(null,XT("E",t))},iR="/v4/Subscriptions",aR="/v3/Maps",sR="/v3/Lists",oR="/v3/Documents",uR="/v3/Streams",cR="/v3/Insights";function lR(e,t,n){return e&&void 0!==e[t]?e[t]:n}var fR=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};yT.default(this,e);var n=t.region||"us1",r="https://cds.".concat(n,".twilio.com"),i=t.cdsUri||r;this.settings={subscriptionsUri:i+iR,documentsUri:i+oR,listsUri:i+sR,mapsUri:i+aR,streamsUri:i+uR,insightsUri:i+cR,sessionStorageEnabled:lR(t.Sync,"enableSessionStorage",!0),productId:t.productId}}return mT.default(e,[{key:"subscriptionsUri",get:function(){return this.settings.subscriptionsUri}},{key:"documentsUri",get:function(){return this.settings.documentsUri}},{key:"listsUri",get:function(){return this.settings.listsUri}},{key:"mapsUri",get:function(){return this.settings.mapsUri}},{key:"streamsUri",get:function(){return this.settings.streamsUri}},{key:"insightsUri",get:function(){return this.settings.insightsUri}},{key:"backoffConfig",get:function(){return this.settings.backoffConfig||{}}},{key:"sessionStorageEnabled",get:function(){return this.settings.sessionStorageEnabled}},{key:"productId",get:function(){return this.settings.productId}}]),e}();function dR(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return pR(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return pR(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function pR(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var hR=function(){function e(t){yT.default(this,e),this.localObject=t,this.pendingCorrelationId=null,this.pendingAction=null,this.established=!1,this.retryCount=0}return mT.default(e,[{key:"sid",get:function(){return this.localObject.sid}},{key:"type",get:function(){return this.localObject.type}},{key:"lastEventId",get:function(){return this.localObject.lastEventId}},{key:"indexName",get:function(){return this.localObject.indexName}},{key:"queryString",get:function(){return this.localObject.queryString}},{key:"isEstablished",get:function(){return this.established}},{key:"update",value:function(e,t){this.localObject._update(e,t)}},{key:"updatePending",value:function(e,t){this.pendingAction=e,this.pendingCorrelationId=t}},{key:"reset",value:function(){this.updatePending(null,null),this.retryCount=0,this.established=!1,this.setSubscriptionState("none")}},{key:"markAsFailed",value:function(e){this.rejectedWithError=e.error,this.updatePending(null,null),this.localObject.reportFailure(new SyncError("Failed to subscribe on service events: ".concat(e.error.message),e.error.status,e.error.code))}},{key:"complete",value:function(e){this.updatePending(null,null),this.established=!0,this.localObject._advanceLastEventId(e)}},{key:"setSubscriptionState",value:function(e){this.localObject._setSubscriptionState(e)}}]),e}(),vR=function(){function e(t){var n=this;yT.default(this,e),xT.default(this,"isConnected",!1),xT.default(this,"maxBatchSize",100),xT.default(this,"subscriptionTtlTimer",null),xT.default(this,"pendingPokeReason",null),this.services=t,this.subscriptions=new Map,this.persisted=new Map,this.latestPokeResponseArrivalTimestampByCorrelationId=new Map;this.backoff=cT.Backoff.exponential(Object.assign({randomisationFactor:.2,initialDelay:100,maxDelay:12e4},this.services.config.backoffConfig)),this.backoff.on("ready",(function(){var e=n.getSubscriptionUpdateBatch(),t=e.action,r=e.subscriptions;t?n.applyNewSubscriptionUpdateBatch(t,r):(n.backoff.reset(),tR("All subscriptions resolved."))}))}var t;return mT.default(e,[{key:"getSubscriptionUpdateBatch",value:function(){function e(e,t,n,r){var i,a=[],s=dR(e);try{for(s.s();!(i=s.n()).done;){var o=RT.default(i.value,2),u=o[0],c=o[1];if(!t.get(u)&&n!==c.pendingAction&&!c.rejectedWithError&&(a.push(c),r&&a.length>=r))break}}catch(e){s.e(e)}finally{s.f()}return a}var t=e(this.subscriptions,this.persisted,"establish",this.maxBatchSize);if(t.length>0)return{action:"establish",subscriptions:t};var n=e(this.persisted,this.subscriptions,"cancel",this.maxBatchSize);return n.length>0?{action:"cancel",subscriptions:n}:{action:null,subscriptions:null}}},{key:"persist",value:function(){this.backoff.backoff()}},{key:"applyNewSubscriptionUpdateBatch",value:(t=vT.default(_T.default.mark((function e(t,n){var r,i,a,s,o,u,c,l,f,d,p,h,v=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isConnected){e.next=4;break}return tR("Twilsock connection (required for subscription) not ready; waiting…"),this.backoff.reset(),e.abrupt("return");case 4:n=this.processLocalActions(t,n),r=(new Date).getTime(),i=dR(n);try{for(i.s();!(a=i.n()).done;)s=a.value,this.recordActionAttemptOn(s,t,r)}catch(e){i.e(e)}finally{i.f()}return o=this.pendingPokeReason,this.pendingPokeReason=null,e.prev=10,e.next=13,this.request(t,r,o,n);case 13:u=e.sent,c=u.body.max_batch_size,!isNaN(parseInt(c))&&isFinite(c)&&c>0&&(this.maxBatchSize=c),this.subscriptionTtlTimer||(l=u.body.ttl_in_s,!isNaN(parseFloat(l))&&isFinite(l)&&l>0&&(this.subscriptionTtlTimer=setTimeout((function(){return v.onSubscriptionTtlElapsed()}),1e3*l))),"establish"===t&&(f=u.body.estimated_delivery_in_ms,!isNaN(parseFloat(f))&&isFinite(f)&&f>0?setTimeout((function(){return v.verifyPokeDelivery(r,f,n)}),f):rR("Invalid timeout: ".concat(f)),n.filter((function(e){return e.pendingCorrelationId===r})).forEach((function(e){return e.setSubscriptionState("response_in_flight")}))),this.backoff.reset(),e.next=26;break;case 21:e.prev=21,e.t0=e.catch(10),d=dR(n);try{for(d.s();!(p=d.n()).done;)h=p.value,this.recordActionFailureOn(h,t)}catch(e){d.e(e)}finally{d.f()}e.t0 instanceof aT.TransportUnavailableError?(tR("Twilsock connection (required for subscription) not ready (c:".concat(r,"); waiting…")),this.backoff.reset()):(tR("Failed an attempt to ".concat(t," subscriptions (c:").concat(r,"); retrying"),e.t0),this.persist());case 26:case"end":return e.stop()}}),e,this,[[10,21]])}))),function(e,n){return t.apply(this,arguments)})},{key:"verifyPokeDelivery",value:function(e,t,n){var r=this,i=this.latestPokeResponseArrivalTimestampByCorrelationId.get(e),a=i?(new Date).getTime()-i:t;a>=t?(n.filter((function(t){return t.pendingCorrelationId===e})).forEach((function(e){e.updatePending(null,null),e.retryCount++,r.persisted.delete(e.sid)})),this.persist(),this.latestPokeResponseArrivalTimestampByCorrelationId.delete(e)):setTimeout((function(){return r.verifyPokeDelivery(e,t,n)}),t-a)}},{key:"processLocalActions",value:function(e,t){return"cancel"===e?t.filter((function(e){return!e.rejectedWithError})):t}},{key:"recordActionAttemptOn",value:function(e,t,n){if(e.setSubscriptionState("request_in_flight"),"establish"===t)this.persisted.set(e.sid,e),e.updatePending(t,n);else{var r=this.persisted.get(e.sid);r&&r.updatePending(t,n)}}},{key:"recordActionFailureOn",value:function(e,t){e.setSubscriptionState("none"),e.updatePending(null,null),"establish"===t&&this.persisted.delete(e.sid)}},{key:"request",value:function(e,t,n,r){var i=r.map((function(t){return{object_sid:t.sid,object_type:t.type,last_event_id:"establish"===e?t.lastEventId:void 0,index_name:"establish"===e?t.indexName:void 0,query_string:"establish"===e?t.queryString:void 0}})),a=r.filter((function(e){return e.retryCount>0})).length;tR("Attempting '".concat(e,"' request (c:").concat(t,"):"),i);var s={event_protocol_version:4,action:e,correlation_id:t,retried_requests:a,ttl_in_s:-1,requests:i};return"ttl"===n&&(s.reason=n),this.services.network.post(this.services.config.subscriptionsUri,s)}},{key:"add",value:function(e,t){tR("Establishing intent to subscribe to ".concat(e));var n=this.subscriptions.get(e);n&&t&&n.lastEventId===t.lastEventId||(this.persisted.delete(e),this.subscriptions.set(e,new hR(t)),this.persist())}},{key:"remove",value:function(e){tR("Establishing intent to unsubscribe from ".concat(e)),this.subscriptions.delete(e)&&this.persist()}},{key:"acceptMessage",value:function(e,t){eR("Subscriptions received",e);var n=e.event_type,r=void 0!==e.events?e.events:[e.event],i=e.correlation_id;i&&this.latestPokeResponseArrivalTimestampByCorrelationId.set(i,(new Date).getTime());var a,s=dR(r);try{for(s.s();!(a=s.n()).done;){var o=a.value,u=void 0;switch(e.event_type){case"subscription_established":this.applySubscriptionEstablishedMessage(o,i);break;case"subscription_canceled":this.applySubscriptionCancelledMessage(o,i);break;case"subscription_failed":this.applySubscriptionFailedMessage(o,i);break;case(u=n.match(/^(?:map|list|document|stream|live_query)_/)||{}).input:var c=void 0;switch(u[0]){case"map_":c=o.map_sid;break;case"list_":c=o.list_sid;break;case"document_":c=o.document_sid;break;case"stream_":c=o.stream_sid;break;case"live_query_":c=o.query_id,t=!1,!0===e.strictly_ordered&&(t=!0);break;default:c=void 0}this.applyEventToSubscribedEntity(c,o,n,t);break;default:tR("Dropping unknown message type ".concat(n))}}}catch(e){s.e(e)}finally{s.f()}}},{key:"applySubscriptionEstablishedMessage",value:function(e,t){var n=e.object_sid,r=this.persisted.get(e.object_sid);r&&r.pendingCorrelationId===t?"interrupted"===e.replay_status?(tR("Event Replay for subscription to ".concat(n," (c:").concat(t,") interrupted; continuing eagerly.")),r.updatePending(null,null),this.persisted.delete(r.sid),this.backoff.reset()):"completed"===e.replay_status&&(tR("Event Replay for subscription to ".concat(n," (c:").concat(t,") completed. Subscription is ready.")),r.complete(e.last_event_id),this.persisted.set(e.object_sid,r),r.setSubscriptionState("established"),this.backoff.reset()):tR("Late message for ".concat(e.object_sid," (c:").concat(t,") dropped.")),this.persist()}},{key:"applySubscriptionCancelledMessage",value:function(e,t){var n=this.persisted.get(e.object_sid);n&&n.pendingCorrelationId===t?(n.updatePending(null,null),n.setSubscriptionState("none"),this.persisted.delete(e.object_sid)):tR("Late message for ".concat(e.object_sid," (c:").concat(t,") dropped.")),this.persist()}},{key:"applySubscriptionFailedMessage",value:function(e,t){var n=e.object_sid,r=this.subscriptions.get(n),i=this.persisted.get(n);r&&i?i.pendingCorrelationId===t&&(rR("Failed to subscribe on ".concat(i.sid),e.error),i.markAsFailed(e),i.setSubscriptionState("none")):!r&&i&&(this.persisted.delete(n),i.setSubscriptionState("none")),this.persist()}},{key:"applyEventToSubscribedEntity",value:function(e,t,n,r){if(e){var i;r=r||(i=this.persisted.get(e))&&i.isEstablished;var a=this.subscriptions.get(e);a?(t.type=n,a.update(t,r)):tR("Message dropped for SID '".concat(e,"', for which there is no subscription."))}}},{key:"onConnectionStateChanged",value:function(e){this.isConnected=e,e&&this.poke("reconnect")}},{key:"onSubscriptionTtlElapsed",value:function(){this.isConnected&&this.poke("ttl")}},{key:"poke",value:function(e){tR("Triggering event replay for all subscriptions, reason=".concat(e)),this.pendingPokeReason=e,this.subscriptionTtlTimer&&(clearTimeout(this.subscriptionTtlTimer),this.subscriptionTtlTimer=null);var t,n=[],r=dR(this.persisted.values());try{for(r.s();!(t=r.n()).done;){var i=t.value;i.reset(),i.rejectedWithError&&n.push(i)}}catch(e){r.e(e)}finally{r.f()}this.persisted.clear();for(var a=0,s=n;a<s.length;a++){var o=s[a];this.persisted.set(o.sid,o)}this.persist()}},{key:"shutdown",value:function(){this.backoff.reset(),this.subscriptions.clear()}}]),e}();function yR(e){if(e.body&&e.body.message)return e.body.message;switch(e.status){case 429:return"Throttled by server";case 404:return"Not found from server";default:return"Error from server"}}function mR(e){return e.body?e.body.code:0}function gR(e){return 409===e.status?new JT(yR(e),e.status,mR(e),e.body):e.status?new SyncError(yR(e),e.status,mR(e)):e instanceof aT.TransportUnavailableError?e:new SyncError(e.message,0,0)}var bR=function(){function e(t,n,r){yT.default(this,e),this.clientInfo=t,this.config=n,this.transport=r}return mT.default(e,[{key:"createHeaders",value:function(){return{"Content-Type":"application/json","Twilio-Sync-Client-Info":JSON.stringify(this.clientInfo),"Twilio-Request-Id":"RQ"+CT.v4().replace(/-/g,"")}}},{key:"backoffConfig",value:function(){return Object.assign({min:4e3,max:6e4,maxAttemptsTime:9e4,randomness:.2},this.config.backoffConfig)}},{key:"executeWithRetry",value:function(e){var t=this,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return new Promise((function(r,i){var a=[502,503,504];n&&a.push(429);var s=new cT.Retrier(t.backoffConfig());s.on("attempt",(function(){e().then((function(e){return s.succeeded(e)})).catch((function(e){if(a.includes(e.status)){var t=parseInt(e.headers?e.headers["Retry-After"]:null);s.failed(gR(e),isNaN(t)?null:1e3*t)}else"Twilsock disconnected"===e.message?s.failed(gR(e)):(s.removeAllListeners(),s.cancel(),i(gR(e)))}))})),s.on("succeeded",(function(e){r(e)})),s.on("cancelled",(function(e){return i(gR(e))})),s.on("failed",(function(e){return i(gR(e))})),s.start()}))}},{key:"get",value:function(e){var t=this,n=this.createHeaders();return tR("GET",e,"ID:",n["Twilio-Request-Id"]),this.executeWithRetry((function(){return t.transport.get(e,n,t.config.productId)}),!0)}},{key:"post",value:function(e,t,n){var r=this,i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],a=this.createHeaders();return null!=n&&(a["If-Match"]=n),tR("POST",e,"ID:",a["Twilio-Request-Id"]),this.executeWithRetry((function(){return r.transport.post(e,a,t,r.config.productId)}),i)}},{key:"put",value:function(e,t,n){var r=this,i=this.createHeaders();return null!=n&&(i["If-Match"]=n),tR("PUT",e,"ID:",i["Twilio-Request-Id"]),this.executeWithRetry((function(){return r.transport.put(e,i,t,r.config.productId)}),!1)}},{key:"delete",value:function(e){var t=this,n=this.createHeaders();return tR("DELETE",e,"ID:",n["Twilio-Request-Id"]),this.executeWithRetry((function(){return t.transport.delete(e,n,t.config.productId)}),!1)}}]),e}(),wR=function(){function e(t,n){yT.default(this,e),this.config=t,this.storageId=null;try{this.storage=n||sessionStorage}catch(e){}}return mT.default(e,[{key:"storageKey",value:function(e,t){return"".concat(this.storageId,"::").concat(e,"::").concat(t)}},{key:"isReady",get:function(){return this.config.sessionStorageEnabled&&!!this.storageId}},{key:"updateStorageId",value:function(e){this.storageId=e}},{key:"store",value:function(e,t,n){return this.isReady?this._store(this.storageKey(e,t),n):null}},{key:"read",value:function(e,t){return this.isReady?this._read(this.storageKey(e,t)):null}},{key:"remove",value:function(e,t,n){if(!this.isReady)return null;try{this.storage.removeItem(this.storageKey(e,t)),n&&this.storage.removeItem(this.storageKey(e,n))}catch(e){}}},{key:"update",value:function(e,t,n,r){if(!this.isReady)return null;this._apply(this.storageKey(e,t),r),n&&this._apply(this.storageKey(e,n),r)}},{key:"_store",value:function(e,t){try{this.storage.setItem(e,JSON.stringify(t))}catch(e){}}},{key:"_read",value:function(e){try{var t=this.storage.getItem(e);if(t)return JSON.parse(t)}catch(e){}return null}},{key:"_apply",value:function(e,t){var n=this._read(e);if(!n)return!1;this._store(e,Object.assign(n,t))}}]),e}();function kR(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return xR(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return xR(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function xR(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var _R=function(){function e(t,n){yT.default(this,e),this.services=t,this.removalHandler=n,this.subscriptionState="none",this._attachedListeners=new Map}return mT.default(e,[{key:"_advanceLastEventId",value:function(e,t){}},{key:"reportFailure",value:function(e){404===e.status?this.onRemoved(!1):this.broadcastEventToListeners("failure",e)}},{key:"_subscribe",value:function(){this.services.router._subscribe(this.sid,this)}},{key:"_unsubscribe",value:function(){this.services.router._unsubscribe(this.sid)}},{key:"_setSubscriptionState",value:function(e){this.subscriptionState=e,this.broadcastEventToListeners("_subscriptionStateChanged",e)}},{key:"close",value:function(){this._unsubscribe(),null!=this.removalHandler&&this.removalHandler(this.type,this.sid,this.uniqueName)}},{key:"attach",value:function(e){var t=e.listenerUuid;this._attachedListeners.get(t)||(this._attachedListeners.size||this._subscribe(),this._attachedListeners.set(t,e))}},{key:"detach",value:function(e){this._attachedListeners.delete(e),this._attachedListeners.size||this.close()}},{key:"broadcastEventToListeners",value:function(e,t){var n,r=kR(this._attachedListeners.values());try{for(r.s();!(n=r.n()).done;){n.value.emit(e,t)}}catch(e){r.e(e)}finally{r.f()}}}]),e}(),SR=function(){function e(t){yT.default(this,e),xT.default(this,"queuedRequests",[]),xT.default(this,"isRequestInFlight",!1),this.inputMergingFunction=t}return mT.default(e,[{key:"add",value:function(e,t){var n=this,r=new Promise((function(r,i){return n.queuedRequests.push({input:e,requestFunction:t,resolve:r,reject:i})}));return this.wakeupQueue(),r}},{key:"squashAndAdd",value:function(e,t){var n,r=this.queuedRequests;this.queuedRequests=[],r.length>0?(n=r.map((function(e){return e.input})).reduce(this.inputMergingFunction),n=this.inputMergingFunction(n,e)):n=e;var i=this.add(n,t);return r.forEach((function(e){return i.then(e.resolve,e.reject)})),i}},{key:"isEmpty",value:function(){return 0===this.queuedRequests.length&&!this.isRequestInFlight}},{key:"wakeupQueue",value:function(){var e=this;if(0!==this.queuedRequests.length&&!this.isRequestInFlight){var t=this.queuedRequests.shift();this.isRequestInFlight=!0,t.requestFunction(t.input).then(t.resolve,t.reject).then((function(t){e.isRequestInFlight=!1,e.wakeupQueue()}))}}}]),e}(),ER=function(){function e(t){yT.default(this,e),xT.default(this,"queueByNamespaceKey",new Map),this.inputReducer=t}var t,n,r;return mT.default(e,[{key:"add",value:(r=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.invokeQueueMethod(t,(function(e){return e.add(n,r)})));case 1:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return r.apply(this,arguments)})},{key:"squashAndAdd",value:(n=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.invokeQueueMethod(t,(function(e){return e.squashAndAdd(n,r)})));case 1:case"end":return e.stop()}}),e,this)}))),function(e,t,r){return n.apply(this,arguments)})},{key:"invokeQueueMethod",value:(t=vT.default(_T.default.mark((function e(t,n){var r,i;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.queueByNamespaceKey.has(t)||this.queueByNamespaceKey.set(t,new SR(this.inputReducer)),r=this.queueByNamespaceKey.get(t),i=n(r),this.queueByNamespaceKey.get(t).isEmpty()&&this.queueByNamespaceKey.delete(t),e.abrupt("return",i);case 5:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})}]),e}();function TR(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}var RR=function(e){bT.default(n,e);var t=TR(n);function n(){var e;return yT.default(this,n),(e=t.call(this)).closed=!1,e.uuid=lT.v4(),e}return mT.default(n,[{key:"listenerUuid",get:function(){return this.uuid}},{key:"close",value:function(){this.removeAllListeners(),this.closed=!0}},{key:"ensureNotClosed",value:function(){if(this.closed)throw new Error("Invalid operation on closed object")}}]),n}(MT);function CR(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}var IR=function(e){bT.default(f,e);var t,n,r,i,a,s,o,u,c,l=CR(f);function f(e,t,n){var r;yT.default(this,f),r=l.call(this,e,n),xT.default(gT.default(r),"isDeleted",!1);return r.updateMergingQueue=new SR((function(e,t){return"number"==typeof t.ttl?{ttl:t.ttl}:e})),r.descriptor=t,r.descriptor.data=r.descriptor.data||{},r.descriptor.date_updated=new Date(r.descriptor.date_updated),r}return mT.default(f,[{key:"uri",get:function(){return this.descriptor.url}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"type",get:function(){return"document"}},{key:"indexName",get:function(){}},{key:"queryString",get:function(){}},{key:"sid",get:function(){return this.descriptor.sid}},{key:"data",get:function(){return this.descriptor.data}},{key:"dateUpdated",get:function(){return this.descriptor.date_updated}},{key:"uniqueName",get:function(){return this.descriptor.unique_name||null}},{key:"_update",value:function(e){switch(e.date_created=new Date(e.date_created),e.type){case"document_updated":if(e.id<=this.lastEventId){eR("Document update skipped, current:",this.lastEventId,", remote:",e.id);break}var t=void 0!==this.descriptor.data?KT(this.descriptor.data):null;this.descriptor.last_event_id=e.id,this.descriptor.revision=e.document_revision,this.descriptor.date_updated=e.date_created,this.descriptor.data=e.document_data,this.broadcastEventToListeners("updated",{data:e.document_data,isLocal:!1,previousData:t}),this.services.storage.update(this.type,this.sid,this.uniqueName,{last_event_id:e.id,revision:e.document_revision,date_updated:e.date_created,data:e.document_data});break;case"document_removed":this.onRemoved(!1)}}},{key:"set",value:(c=vT.default(_T.default.mark((function e(t,n){var r,i=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=n||{},e.abrupt("return",this.updateMergingQueue.squashAndAdd(r,(function(e){return i._setUnconditionally(t,e.ttl)})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return c.apply(this,arguments)})},{key:"mutate",value:(u=vT.default(_T.default.mark((function e(t,n){var r,i=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=n||{},e.abrupt("return",this.updateMergingQueue.add(r,(function(e){return i._setWithIfMatch(t,e.ttl)})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return u.apply(this,arguments)})},{key:"update",value:(o=vT.default(_T.default.mark((function e(t,n){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.mutate((function(e){return Object.assign(e,t)}),n));case 1:case"end":return e.stop()}}),e,this)}))),function(e,t){return o.apply(this,arguments)})},{key:"setTtl",value:(s=vT.default(_T.default.mark((function e(t){var n;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._postUpdateToServer({ttl:t});case 2:n=e.sent,this.descriptor.date_expires=n.date_expires;case 4:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"_setUnconditionally",value:(a=vT.default(_T.default.mark((function e(t,n){var r;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._postUpdateToServer({data:t,revision:void 0,ttl:n});case 2:return r=e.sent,this._handleSuccessfulUpdateResult(r),e.abrupt("return",this.descriptor.data);case 5:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"_setWithIfMatch",value:(i=vT.default(_T.default.mark((function e(t,n){var r,i,a;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(r=t(KT(this.descriptor.data)))){e.next=22;break}return i=this.revision,e.prev=3,e.next=6,this._postUpdateToServer({data:r,revision:i,ttl:n});case 6:return a=e.sent,this._handleSuccessfulUpdateResult(a),e.abrupt("return",this.descriptor.data);case 11:if(e.prev=11,e.t0=e.catch(3),412!==e.t0.status){e.next=19;break}return e.next=16,this._softSync();case 16:return e.abrupt("return",this._setWithIfMatch(t));case 19:throw e.t0;case 20:e.next=23;break;case 22:return e.abrupt("return",this.descriptor.data);case 23:case"end":return e.stop()}}),e,this,[[3,11]])}))),function(e,t){return i.apply(this,arguments)})},{key:"_handleSuccessfulUpdateResult",value:function(e){if(!(e.last_event_id<=this.descriptor.last_event_id)){var t=void 0!==this.descriptor.data?KT(this.descriptor.data):null;this.descriptor.revision=e.revision,this.descriptor.data=e.data,this.descriptor.last_event_id=e.last_event_id,this.descriptor.date_expires=e.date_expires,this.descriptor.date_updated=new Date(e.date_updated),this.services.storage.update(this.type,this.sid,this.uniqueName,{last_event_id:e.last_event_id,revision:e.revision,date_updated:e.date_updated,data:e.data}),this.broadcastEventToListeners("updated",{data:this.descriptor.data,isLocal:!0,previousData:t})}}},{key:"_postUpdateToServer",value:(r=vT.default(_T.default.mark((function e(t){var n,r,i;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isDeleted){e.next=17;break}return n={data:t.data},void 0!==t.ttl&&(n.ttl=t.ttl),r=t.revision,e.prev=4,e.next=7,this.services.network.post(this.uri,n,r);case 7:return i=e.sent,e.abrupt("return",{revision:i.body.revision,data:t.data,last_event_id:i.body.last_event_id,date_updated:i.body.date_updated,date_expires:i.body.date_expires});case 11:throw e.prev=11,e.t0=e.catch(4),404===e.t0.status&&this.onRemoved(!1),e.t0;case 15:e.next=18;break;case 17:return e.abrupt("return",Promise.reject(new SyncError("The Document has been removed",404,54100)));case 18:case"end":return e.stop()}}),e,this,[[4,11]])}))),function(e){return r.apply(this,arguments)})},{key:"_softSync",value:(n=vT.default(_T.default.mark((function e(){var t=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.services.network.get(this.uri).then((function(e){var n={type:"document_updated",id:e.body.last_event_id,document_revision:e.body.revision,document_data:e.body.data,date_created:e.body.date_updated};return t._update(n),t})).catch((function(e){404===e.status?t.onRemoved(!1):rR("Can't get updates for ".concat(t.sid,":"),e)})));case 1:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"onRemoved",value:function(e){if(!this.isDeleted){var t=void 0!==this.descriptor.data?KT(this.descriptor.data):null;this.isDeleted=!0,this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e,previousData:t})}}},{key:"removeDocument",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.isDeleted){e.next=6;break}return e.next=3,this.services.network.delete(this.uri);case 3:this.onRemoved(!0),e.next=7;break;case 6:return e.abrupt("return",Promise.reject(new SyncError("The Document has been removed",404,54100)));case 7:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}],[{key:"type",get:function(){return"document"}}]),f}(_R),OR=function(e){bT.default(o,e);var t,n,r,i,a,s=CR(o);function o(e){var t;return yT.default(this,o),(t=s.call(this)).syncDocumentImpl=e,t.syncDocumentImpl.attach(gT.default(t)),t}return mT.default(o,[{key:"uri",get:function(){return this.syncDocumentImpl.uri}},{key:"revision",get:function(){return this.syncDocumentImpl.revision}},{key:"lastEventId",get:function(){return this.syncDocumentImpl.lastEventId}},{key:"dateExpires",get:function(){return this.syncDocumentImpl.dateExpires}},{key:"type",get:function(){return IR.type}},{key:"sid",get:function(){return this.syncDocumentImpl.sid}},{key:"data",get:function(){return this.syncDocumentImpl.data}},{key:"dateUpdated",get:function(){return this.syncDocumentImpl.dateUpdated}},{key:"uniqueName",get:function(){return this.syncDocumentImpl.uniqueName}},{key:"set",value:(a=vT.default(_T.default.mark((function e(t,n){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncDocumentImpl.set(t,n));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return a.apply(this,arguments)})},{key:"mutate",value:(i=vT.default(_T.default.mark((function e(t,n){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncDocumentImpl.mutate(t,n));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return i.apply(this,arguments)})},{key:"update",value:(r=vT.default(_T.default.mark((function e(t,n){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncDocumentImpl.update(t,n));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"setTtl",value:(n=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncDocumentImpl.setTtl(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"removeDocument",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncDocumentImpl.removeDocument());case 2:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"close",value:function(){IT.default(kT.default(o.prototype),"close",this).call(this),this.syncDocumentImpl.detach(this.listenerUuid)}}],[{key:"type",get:function(){return IR.type}}]),o}(RR);xT.default(OR,"removed","removed"),xT.default(OR,"updated","updated"),PT([iT.validateTypesAsync(iT.pureObject,["undefined",iT.objectSchema("document metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Object,Object]),AT("design:returntype",Promise)],OR.prototype,"set",null),PT([iT.validateTypesAsync("function",["undefined",iT.objectSchema("document metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Function,Object]),AT("design:returntype",Promise)],OR.prototype,"mutate",null),PT([iT.validateTypesAsync(iT.pureObject,["undefined",iT.objectSchema("document metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Object,Object]),AT("design:returntype",Promise)],OR.prototype,"update",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number]),AT("design:returntype",Promise)],OR.prototype,"setTtl",null);var PR=function(){function e(t){yT.default(this,e),this.descriptor=t}return mT.default(e,[{key:"uri",get:function(){return this.descriptor.uri}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.lastEventId}},{key:"dateUpdated",get:function(){return this.descriptor.dateUpdated}},{key:"dateExpires",get:function(){return this.descriptor.dateExpires}},{key:"index",get:function(){return this.descriptor.index}},{key:"data",get:function(){return this.descriptor.data}},{key:"update",value:function(e,t,n,r){return this.descriptor.lastEventId=e,this.descriptor.revision=t,this.descriptor.data=n,this.descriptor.dateUpdated=r,this}},{key:"updateDateExpires",value:function(e){this.descriptor.dateExpires=e}}]),e}(),Paginator=function(){function Paginator(e,t,n,r){yT.default(this,Paginator),this.prevToken=n,this.nextToken=r,this.items=e,this.source=t}var e,t;return mT.default(Paginator,[{key:"hasNextPage",get:function(){return!!this.nextToken}},{key:"hasPrevPage",get:function(){return!!this.prevToken}},{key:"nextPage",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasNextPage){e.next=2;break}throw new Error("No next page");case 2:return e.abrupt("return",this.source(this.nextToken));case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"prevPage",value:(e=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.hasPrevPage){e.next=2;break}throw new Error("No previous page");case 2:return e.abrupt("return",this.source(this.prevToken));case 3:case"end":return e.stop()}}),e,this)}))),function(){return e.apply(this,arguments)})}]),Paginator}();function AR(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return jR(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return jR(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function jR(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var MR=function(){function e(t,n){yT.default(this,e),this.balanceFactor=0,this.key=t,this.value=n,this.parent=null,this.left=null,this.right=null}return mT.default(e,[{key:"isRoot",get:function(){return null===this.parent}},{key:"isLeaf",get:function(){return null===this.left&&null===this.right}},{key:"isLeftChild",get:function(){return this.parent.left===this}},{key:"update",value:function(e){this.value=e}},{key:"replace",value:function(e,t){e&&(this.left===t?this.left=t:this.right===t&&(this.right=t))}}]),e}(),LR=function(){function e(t,n){yT.default(this,e),this.isLessThan=t||function(e,t){return e<t},this.isEqual=n||function(e,t){return e===t},this.root=null,this.count=null}return mT.default(e,[{key:"size",get:function(){return this.count}},{key:"clear",value:function(){this.root=null,this.count=0}},{key:"set",value:function(e,t){var n=this.getNode(e);n?n.update(t):this.insert(e,t)}},{key:"insert",value:function(e,t){var n=new MR(e,t);if(this.count++,this.root){for(var r=this.root;;)if(this.isLessThan(e,r.key)){if(!r.left){r.left=n;break}r=r.left}else{if(!r.right){r.right=n;break}r=r.right}for(n.parent=r,r=n;r.parent;){var i=r.parent,a=i.balanceFactor;if(r.isLeftChild?i.balanceFactor++:i.balanceFactor--,Math.abs(i.balanceFactor)<Math.abs(a))break;if(i.balanceFactor<-1||i.balanceFactor>1){this.rebalance(i);break}r=i}}else this.root=n}},{key:"get",value:function(e){for(var t=this.root;t;){if(this.isEqual(e,t.key))return t.value;t=this.isLessThan(e,t.key)?t.left:t.right}return null}},{key:"delete",value:function(e){var t=this.getNode(e);if(!t||t.key!==e)return null;var n=t.parent,r=t.left,i=t.right;if(!!r!=!!i){var a=r||i;n||a?n&&!a?this.root=a:(n.replace(t,null),this.rebalance(n)):this.root=null}else{for(var s=t.left;s.right;)s=s.right;if(t.left===s)t.isRoot?(this.root=s,s.parent=null):(t.isLeftChild?t.parent.left=s:t.parent.right=s,s.parent=t.parent),s.right=t.right,s.right.parent=s,s.balanceFactor=t.balanceFactor,t={parent:s,isLeftChild:!0};else{var o=s.parent,u=s.left;o.right=u,u&&(u.parent=o),t.isRoot?(this.root=s,s.parent=null):(t.isLeftChild?t.parent.left=s:t.parent.right=s,s.parent=t.parent),s.right=t.right,s.right.parent=s,s.left=t.left,s.left.parent=s,s.balanceFactor=t.balanceFactor,t={parent:o,isLeftChild:!1}}}for(this.count--;t.parent;){var c=t.parent,l=c.balanceFactor;if(t.isLeftChild?c.balanceFactor-=1:c.balanceFactor+=1,Math.abs(c.balanceFactor)>Math.abs(l)){if(!(c.balanceFactor<-1||c.balanceFactor>1))break;if(this.rebalance(c),0!==c.parent.balanceFactor)break;t=c.parent}else t=c}return null}},{key:"getNode",value:function(e){for(var t=this.root;t;){if(this.isEqual(e,t.key))return t;t=this.isLessThan(e,t.key)?t.left:t.right}return null}},{key:"rebalance",value:function(e){e.balanceFactor<0?e.right.balanceFactor>0?(this.rotateRight(e.right),this.rotateLeft(e)):this.rotateLeft(e):e.balanceFactor>0&&(e.left.balanceFactor<0?(this.rotateLeft(e.left),this.rotateRight(e)):this.rotateRight(e))}},{key:"rotateLeft",value:function(e){var t=e.right;e.right=t.left,null!==t.left&&(t.left.parent=e),t.parent=e.parent,null===t.parent?this.root=t:e.isLeftChild?t.parent.left=t:t.parent.right=t,t.left=e,e.parent=t,e.balanceFactor=e.balanceFactor+1-Math.min(t.balanceFactor,0),t.balanceFactor=t.balanceFactor+1-Math.max(e.balanceFactor,0)}},{key:"rotateRight",value:function(e){var t=e.left;e.left=t.right,null!==t.right&&(t.right.parent=e),t.parent=e.parent,null===t.parent?this.root=t:e.isLeftChild?t.parent.left=t:t.parent.right=t,t.right=e,e.parent=t,e.balanceFactor=e.balanceFactor-1-Math.min(t.balanceFactor,0),t.balanceFactor=t.balanceFactor-1-Math.max(e.balanceFactor,0)}},{key:Symbol.iterator,value:_T.default.mark((function e(){var t,n,r;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=AR(this.getIterator()),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=9;break}return r=n.value,e.next=7,r;case 7:e.next=3;break;case 9:e.next=14;break;case 11:e.prev=11,e.t0=e.catch(1),t.e(e.t0);case 14:return e.prev=14,t.f(),e.finish(14);case 17:case"end":return e.stop()}}),e,this,[[1,11,14,17]])}))},{key:"getIterator",value:_T.default.mark((function e(){var t,n,r,i=arguments;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=i.length>0&&void 0!==i[0]?i[0]:null,n=this.root;case 2:if(!n){e.next=8;break}if(!this.isEqual(t,n.key)&&(null!==t||n.left)){e.next=5;break}return e.abrupt("break",8);case 5:n=this.isLessThan(t,n.key)||null===t?n.left:n.right,e.next=2;break;case 8:if(n){e.next=10;break}return e.abrupt("return",null);case 10:r=!0;case 11:if(!r){e.next=29;break}return e.next=14,[n.key,n.value];case 14:if(r=!1,!n.right){e.next=21;break}for(n=n.right;n.left;)n=n.left;r=!0,e.next=27;break;case 21:if(!n.parent){e.next=26;break}r=n.parent.left===n,n=n.parent,e.next=27;break;case 26:return e.abrupt("break",37);case 27:e.next=35;break;case 29:if(!n.parent){e.next=34;break}r=n.parent.left===n,n=n.parent,e.next=35;break;case 34:return e.abrupt("break",37);case 35:e.next=11;break;case 37:return e.abrupt("return",null);case 38:case"end":return e.stop()}}),e,this)}))},{key:"getReverseIterator",value:_T.default.mark((function e(){var t,n,r,i=arguments;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=i.length>0&&void 0!==i[0]?i[0]:null,n=this.root;case 2:if(!n){e.next=8;break}if(!this.isEqual(t,n.key)&&(null!==t||n.right)){e.next=5;break}return e.abrupt("break",8);case 5:n=this.isLessThan(t,n.key)&&null!==t?n.left:n.right,e.next=2;break;case 8:if(n){e.next=10;break}return e.abrupt("return",null);case 10:r=!0;case 11:if(!r){e.next=29;break}return e.next=14,[n.key,n.value];case 14:if(r=!1,!n.left){e.next=21;break}for(n=n.left;n.right;)n=n.right;r=!0,e.next=27;break;case 21:if(!n.parent){e.next=26;break}r=n.parent.right===n,n=n.parent,e.next=27;break;case 26:return e.abrupt("break",37);case 27:e.next=35;break;case 29:if(!n.parent){e.next=34;break}r=n.parent.right===n,n=n.parent,e.next=35;break;case 34:return e.abrupt("break",37);case 35:e.next=11;break;case 37:return e.abrupt("return",null);case 38:case"end":return e.stop()}}),e,this)}))}]),e}();function NR(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return UR(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return UR(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function UR(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var DR=function(){function e(t,n){yT.default(this,e),this.value=t,this.revision=n||0}return mT.default(e,[{key:"isValid",get:function(){return!0}}]),e}(),FR=function(){function e(t){yT.default(this,e),this.revision=t}return mT.default(e,[{key:"isValid",get:function(){return!1}}]),e}(),BR=function(){function e(){yT.default(this,e),this.items=new LR}return mT.default(e,[{key:"store",value:function(e,t,n){var r=this.items.get(e);return r&&r.revision>n?r.isValid?r.value:null:(this.items.set(e,new DR(t,n)),t)}},{key:"delete",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this.items.get(e);(!r||r.revision<t||r&&!0===n)&&this.items.set(e,new FR(t))}},{key:"isKnown",value:function(e,t){var n=this.items.get(e);return n&&n.revision>=t}},{key:"get",value:function(e){var t=this.items.get(e);return t&&t.isValid?t.value:null}},{key:"has",value:function(e){var t=this.items.get(e);return t&&t.isValid}},{key:"forEach",value:function(e){if(this.items){var t,n=NR(this.items);try{for(n.s();!(t=n.n()).done;){var r=RT.default(t.value,2),i=r[0],a=r[1];a.isValid&&e(i,a.value)}}catch(e){n.e(e)}finally{n.f()}}}}]),e}();function qR(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}var zR=function(e){bT.default(y,e);var t,n,r,i,a,s,o,u,c,l,f,d,p,h,v=qR(y);function y(e,t,n){var r;yT.default(this,y);return(r=v.call(this,e,n)).updateMergingQueue=new ER((function(e,t){return"number"==typeof t.ttl?{ttl:t.ttl}:e})),r.cache=new BR,r.descriptor=t,r.descriptor.date_updated=new Date(r.descriptor.date_updated),r}return mT.default(y,[{key:"uri",get:function(){return this.descriptor.url}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"links",get:function(){return this.descriptor.links}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"type",get:function(){return"list"}},{key:"indexName",get:function(){}},{key:"queryString",get:function(){}},{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return this.descriptor.unique_name||null}},{key:"dateUpdated",get:function(){return this.descriptor.date_updated}},{key:"_addOrUpdateItemOnServer",value:(h=vT.default(_T.default.mark((function e(t,n,r,i){var a,s;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a={data:n},void 0!==i&&(a.ttl=i),e.next=4,this.services.network.post(t,a,r);case 4:return(s=e.sent).body.data=n,s.body.date_updated=new Date(s.body.date_updated),e.abrupt("return",s.body);case 8:case"end":return e.stop()}}),e,this)}))),function(e,t,n,r){return h.apply(this,arguments)})},{key:"push",value:(p=vT.default(_T.default.mark((function e(t,n){var r,i,a;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=(n||{}).ttl,e.next=3,this._addOrUpdateItemOnServer(this.links.items,t,void 0,r);case 3:return i=e.sent,a=Number(i.index),this._handleItemMutated(a,i.url,i.last_event_id,i.revision,t,i.date_updated,i.date_expires,!0,!1),e.abrupt("return",this.cache.get(a));case 7:case"end":return e.stop()}}),e,this)}))),function(e,t){return p.apply(this,arguments)})},{key:"set",value:(d=vT.default(_T.default.mark((function e(t,n,r){var i,a=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r||{},e.abrupt("return",this.updateMergingQueue.squashAndAdd(t,i,(function(e){return a._updateItemUnconditionally(t,n,e.ttl)})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return d.apply(this,arguments)})},{key:"_updateItemUnconditionally",value:(f=vT.default(_T.default.mark((function e(t,n,r){var i,a;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.get(t);case 2:return i=e.sent,e.next=5,this._addOrUpdateItemOnServer(i.uri,n,void 0,r);case 5:return a=e.sent,this._handleItemMutated(t,a.url,a.last_event_id,a.revision,a.data,a.date_updated,a.date_expires,!1,!1),e.abrupt("return",this.cache.get(t));case 8:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return f.apply(this,arguments)})},{key:"_updateItemWithIfMatch",value:(l=vT.default(_T.default.mark((function e(t,n,r){var i,a,s,o;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.get(t);case 2:if(i=e.sent,!(a=n(KT(i.data)))){e.next=25;break}return s=i.revision,e.prev=6,e.next=9,this._addOrUpdateItemOnServer(i.uri,a,s,r);case 9:return o=e.sent,this._handleItemMutated(t,o.url,o.last_event_id,o.revision,o.data,o.date_updated,o.date_expires,!1,!1),e.abrupt("return",this.cache.get(t));case 14:if(e.prev=14,e.t0=e.catch(6),412!==e.t0.status){e.next=22;break}return e.next=19,this._getItemFromServer(t);case 19:return e.abrupt("return",this._updateItemWithIfMatch(t,n,r));case 22:throw e.t0;case 23:e.next=26;break;case 25:return e.abrupt("return",i);case 26:case"end":return e.stop()}}),e,this,[[6,14]])}))),function(e,t,n){return l.apply(this,arguments)})},{key:"mutate",value:(c=vT.default(_T.default.mark((function e(t,n,r){var i,a=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r||{},e.abrupt("return",this.updateMergingQueue.add(t,i,(function(e){return a._updateItemWithIfMatch(t,n,e.ttl)})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return c.apply(this,arguments)})},{key:"update",value:(u=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.mutate(t,(function(e){return Object.assign(e,n)}),r));case 1:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return u.apply(this,arguments)})},{key:"remove",value:(o=vT.default(_T.default.mark((function e(t){var n,r,i;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.get(t);case 2:return n=e.sent,r=KT(n.data),e.next=6,this.services.network.delete(n.uri);case 6:i=e.sent,this._handleItemRemoved(t,i.body.last_event_id,r,new Date(i.body.date_updated),!1);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"get",value:function(){var e=vT.default(_T.default.mark((function e(t){var n;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(n=this.cache.get(t))){e.next=5;break}return e.abrupt("return",n);case 5:return e.abrupt("return",this._getItemFromServer(t));case 6:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"_getItemFromServer",value:(s=vT.default(_T.default.mark((function e(t){var n;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.queryItems({index:t});case 2:if(!((n=e.sent).items.length<1)){e.next=7;break}throw new SyncError("No item with index ".concat(t," found"),404,54151);case 7:return e.abrupt("return",n.items[0]);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"queryItems",value:function(){var e=vT.default(_T.default.mark((function e(t){var n,r,i,a,s=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=t||{},n=new $T(this.links.items).queryParam("From",t.from).queryParam("PageSize",t.limit).queryParam("Index",t.index).queryParam("PageToken",t.pageToken).queryParam("Order",t.order).build(),e.next=4,this.services.network.get(n);case 4:return r=e.sent,i=r.body.items.map((function(e){return e.date_updated=new Date(e.date_updated),s.cache.get(e.index)?s._handleItemMutated(e.index,e.url,e.last_event_id,e.revision,e.data,e.date_updated,e.date_expires,!1,!0):s.cache.store(Number(e.index),new PR({index:Number(e.index),uri:e.url,revision:e.revision,lastEventId:e.last_event_id,dateUpdated:e.date_updated,dateExpires:e.date_expires,data:e.data}),e.last_event_id),s.cache.get(e.index)})),a=r.body.meta,e.abrupt("return",new Paginator(i,(function(e){return s.queryItems({pageToken:e})}),a.previous_token,a.next_token));case 8:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"getItems",value:(a=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return HT((t=t||{}).pageSize),t.limit=t.pageSize||t.limit||50,t.order=t.order||"asc",e.abrupt("return",this.queryItems(t));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"getContext",value:(i=vT.default(_T.default.mark((function e(){var t;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.context){e.next=5;break}return e.next=3,this.services.network.get(this.links.context);case 3:t=e.sent,this._updateContextIfRequired(t.body.data,t.body.last_event_id);case 5:return e.abrupt("return",this.context);case 6:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"setTtl",value:(r=vT.default(_T.default.mark((function e(t){var n,r;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,n={ttl:t},e.next=4,this.services.network.post(this.uri,n);case 4:r=e.sent,this.descriptor.date_expires=r.body.date_expires,e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(0),404===e.t0.status&&this.onRemoved(!1),e.t0;case 12:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(e){return r.apply(this,arguments)})},{key:"setItemTtl",value:(n=vT.default(_T.default.mark((function e(t,n){var r,i,a;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.get(t);case 2:return r=e.sent,i={ttl:n},e.next=6,this.services.network.post(r.uri,i);case 6:a=e.sent,r.updateDateExpires(a.body.date_expires);case 8:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"removeList",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.network.delete(this.uri);case 2:this.onRemoved(!0);case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"onRemoved",value:function(e){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e})}},{key:"shouldIgnoreEvent",value:function(e,t){return this.cache.isKnown(e,t)}},{key:"_update",value:function(e,t){var n=Number(e.item_index);switch(e.date_created=new Date(e.date_created),e.type){case"list_item_added":case"list_item_updated":this._handleItemMutated(n,e.item_url,e.id,e.item_revision,e.item_data,e.date_created,void 0,"list_item_added"===e.type,!0);break;case"list_item_removed":this._handleItemRemoved(n,e.id,e.item_data,e.date_created,!0);break;case"list_context_updated":this._handleContextUpdate(e.context_data,e.id,e.date_created);break;case"list_removed":this.onRemoved(!1)}t&&this._advanceLastEventId(e.id,e.list_revision)}},{key:"_advanceLastEventId",value:function(e,t){this.lastEventId<e&&(this.descriptor.last_event_id=e,t&&(this.descriptor.revision=t))}},{key:"_updateRootDateUpdated",value:function(e){(!this.descriptor.date_updated||e.getTime()>this.descriptor.date_updated.getTime())&&(this.descriptor.date_updated=e,this.services.storage.update(this.type,this.sid,this.uniqueName,{date_updated:e}))}},{key:"_handleItemMutated",value:function(e,t,n,r,i,a,s,o,u){if(this.shouldIgnoreEvent(e,n))eR("Item ".concat(e," update skipped, current: ").concat(this.lastEventId,", remote: ").concat(n));else{this._updateRootDateUpdated(a);var c=this.cache.get(e);if(!c){var l=new PR({index:e,uri:t,lastEventId:n,revision:r,data:i,dateUpdated:a,dateExpires:s});return this.cache.store(e,l,n),void this.emitItemMutationEvent(l,u,o)}var f=KT(c.data);c.update(n,r,i,a),this.cache.store(e,c,n),void 0!==s&&c.updateDateExpires(s),this.emitItemMutationEvent(c,u,!1,f)}}},{key:"emitItemMutationEvent",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=n?"itemAdded":"itemUpdated",a={item:e,isLocal:!t};n||(a.previousItemData=r),this.broadcastEventToListeners(i,a)}},{key:"_handleItemRemoved",value:function(e,t,n,r,i){this._updateRootDateUpdated(r),this.cache.delete(e,t),this.broadcastEventToListeners("itemRemoved",{index:e,isLocal:!i,previousItemData:n})}},{key:"_handleContextUpdate",value:function(e,t,n){this._updateRootDateUpdated(n),this._updateContextIfRequired(e,t)&&this.broadcastEventToListeners("contextUpdated",{context:e,isLocal:!1})}},{key:"_updateContextIfRequired",value:function(e,t){return!this.contextEventId||t>this.contextEventId?(this.context=e,this.contextEventId=t,!0):(eR("Context update skipped, current:",this.lastEventId,", remote:",t),!1)}}],[{key:"type",get:function(){return"list"}}]),y}(_R),WR=function(e){bT.default(p,e);var t,n,r,i,a,s,o,u,c,l,f,d=qR(p);function p(e){var t;return yT.default(this,p),(t=d.call(this)).syncListImpl=e,t.syncListImpl.attach(gT.default(t)),t}return mT.default(p,[{key:"uri",get:function(){return this.syncListImpl.uri}},{key:"revision",get:function(){return this.syncListImpl.revision}},{key:"lastEventId",get:function(){return this.syncListImpl.lastEventId}},{key:"links",get:function(){return this.syncListImpl.links}},{key:"dateExpires",get:function(){return this.syncListImpl.dateExpires}},{key:"type",get:function(){return zR.type}},{key:"sid",get:function(){return this.syncListImpl.sid}},{key:"uniqueName",get:function(){return this.syncListImpl.uniqueName}},{key:"dateUpdated",get:function(){return this.syncListImpl.dateUpdated}},{key:"push",value:(f=vT.default(_T.default.mark((function e(t,n){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.push(t,n));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return f.apply(this,arguments)})},{key:"set",value:(l=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.set(t,n,r));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return l.apply(this,arguments)})},{key:"mutate",value:(c=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.mutate(t,n,r));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return c.apply(this,arguments)})},{key:"update",value:(u=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.update(t,n,r));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return u.apply(this,arguments)})},{key:"remove",value:(o=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.remove(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"get",value:(s=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.get(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"getContext",value:(a=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.getContext());case 2:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"getItems",value:(i=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.getItems(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"setTtl",value:(r=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.setTtl(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"setItemTtl",value:(n=vT.default(_T.default.mark((function e(t,n){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.setItemTtl(t,n));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"removeList",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncListImpl.removeList());case 2:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"close",value:function(){IT.default(kT.default(p.prototype),"close",this).call(this),this.syncListImpl.detach(this.listenerUuid)}}],[{key:"type",get:function(){return zR.type}}]),p}(RR);xT.default(WR,"itemAdded","itemAdded"),xT.default(WR,"itemUpdated","itemUpdated"),xT.default(WR,"itemRemoved","itemRemoved"),xT.default(WR,"removed","removed"),PT([iT.validateTypesAsync(iT.pureObject,["undefined",iT.objectSchema("item metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Object,Object]),AT("design:returntype",Promise)],WR.prototype,"push",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger,iT.pureObject,["undefined",iT.objectSchema("item metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Number,Object,Object]),AT("design:returntype",Promise)],WR.prototype,"set",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger,"function",["undefined",iT.objectSchema("item metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Number,Function,Object]),AT("design:returntype",Promise)],WR.prototype,"mutate",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger,iT.pureObject,["undefined",iT.objectSchema("item metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Number,Object,Object]),AT("design:returntype",Promise)],WR.prototype,"update",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number]),AT("design:returntype",Promise)],WR.prototype,"remove",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number]),AT("design:returntype",Promise)],WR.prototype,"get",null),PT([iT.validateTypesAsync(["undefined",iT.objectSchema("query options",{from:[iT.nonNegativeInteger,"undefined"],pageSize:[iT.custom((function(e){return[YT(e),"a positive integer"]})),"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],WR.prototype,"getItems",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number]),AT("design:returntype",Promise)],WR.prototype,"setTtl",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger,iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number,Number]),AT("design:returntype",Promise)],WR.prototype,"setItemTtl",null);var GR=function(){function e(t){yT.default(this,e),this.descriptor=t}return mT.default(e,[{key:"uri",get:function(){return this.descriptor.url}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"key",get:function(){return this.descriptor.key}},{key:"data",get:function(){return this.descriptor.data}},{key:"dateUpdated",get:function(){return this.descriptor.date_updated}},{key:"update",value:function(e,t,n,r){return this.descriptor.last_event_id=e,this.descriptor.revision=t,this.descriptor.data=n,this.descriptor.date_updated=r,this}},{key:"updateDateExpires",value:function(e){this.descriptor.date_expires=e}}]),e}();function $R(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}var VR=function(e){bT.default(h,e);var t,n,r,i,a,s,o,u,c,l,f,d,p=$R(h);function h(e,t,n){var r;yT.default(this,h);return(r=p.call(this,e,n)).updateMergingQueue=new ER((function(e,t){return"number"==typeof t.ttl?{ttl:t.ttl}:e})),r.cache=new BR,r.descriptor=t,r.descriptor.date_updated=new Date(r.descriptor.date_updated),t.items&&t.items.forEach((function(e){e.date_updated=new Date(e.date_updated),r.cache.store(e.key,new GR(e),e.last_event_id)})),r}return mT.default(h,[{key:"uri",get:function(){return this.descriptor.url}},{key:"links",get:function(){return this.descriptor.links}},{key:"revision",get:function(){return this.descriptor.revision}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"type",get:function(){return"map"}},{key:"indexName",get:function(){}},{key:"queryString",get:function(){}},{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return this.descriptor.unique_name||null}},{key:"dateUpdated",get:function(){return this.descriptor.date_updated}},{key:"set",value:(d=vT.default(_T.default.mark((function e(t,n,r){var i,a=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r||{},e.abrupt("return",this.updateMergingQueue.squashAndAdd(t,i,(function(e){return a._putItemUnconditionally(t,n,e.ttl)})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return d.apply(this,arguments)})},{key:"get",value:function(){var e=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=t){e.next=2;break}throw new SyncError("SyncMapItem key may not be empty",400,54209);case 2:if(!this.cache.has(t)){e.next=6;break}return e.abrupt("return",this.cache.get(t));case 6:return e.abrupt("return",this._getItemFromServer(t));case 7:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"_getItemFromServer",value:(f=vT.default(_T.default.mark((function e(t){var n;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.queryItems({key:t});case 2:if(!((n=e.sent).items.length<1)){e.next=7;break}throw new SyncError("The specified Map Item does not exist",404,54201);case 7:return e.abrupt("return",n.items[0]);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return f.apply(this,arguments)})},{key:"mutate",value:(l=vT.default(_T.default.mark((function e(t,n,r){var i,a=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r||{},e.abrupt("return",this.updateMergingQueue.add(t,i,(function(e){return a._putItemWithIfMatch(t,n,e.ttl)})));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return l.apply(this,arguments)})},{key:"update",value:(c=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.mutate(t,(function(e){return Object.assign(e,n)}),r));case 1:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return c.apply(this,arguments)})},{key:"_putItemUnconditionally",value:(u=vT.default(_T.default.mark((function e(t,n,r){var i,a;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._putItemToServer(t,n,void 0,r);case 2:return i=e.sent,a=i.item,this._handleItemMutated(a.key,a.url,a.last_event_id,a.revision,a.data,a.date_updated,a.date_expires,i.added,!1),e.abrupt("return",this.cache.get(a.key));case 6:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return u.apply(this,arguments)})},{key:"_putItemWithIfMatch",value:(o=vT.default(_T.default.mark((function e(t,n,r){var i,a,s,o,u;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.get(t).catch((function(e){if(404===e.status)return new GR({key:t,data:{},last_event_id:-1,revision:"-1",url:null,date_updated:null,date_expires:null});throw e}));case 2:if(i=e.sent,!(a=n(KT(i.data)))){e.next=26;break}return s=i.revision,e.prev=6,e.next=9,this._putItemToServer(t,a,s,r);case 9:return o=e.sent,u=o.item,this._handleItemMutated(u.key,u.url,u.last_event_id,u.revision,u.data,u.date_updated,u.date_expires,o.added,!1),e.abrupt("return",this.cache.get(u.key));case 15:if(e.prev=15,e.t0=e.catch(6),412!==e.t0.status){e.next=23;break}return e.next=20,this._getItemFromServer(t);case 20:return e.abrupt("return",this._putItemWithIfMatch(t,n,r));case 23:throw e.t0;case 24:e.next=27;break;case 26:return e.abrupt("return",i);case 27:case"end":return e.stop()}}),e,this,[[6,15]])}))),function(e,t,n){return o.apply(this,arguments)})},{key:"_putItemToServer",value:(s=vT.default(_T.default.mark((function e(t,n,r,i){var a,s,o,u,c;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=new $T(this.links.items).pathSegment(t).build(),s={data:n},void 0!==i&&(s.ttl=i),e.prev=3,e.next=6,this.services.network.put(a,s,r);case 6:return o=e.sent,(u=o.body).data=n,u.date_updated=new Date(u.date_updated),c=201===o.status.code,e.abrupt("return",{added:c,item:u});case 14:throw e.prev=14,e.t0=e.catch(3),404===e.t0.status&&this.onRemoved(!1),e.t0;case 18:case"end":return e.stop()}}),e,this,[[3,14]])}))),function(e,t,n,r){return s.apply(this,arguments)})},{key:"remove",value:(a=vT.default(_T.default.mark((function e(t){var n,r,i;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.get(t);case 2:return n=e.sent,r=KT(n.data),e.next=6,this.services.network.delete(n.uri);case 6:i=e.sent,this._handleItemRemoved(t,i.body.last_event_id,r,new Date(i.body.date_updated),!1);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"queryItems",value:function(){var e=vT.default(_T.default.mark((function e(t){var n,r,i,a,s=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=t||{},n=new $T(this.links.items).queryParam("From",t.from).queryParam("PageSize",t.limit).queryParam("Key",t.key).queryParam("PageToken",t.pageToken).queryParam("Order",t.order).build(),e.next=4,this.services.network.get(n);case 4:return r=e.sent,i=r.body.items.map((function(e){return e.date_updated=new Date(e.date_updated),s.cache.get(e.key)?s._handleItemMutated(e.key,e.url,e.last_event_id,e.revision,e.data,e.date_updated,e.date_expires,!1,!0):s.cache.store(e.key,new GR(e),e.last_event_id),s.cache.get(e.key)})),a=r.body.meta,e.abrupt("return",new Paginator(i,(function(e){return s.queryItems({pageToken:e})}),a.previous_token,a.next_token));case 8:case"end":return e.stop()}}),e,this)})));return function(t){return e.apply(this,arguments)}}()},{key:"getItems",value:(i=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return HT((t=t||{}).pageSize),t.limit=t.pageSize||t.limit||50,t.order=t.order||"asc",e.abrupt("return",this.queryItems(t));case 5:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"shouldIgnoreEvent",value:function(e,t){return this.cache.isKnown(e,t)}},{key:"_update",value:function(e,t){switch(e.date_created=new Date(e.date_created),e.type){case"map_item_added":case"map_item_updated":this._handleItemMutated(e.item_key,e.item_url,e.id,e.item_revision,e.item_data,e.date_created,void 0,"map_item_added"===e.type,!0);break;case"map_item_removed":this._handleItemRemoved(e.item_key,e.id,e.item_data,e.date_created,!0);break;case"map_removed":this.onRemoved(!1)}t&&this._advanceLastEventId(e.id,e.map_revision)}},{key:"_advanceLastEventId",value:function(e,t){this.lastEventId<e&&(this.descriptor.last_event_id=e,t&&(this.descriptor.revision=t))}},{key:"_updateRootDateUpdated",value:function(e){(!this.descriptor.date_updated||e.getTime()>this.descriptor.date_updated.getTime())&&(this.descriptor.date_updated=e,this.services.storage.update(this.type,this.sid,this.uniqueName,{date_updated:e}))}},{key:"_handleItemMutated",value:function(e,t,n,r,i,a,s,o,u){if(this.shouldIgnoreEvent(e,n))eR("SyncMapItem ",e," update skipped, current:",this.lastEventId,", remote:",n);else{this._updateRootDateUpdated(a);var c=this.cache.get(e);if(!c){var l=new GR({key:e,url:t,last_event_id:n,revision:r,data:i,date_updated:a,date_expires:s});return this.cache.store(e,l,n),void this.emitItemMutationEvent(l,u,o)}var f=KT(c.data);c.update(n,r,i,a),this.cache.store(e,c,n),void 0!==s&&c.updateDateExpires(s),this.emitItemMutationEvent(c,u,!1,f)}}},{key:"emitItemMutationEvent",value:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,i=n?"itemAdded":"itemUpdated",a={item:e,isLocal:!t};n||(a.previousItemData=r),this.broadcastEventToListeners(i,a)}},{key:"_handleItemRemoved",value:function(e,t,n,r,i){this._updateRootDateUpdated(r),this.cache.delete(e,t),this.broadcastEventToListeners("itemRemoved",{key:e,isLocal:!i,previousItemData:n})}},{key:"onRemoved",value:function(e){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e})}},{key:"setTtl",value:(r=vT.default(_T.default.mark((function e(t){var n,r;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,n={ttl:t},e.next=4,this.services.network.post(this.uri,n);case 4:r=e.sent,this.descriptor.date_expires=r.body.date_expires,e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(0),404===e.t0.status&&this.onRemoved(!1),e.t0;case 12:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(e){return r.apply(this,arguments)})},{key:"setItemTtl",value:(n=vT.default(_T.default.mark((function e(t,n){var r,i,a;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.get(t);case 2:return r=e.sent,i={ttl:n},e.next=6,this.services.network.post(r.uri,i);case 6:a=e.sent,r.updateDateExpires(a.body.date_expires);case 8:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"removeMap",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.network.delete(this.uri);case 2:this.onRemoved(!0);case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}],[{key:"type",get:function(){return"map"}}]),h}(_R),JR=function(e){bT.default(f,e);var t,n,r,i,a,s,o,u,c,l=$R(f);function f(e){var t;return yT.default(this,f),(t=l.call(this)).syncMapImpl=e,t.syncMapImpl.attach(gT.default(t)),t}return mT.default(f,[{key:"uri",get:function(){return this.syncMapImpl.uri}},{key:"links",get:function(){return this.syncMapImpl.links}},{key:"revision",get:function(){return this.syncMapImpl.revision}},{key:"lastEventId",get:function(){return this.syncMapImpl.lastEventId}},{key:"dateExpires",get:function(){return this.syncMapImpl.dateExpires}},{key:"type",get:function(){return VR.type}},{key:"sid",get:function(){return this.syncMapImpl.sid}},{key:"uniqueName",get:function(){return this.syncMapImpl.uniqueName}},{key:"dateUpdated",get:function(){return this.syncMapImpl.dateUpdated}},{key:"set",value:(c=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.set(t,n,r));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return c.apply(this,arguments)})},{key:"get",value:(u=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.get(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"mutate",value:(o=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.mutate(t,n,r));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return o.apply(this,arguments)})},{key:"update",value:(s=vT.default(_T.default.mark((function e(t,n,r){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.update(t,n,r));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return s.apply(this,arguments)})},{key:"remove",value:(a=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.remove(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"getItems",value:(i=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.getItems(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"setTtl",value:(r=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.setTtl(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"setItemTtl",value:(n=vT.default(_T.default.mark((function e(t,n){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncMapImpl.setItemTtl(t,n));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"removeMap",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.next=3,this.syncMapImpl.removeMap();case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"close",value:function(){IT.default(kT.default(f.prototype),"close",this).call(this),this.syncMapImpl.detach(this.listenerUuid)}}],[{key:"type",get:function(){return VR.type}}]),f}(RR);function KR(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}xT.default(JR,"itemAdded","itemAdded"),xT.default(JR,"itemUpdated","itemUpdated"),xT.default(JR,"itemRemoved","itemRemoved"),xT.default(JR,"removed","removed"),PT([iT.validateTypesAsync("string",iT.pureObject,["undefined",iT.objectSchema("item metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[String,Object,Object]),AT("design:returntype",Promise)],JR.prototype,"set",null),PT([iT.validateTypesAsync("string"),AT("design:type",Function),AT("design:paramtypes",[String]),AT("design:returntype",Promise)],JR.prototype,"get",null),PT([iT.validateTypesAsync("string","function",["undefined",iT.objectSchema("item metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[String,Function,Object]),AT("design:returntype",Promise)],JR.prototype,"mutate",null),PT([iT.validateTypesAsync("string",iT.pureObject,["undefined",iT.objectSchema("item metadata",{ttl:[iT.nonNegativeInteger,"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[String,Object,Object]),AT("design:returntype",Promise)],JR.prototype,"update",null),PT([iT.validateTypesAsync("string"),AT("design:type",Function),AT("design:paramtypes",[String]),AT("design:returntype",Promise)],JR.prototype,"remove",null),PT([iT.validateTypesAsync(["undefined",iT.objectSchema("query options",{from:["string","undefined"],pageSize:[iT.custom((function(e){return[YT(e),"a positive integer"]})),"undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],JR.prototype,"getItems",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number]),AT("design:returntype",Promise)],JR.prototype,"setTtl",null),PT([iT.validateTypesAsync("string",iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[String,Number]),AT("design:returntype",Promise)],JR.prototype,"setItemTtl",null);var HR=function(e){bT.default(a,e);var t,n,r,i=KR(a);function a(e,t,n){var r;return yT.default(this,a),(r=i.call(this,e,n)).descriptor=t,r}return mT.default(a,[{key:"uri",get:function(){return this.descriptor.url}},{key:"links",get:function(){return this.descriptor.links}},{key:"dateExpires",get:function(){return this.descriptor.date_expires}},{key:"type",get:function(){return"stream"}},{key:"lastEventId",get:function(){return null}},{key:"indexName",get:function(){}},{key:"queryString",get:function(){}},{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return this.descriptor.unique_name||null}},{key:"publishMessage",value:(r=vT.default(_T.default.mark((function e(t){var n,r,i,a;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n={data:t},e.next=3,this.services.network.post(this.links.messages,n);case 3:return r=e.sent,i=r.body,a=this._handleMessagePublished(i.sid,t,!1),e.abrupt("return",a);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"setTtl",value:(n=vT.default(_T.default.mark((function e(t){var n,r;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,n={ttl:t},e.next=4,this.services.network.post(this.uri,n);case 4:r=e.sent,this.descriptor.date_expires=r.body.date_expires,e.next=12;break;case 8:throw e.prev=8,e.t0=e.catch(0),404===e.t0.status&&this.onRemoved(!1),e.t0;case 12:case"end":return e.stop()}}),e,this,[[0,8]])}))),function(e){return n.apply(this,arguments)})},{key:"removeStream",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.network.delete(this.uri);case 2:this.onRemoved(!0);case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"_update",value:function(e){switch(e.type){case"stream_message_published":this._handleMessagePublished(e.message_sid,e.message_data,!0);break;case"stream_removed":this.onRemoved(!1)}}},{key:"_handleMessagePublished",value:function(e,t,n){var r={sid:e,data:t};return this.broadcastEventToListeners("messagePublished",{message:r,isLocal:!n}),r}},{key:"onRemoved",value:function(e){this._unsubscribe(),this.removalHandler(this.type,this.sid,this.uniqueName),this.broadcastEventToListeners("removed",{isLocal:e})}}],[{key:"type",get:function(){return"stream"}}]),a}(_R);PT([iT.validateTypesAsync(iT.pureObject),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],HR.prototype,"publishMessage",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number]),AT("design:returntype",Promise)],HR.prototype,"setTtl",null);var YR=function(e){bT.default(a,e);var t,n,r,i=KR(a);function a(e){var t;return yT.default(this,a),(t=i.call(this)).syncStreamImpl=e,t.syncStreamImpl.attach(gT.default(t)),t}return mT.default(a,[{key:"uri",get:function(){return this.syncStreamImpl.uri}},{key:"links",get:function(){return this.syncStreamImpl.links}},{key:"dateExpires",get:function(){return this.syncStreamImpl.dateExpires}},{key:"type",get:function(){return HR.type}},{key:"lastEventId",get:function(){return null}},{key:"sid",get:function(){return this.syncStreamImpl.sid}},{key:"uniqueName",get:function(){return this.syncStreamImpl.uniqueName}},{key:"publishMessage",value:(r=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncStreamImpl.publishMessage(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"setTtl",value:(n=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncStreamImpl.setTtl(t));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"removeStream",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.ensureNotClosed(),e.abrupt("return",this.syncStreamImpl.removeStream());case 2:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"close",value:function(){IT.default(kT.default(a.prototype),"close",this).call(this),this.syncStreamImpl.detach(this.listenerUuid)}}],[{key:"type",get:function(){return HR.type}}]),a}(RR);xT.default(YR,"messagePublished","messagePublished"),xT.default(YR,"removed","removed"),PT([iT.validateTypesAsync(iT.pureObject),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],YR.prototype,"publishMessage",null),PT([iT.validateTypesAsync(iT.nonNegativeInteger),AT("design:type",Function),AT("design:paramtypes",[Number]),AT("design:returntype",Promise)],YR.prototype,"setTtl",null);var QR=function e(t){yT.default(this,e),this.sdk="js",this.sdkVer=t,this.os=OT.os.family,this.osVer=OT.os.version,this.pl=OT.name,this.plVer=OT.version},XR=function(){function e(){yT.default(this,e),this.names=new Map,this.entities=new Map}return mT.default(e,[{key:"store",value:function(e){var t=this.entities.get(e.sid);return t||(this.entities.set(e.sid,e),e.uniqueName&&this.names.set(e.type+"::"+e.uniqueName,e.sid),e)}},{key:"getResolved",value:function(e,t){var n=this.names.get(t+"::"+e);return n?this.entities.get(n):null}},{key:"get",value:function(e,t){return this.entities.get(e)||this.getResolved(e,t)||null}},{key:"remove",value:function(e){var t=this.entities.get(e);t&&(this.entities.delete(e),t.uniqueName&&this.names.delete(t.type+"::"+t.uniqueName))}}]),e}();function ZR(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}var eC=function(e){bT.default(n,e);var t=ZR(n);function n(e,r,i,a){var s;return yT.default(this,n),(s=t.call(this,r,i)).descriptor=e,s.cache=new BR,a&&a.forEach((function(e){s.cache.store(e.key,{key:e.key,value:e.data},e.revision)})),s}return mT.default(n,[{key:"sid",get:function(){return this.descriptor.sid}},{key:"uniqueName",get:function(){return null}},{key:"type",get:function(){return n.type}},{key:"lastEventId",get:function(){return this.descriptor.last_event_id}},{key:"indexName",get:function(){return this.descriptor.indexName}},{key:"queryString",get:function(){return this.descriptor.queryExpression}},{key:"queryUri",get:function(){return this.descriptor.queryUri}},{key:"liveQueryDescriptor",get:function(){return this.descriptor}},{key:"onRemoved",value:function(){}},{key:"getItems",value:function(){var e={};return this.cache.forEach((function(t,n){e[t]=n.value})),e}},{key:"_update",value:function(e,t){switch(e.type){case"live_query_item_updated":this.handleItemMutated(e.item_key,e.item_data,e.item_revision);break;case"live_query_item_removed":this.handleItemRemoved(e.item_key,e.item_revision);break;case"live_query_updated":this.handleBatchUpdate(e.items)}t&&this._advanceLastEventId(e.last_event_id)}},{key:"handleItemMutated",value:function(e,t,n){if(this.shouldIgnoreEvent(e,n))eR("Item ".concat(e," update skipped, revision: ").concat(n));else{var r={key:e,value:t};this.cache.store(e,r,n),this.broadcastEventToListeners("itemUpdated",r)}}},{key:"handleItemRemoved",value:function(e,t){var n=null===t;this.shouldIgnoreEvent(e,t)?eR("Item ".concat(e," delete skipped, revision: ").concat(t)):(this.cache.delete(e,t,n),this.broadcastEventToListeners("itemRemoved",{key:e}))}},{key:"handleBatchUpdate",value:function(e){var t=this,n={};for(var r in null!=e&&e.forEach((function(e){n[e.key]={data:e.data,revision:e.revision}})),this.cache.forEach((function(e,r){var i=n[e];null!=i?t.handleItemMutated(e,i.data,i.revision):t.handleItemRemoved(e,null),delete n[e]})),n)this.handleItemMutated(r,n[r].data,n[r].revision)}},{key:"shouldIgnoreEvent",value:function(e,t){return null!=e&&null!=t&&this.cache.isKnown(e,t)}},{key:"_advanceLastEventId",value:function(e,t){this.lastEventId<e&&(this.descriptor.last_event_id=e)}}],[{key:"type",get:function(){return"live_query"}}]),n}(_R);function tC(e){return nC.apply(this,arguments)}function nC(){return nC=vT.default(_T.default.mark((function e(t){var n,r,i,a,s,o;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=t.network,r=t.queryString,i=t.uri,a=t.type,null!=r){e.next=3;break}throw new SyncError("Invalid query",400,54507);case 3:return s={query_string:r},a===rC.type&&(s.type=a),e.next=7,n.post(i,s,void 0,!0);case 7:return o=e.sent,e.abrupt("return",o.body);case 9:case"end":return e.stop()}}),e)}))),nC.apply(this,arguments)}var rC=function(e){bT.default(n,e);var t=ZR(n);function n(e){var r;return yT.default(this,n),(r=t.call(this)).liveQueryImpl=e,r.liveQueryImpl.attach(gT.default(r)),r}return mT.default(n,[{key:"type",get:function(){return eC.type}},{key:"lastEventId",get:function(){return this.liveQueryImpl.lastEventId}},{key:"sid",get:function(){return this.liveQueryImpl.sid}},{key:"close",value:function(){IT.default(kT.default(n.prototype),"close",this).call(this),this.liveQueryImpl.detach(this.listenerUuid)}},{key:"getItems",value:function(){return this.ensureNotClosed(),this.liveQueryImpl.getItems()}}],[{key:"type",get:function(){return eC.type}}]),n}(RR);xT.default(rC,"itemUpdated","itemUpdated"),xT.default(rC,"itemRemoved","itemRemoved");var iC=function(e){bT.default(i,e);var t,n,r=ZR(i);function i(e){var t;return yT.default(this,i),t=r.call(this),xT.default(gT.default(t),"queryExpression",null),xT.default(gT.default(t),"items",{}),Object.assign(gT.default(t),e),t.updateIndexName(e.indexName),t}return mT.default(i,[{key:"type",get:function(){return i.type}},{key:"search",value:(n=vT.default(_T.default.mark((function e(t){var n=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return this.items={},e.abrupt("return",tC({network:this.network,uri:this.queryUri,queryString:t}).then((function(e){n.queryExpression=t,e.items&&e.items.forEach((function(e){n.items[e.key]=e.data})),n.emit("searchResult",n.getItems())})).catch((function(e){throw rR("Error '".concat(e.message,"' while executing query '").concat(t,"'")),n.queryExpression=null,e})));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return n.apply(this,arguments)})},{key:"subscribe",value:(t=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=this.queryExpression){e.next=2;break}return e.abrupt("return",Promise.reject(new SyncError("Invalid query",400,54507)));case 2:return e.abrupt("return",this.liveQueryCreator(this.indexName,this.queryExpression));case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"getItems",value:function(){return this.items}},{key:"updateIndexName",value:function(e){this.indexName=e,this.queryUri=this.generateQueryUri(this.indexName)}},{key:"generateQueryUri",value:function(e){return new $T(this.insightsUri).pathSegment(e).pathSegment("Items").build()}}],[{key:"type",get:function(){return"instant_query"}}]),i}(MT);xT.default(iC,"searchResult","searchResult"),PT([iT.validateTypesAsync("string"),AT("design:type",Function),AT("design:paramtypes",[String]),AT("design:returntype",Promise)],iC.prototype,"search",null),PT([iT.validateTypes(iT.nonEmptyString),AT("design:type",Function),AT("design:paramtypes",[String]),AT("design:returntype",void 0)],iC.prototype,"updateIndexName",null);function aC(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=kT.default(e);if(t){var i=kT.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return wT.default(this,n)}}function sC(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 oC(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?sC(Object(n),!0).forEach((function(t){xT.default(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sC(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var uC="data_sync",cC="3.1.0";function lC(e){if(e){if("string"==typeof e)return{id:e,mode:"open_or_create"};var t=e.mode||(e.id?"open_or_create":"create_new");return oC(oC({},e),{},{mode:t})}return{mode:"create_new"}}var fC="com.twilio.rtd.cds.document",dC="com.twilio.rtd.cds.list",pC="com.twilio.rtd.cds.map",hC="twilio.sync.event",Client=function(e){bT.default(Client,e);var t,n,r,i,a,s,o,u,c,l,f,d,p,h,v,y=aC(Client);function Client(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(yT.default(this,Client),t=y.call(this),!e)throw new Error("Sync library needs a valid Twilio token to be passed");n.hasOwnProperty("logLevel")?ZT(n.logLevel):ZT("silent");var r=n.productId=n.productId||uC;n.clientMetadata=n.clientMetadata||{},n.clientMetadata.hasOwnProperty("type")||(n.clientMetadata.type="sync"),n.clientMetadata.hasOwnProperty("sdk")||(n.clientMetadata.sdk="JS",n.clientMetadata.sdkv=cC);var i=!n.twilsockClient;if(!n.initRegistrations){var a=new aT.InitRegistration(r);Client.populateInitRegistrations(a),n.initRegistrations=[a]}var s=n.twilsockClient=n.twilsockClient||new aT.Twilsock(e,r,n);s.on("tokenAboutToExpire",(function(e){return t.emit("tokenAboutToExpire",e)})),s.on("tokenExpired",(function(){return t.emit("tokenExpired")})),s.on("connectionError",(function(e){return t.emit("connectionError",e)})),s.on("stateChanged",(function(e){t.emit("connectionStateChanged",e),t.services.subscriptions.onConnectionStateChanged("connected"===e)})),s.on("message",(function(e,n){return t._routeMessage(e,n)}));var o=new fR(n),u=new bR(new QR(cC),o,s),c=new wR(o);return t.services={config:o,twilsock:s,network:u,storage:c,router:gT.default(t),subscriptions:null},t.services.subscriptions=new vR(t.services),t.entities=new XR,i&&s.connect(),t}return mT.default(Client,[{key:"_routeMessage",value:function(e,t){switch(eR("Notification type:",e,"content:",t),e){case fC:case dC:case pC:this.services.subscriptions.acceptMessage(t,!1);break;case hC:this.services.subscriptions.acceptMessage(t,!0)}}},{key:"_subscribe",value:function(e,t){this.services.subscriptions.add(e,t)}},{key:"_unsubscribe",value:function(e){this.services.subscriptions.remove(e)}},{key:"connectionState",get:function(){return this.services.twilsock.state}},{key:"ensureReady",value:(v=vT.default(_T.default.mark((function e(){var t;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.services.config.sessionStorageEnabled){e.next=2;break}return e.abrupt("return");case 2:return e.prev=2,e.next=5,this.services.twilsock.storageId();case 5:t=e.sent,this.services.storage.updateStorageId(t.id),e.next=12;break;case 9:e.prev=9,e.t0=e.catch(2),nR("Failed to initialize storage",e.t0);case 12:case"end":return e.stop()}}),e,this,[[2,9]])}))),function(){return v.apply(this,arguments)})},{key:"storeRootInSessionCache",value:function(e,t,n){if(this.services.config.sessionStorageEnabled&&t){var r=KT(n);e!==WR.type&&e!==JR.type||(r.last_event_id=null,delete r.items),this.services.storage.store(e,t,r)}}},{key:"readRootFromSessionCache",value:function(e,t){return this.services.config.sessionStorageEnabled&&t?this.services.storage.read(e,t):null}},{key:"_get",value:(h=vT.default(_T.default.mark((function e(t,n){var r,i,a,s=arguments;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=s.length>2&&void 0!==s[2]&&s[2],n){e.next=3;break}throw new SyncError("Cannot get entity without id",404);case 3:return i=new $T(t).pathSegment(n).queryParam("Include",r?"items":void 0).build(),e.next=6,this.services.network.get(i);case 6:return a=e.sent,e.abrupt("return",a.body);case 8:case"end":return e.stop()}}),e,this)}))),function(e,t){return h.apply(this,arguments)})},{key:"_createDocument",value:function(e,t,n){var r={unique_name:e,data:t||{}};return void 0!==n&&(r.ttl=n),this.services.network.post(this.services.config.documentsUri,r).then((function(e){return e.body.data=r.data,e.body}))}},{key:"_getDocument",value:(p=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.readRootFromSessionCache(OR.type,t)||this._get(this.services.config.documentsUri,t));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"_createList",value:function(e,t,n,r){var i={unique_name:e,purpose:t,context:n};return void 0!==r&&(i.ttl=r),this.services.network.post(this.services.config.listsUri,i).then((function(e){return e.body}))}},{key:"_getList",value:(d=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.readRootFromSessionCache(WR.type,t)||this._get(this.services.config.listsUri,t));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return d.apply(this,arguments)})},{key:"_createMap",value:function(e,t){var n={unique_name:e};return void 0!==t&&(n.ttl=t),this.services.network.post(this.services.config.mapsUri,n).then((function(e){return e.body}))}},{key:"_getMap",value:(f=vT.default(_T.default.mark((function e(t){var n,r=arguments;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=r.length>1&&void 0!==r[1]&&r[1],e.abrupt("return",this.readRootFromSessionCache(JR.type,t)||this._get(this.services.config.mapsUri,t,n));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return f.apply(this,arguments)})},{key:"_getStream",value:(l=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.readRootFromSessionCache(YR.type,t)||this._get(this.services.config.streamsUri,t,!1));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"_createStream",value:(c=vT.default(_T.default.mark((function e(t,n){var r,i;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r={unique_name:t},void 0!==n&&(r.ttl=n),e.next=4,this.services.network.post(this.services.config.streamsUri,r);case 4:return i=e.sent,e.abrupt("return",i.body);case 6:case"end":return e.stop()}}),e,this)}))),function(e,t){return c.apply(this,arguments)})},{key:"_getLiveQuery",value:function(e){return this.readRootFromSessionCache(rC.type,e)}},{key:"getCached",value:function(e,t){return e&&this.entities.get(e,t)||null}},{key:"removeFromCacheAndSession",value:function(e,t,n){this.entities.remove(t),this.services.config.sessionStorageEnabled&&this.services.storage.remove(e,t,n)}},{key:"document",value:(u=vT.default(_T.default.mark((function e(t){var n,r,i,a,s=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ensureReady();case 2:if("create_new"!==(n=lC(t)).mode){e.next=9;break}return e.next=6,this._createDocument(n.id,n.data,n.ttl);case 6:case 17:case 29:r=e.sent,e.next=39;break;case 9:if(!(i=this.getCached(n.id,OR.type))){e.next=14;break}return e.abrupt("return",new OR(i));case 14:return e.prev=14,e.next=17,this._getDocument(n.id);case 20:if(e.prev=20,e.t0=e.catch(14),404===e.t0.status&&"open_existing"!==n.mode){e.next=26;break}throw e.t0;case 26:return e.prev=26,e.next=29,this._createDocument(n.id,n.data,n.ttl);case 32:if(e.prev=32,e.t1=e.catch(26),409!==e.t1.status){e.next=38;break}return e.abrupt("return",this.document(t));case 38:throw e.t1;case 39:return this.storeRootInSessionCache(OR.type,n.id,r),a=new IR(this.services,r,(function(e,t,n){return s.removeFromCacheAndSession(e,t,n)})),a=this.entities.store(a),e.abrupt("return",new OR(a));case 43:case"end":return e.stop()}}),e,this,[[14,20],[26,32]])}))),function(e){return u.apply(this,arguments)})},{key:"map",value:(o=vT.default(_T.default.mark((function e(t){var n,r,i,a,s=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ensureReady();case 2:if("create_new"!==(n=lC(t)).mode){e.next=9;break}return e.next=6,this._createMap(n.id,n.ttl);case 6:case 17:case 29:r=e.sent,e.next=39;break;case 9:if(!(i=this.getCached(n.id,JR.type))){e.next=14;break}return e.abrupt("return",new JR(i));case 14:return e.prev=14,e.next=17,this._getMap(n.id,n.includeItems);case 20:if(e.prev=20,e.t0=e.catch(14),404===e.t0.status&&"open_existing"!==n.mode){e.next=26;break}throw e.t0;case 26:return e.prev=26,e.next=29,this._createMap(n.id,n.ttl);case 32:if(e.prev=32,e.t1=e.catch(26),409!==e.t1.status){e.next=38;break}return e.abrupt("return",this.map(t));case 38:throw e.t1;case 39:return this.storeRootInSessionCache(JR.type,n.id,r),a=new VR(this.services,r,(function(e,t,n){return s.removeFromCacheAndSession(e,t,n)})),a=this.entities.store(a),e.abrupt("return",new JR(a));case 43:case"end":return e.stop()}}),e,this,[[14,20],[26,32]])}))),function(e){return o.apply(this,arguments)})},{key:"list",value:(s=vT.default(_T.default.mark((function e(t){var n,r,i,a,s=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ensureReady();case 2:if("create_new"!==(n=lC(t)).mode){e.next=9;break}return e.next=6,this._createList(n.id,n.purpose,n.context,n.ttl);case 6:case 17:case 29:r=e.sent,e.next=39;break;case 9:if(!(i=this.getCached(n.id,WR.type))){e.next=14;break}return e.abrupt("return",new WR(i));case 14:return e.prev=14,e.next=17,this._getList(n.id);case 20:if(e.prev=20,e.t0=e.catch(14),404===e.t0.status&&"open_existing"!==n.mode){e.next=26;break}throw e.t0;case 26:return e.prev=26,e.next=29,this._createList(n.id,n.purpose,n.context,n.ttl);case 32:if(e.prev=32,e.t1=e.catch(26),409!==e.t1.status){e.next=38;break}return e.abrupt("return",this.list(t));case 38:throw e.t1;case 39:return this.storeRootInSessionCache(WR.type,n.id,r),a=new zR(this.services,r,(function(e,t,n){return s.removeFromCacheAndSession(e,t,n)})),a=this.entities.store(a),e.abrupt("return",new WR(a));case 43:case"end":return e.stop()}}),e,this,[[14,20],[26,32]])}))),function(e){return s.apply(this,arguments)})},{key:"stream",value:(a=vT.default(_T.default.mark((function e(t){var n,r,i,a,s,o=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ensureReady();case 2:if("create_new"!==(n=lC(t)).mode){e.next=9;break}return e.next=6,this._createStream(n.id,n.ttl);case 6:case 17:case 29:r=e.sent,e.next=39;break;case 9:if(!(i=this.getCached(n.id,YR.type))){e.next=14;break}return e.abrupt("return",new YR(i));case 14:return e.prev=14,e.next=17,this._getStream(n.id);case 20:if(e.prev=20,e.t0=e.catch(14),404===e.t0.status&&"open_existing"!==n.mode){e.next=26;break}throw e.t0;case 26:return e.prev=26,e.next=29,this._createStream(n.id,n.ttl);case 32:if(e.prev=32,e.t1=e.catch(26),409!==e.t1.status){e.next=38;break}return e.abrupt("return",this.stream(t));case 38:throw e.t1;case 39:return this.storeRootInSessionCache(YR.type,n.id,r),a=function(e,t,n){return o.removeFromCacheAndSession(e,t,n)},s=new HR(this.services,r,a),s=this.entities.store(s),e.abrupt("return",new YR(s));case 44:case"end":return e.stop()}}),e,this,[[14,20],[26,32]])}))),function(e){return a.apply(this,arguments)})},{key:"shutdown",value:(i=vT.default(_T.default.mark((function e(){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.subscriptions.shutdown();case 2:return e.next=4,this.services.twilsock.disconnect();case 4:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"updateToken",value:(r=vT.default(_T.default.mark((function e(t){return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.services.twilsock.updateToken(t).catch((function(e){var t,n=null==e||null===(t=e.reply)||void 0===t?void 0:t.status;if(401===(null==n?void 0:n.code)&&"UNAUTHORIZED"===(null==n?void 0:n.status))throw new SyncError("Updated token was rejected by server",400,51130);throw e})));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"liveQuery",value:(n=vT.default(_T.default.mark((function e(t,n){var r,i,a,s,o,u=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ensureReady();case 2:return r=new $T(this.services.config.insightsUri).pathSegment(t).pathSegment("Items").build(),e.next=5,tC({network:this.services.network,uri:r,queryString:n,type:rC.type});case 5:return i=e.sent,(a=this.getCached(i.query_id,rC.type))||((s=this._getLiveQuery(i.query_id))||(s={indexName:t,queryExpression:n,sid:i.query_id,queryUri:r,last_event_id:i.last_event_id}),o=function(e,t,n){return u.removeFromCacheAndSession(e,t,n)},a=new eC(s,this.services,o,i.items)),this.storeRootInSessionCache(rC.type,i.query_id,a.liveQueryDescriptor),a=this.entities.store(a),e.abrupt("return",new rC(a));case 11:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"instantQuery",value:(t=vT.default(_T.default.mark((function e(t){var n,r=this;return _T.default.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.ensureReady();case 2:return n=function(e,t){return r.liveQuery(e,t)},e.abrupt("return",new iC({indexName:t,network:this.services.network,insightsUri:this.services.config.insightsUri,liveQueryCreator:n}));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}],[{key:"populateInitRegistrations",value:function(e){e.populateInitRegistrations([hC,fC,dC,pC])}},{key:"version",get:function(){return cC}}]),Client}(MT);xT.default(Client,"connectionStateChanged","connectionStateChanged"),xT.default(Client,"connectionError","connectionError"),xT.default(Client,"tokenAboutToExpire","tokenAboutToExpire"),xT.default(Client,"tokenExpired","tokenExpired"),PT([iT.validateTypesAsync(["undefined","string",iT.objectSchema("open document options",{id:["string","undefined"],mode:[iT.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[iT.nonNegativeInteger,"undefined"],data:[iT.pureObject,"undefined",iT.literal(null)]})]),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],Client.prototype,"document",null),PT([iT.validateTypesAsync(["undefined","string",iT.objectSchema("open map options",{id:["string","undefined"],mode:[iT.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[iT.nonNegativeInteger,"undefined"],data:[iT.pureObject,"undefined",iT.literal(null)],includeItems:["boolean","undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],Client.prototype,"map",null),PT([iT.validateTypesAsync(["undefined","string",iT.objectSchema("open list options",{id:["string","undefined"],mode:[iT.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[iT.nonNegativeInteger,"undefined"],data:[iT.pureObject,"undefined",iT.literal(null)],purpose:["string","undefined"],context:[iT.pureObject,"undefined"],includeItems:["boolean","undefined"]})]),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],Client.prototype,"list",null),PT([iT.validateTypesAsync(["undefined","string",iT.objectSchema("open stream options",{id:["string","undefined"],mode:[iT.literal("open_or_create","open_existing","create_new"),"undefined"],ttl:[iT.nonNegativeInteger,"undefined"],data:[iT.pureObject,"undefined",iT.literal(null)]})]),AT("design:type",Function),AT("design:paramtypes",[Object]),AT("design:returntype",Promise)],Client.prototype,"stream",null),PT([iT.validateTypesAsync(iT.nonEmptyString),AT("design:type",Function),AT("design:paramtypes",[String]),AT("design:returntype",Promise)],Client.prototype,"updateToken",null),PT([iT.validateTypesAsync(iT.nonEmptyString,"string"),AT("design:type",Function),AT("design:paramtypes",[String,String]),AT("design:returntype",Promise)],Client.prototype,"liveQuery",null),PT([iT.validateTypesAsync(iT.nonEmptyString),AT("design:type",Function),AT("design:paramtypes",[String]),AT("design:returntype",Promise)],Client.prototype,"instantQuery",null),JE.Client=Client,JE.InsightsItem=function e(){yT.default(this,e)},JE.InstantQuery=iC,JE.LiveQuery=rC,JE.Paginator=Paginator;var vC=JE.SyncClient=Client;JE.SyncDocument=OR,JE.SyncList=WR,JE.SyncListItem=PR,JE.SyncMap=JR,JE.SyncMapItem=GR,JE.SyncStream=YR;var yC,mC={},gC=WS,bC=function(e){if(gC(e))throw TypeError("The method doesn't accept regular expressions");return e},wC=he("match"),kC=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[wC]=!1,"/./"[e](t)}catch(e){}}return!1},xC=Cn,_C=s.f,SC=Dt,EC=Er,TC=bC,RC=k,CC=kC,IC="".startsWith,OC=Math.min,PC=CC("startsWith");xC({target:"String",proto:!0,forced:!!(PC||(yC=_C(String.prototype,"startsWith"),!yC||yC.writable))&&!PC},{startsWith:function(e){var t=EC(RC(this));TC(e);var n=SC(OC(arguments.length>1?arguments[1]:void 0,t.length)),r=EC(e);return IC?IC.call(t,r,n):t.slice(n,n+r.length)===r}});var AC=o,jC=he("iterator"),MC=!AC((function(){var e=new URL("b?a=1&b=2&c=3","http://a"),t=e.searchParams,n="";return e.pathname="c%20d",t.forEach((function(e,r){t.delete("b"),n+=r+e})),!t.sort||"http://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[jC]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("http://тест").host||"#%D0%B1"!==new URL("http://a#б").hash||"a1c3"!==n||"x"!==new URL("http://x",void 0).host})),LC=2147483647,NC=/[^\0-\u007E]/,UC=/[.\u3002\uFF0E\uFF61]/g,DC="Overflow: input needs wider integers to process",FC=Math.floor,BC=String.fromCharCode,qC=function(e){return e+22+75*(e<26)},zC=function(e,t,n){var r=0;for(e=n?FC(e/700):e>>1,e+=FC(e/t);e>455;r+=36)e=FC(e/35);return FC(r+36*e/(e+38))},WC=function(e){var t=[];e=function(e){for(var t=[],n=0,r=e.length;n<r;){var i=e.charCodeAt(n++);if(i>=55296&&i<=56319&&n<r){var a=e.charCodeAt(n++);56320==(64512&a)?t.push(((1023&i)<<10)+(1023&a)+65536):(t.push(i),n--)}else t.push(i)}return t}(e);var n,r,i=e.length,a=128,s=0,o=72;for(n=0;n<e.length;n++)(r=e[n])<128&&t.push(BC(r));var u=t.length,c=u;for(u&&t.push("-");c<i;){var l=LC;for(n=0;n<e.length;n++)(r=e[n])>=a&&r<l&&(l=r);var f=c+1;if(l-a>FC((LC-s)/f))throw RangeError(DC);for(s+=(l-a)*f,a=l,n=0;n<e.length;n++){if((r=e[n])<a&&++s>LC)throw RangeError(DC);if(r==a){for(var d=s,p=36;;p+=36){var h=p<=o?1:p>=o+26?26:p-o;if(d<h)break;var v=d-h,y=36-h;t.push(BC(qC(h+v%y))),d=FC(v/y)}t.push(BC(qC(d))),o=zC(s,f,c==u),s=0,++c}}++s,++a}return t.join("")},GC=Cn,$C=C,VC=MC,JC=Ke.exports,KC=Xa,HC=An,YC=Yl,QC=_t,XC=us,ZC=te,eI=Fr,tI=Ga,nI=Fe,rI=E,iI=Er,aI=nr,sI=v,oI=ws,uI=ms,cI=he,lI=$C("fetch"),fI=$C("Request"),dI=fI&&fI.prototype,pI=$C("Headers"),hI=cI("iterator"),vI="URLSearchParams",yI="URLSearchParamsIterator",mI=QC.set,gI=QC.getterFor(vI),bI=QC.getterFor(yI),wI=/\+/g,kI=Array(4),xI=function(e){return kI[e-1]||(kI[e-1]=RegExp("((?:%[\\da-f]{2}){"+e+"})","gi"))},_I=function(e){try{return decodeURIComponent(e)}catch(t){return e}},SI=function(e){var t=e.replace(wI," "),n=4;try{return decodeURIComponent(t)}catch(e){for(;n;)t=t.replace(xI(n--),_I);return t}},EI=/[!'()~]|%20/g,TI={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},RI=function(e){return TI[e]},CI=function(e){return encodeURIComponent(e).replace(EI,RI)},II=function(e,t){if(t)for(var n,r,i=t.split("&"),a=0;a<i.length;)(n=i[a++]).length&&(r=n.split("="),e.push({key:SI(r.shift()),value:SI(r.join("="))}))},OI=function(e){this.entries.length=0,II(this.entries,e)},PI=function(e,t){if(e<t)throw TypeError("Not enough arguments")},AI=YC((function(e,t){mI(this,{type:yI,iterator:oI(gI(e).entries),kind:t})}),"Iterator",(function(){var e=bI(this),t=e.kind,n=e.iterator.next(),r=n.value;return n.done||(n.value="keys"===t?r.key:"values"===t?r.value:[r.key,r.value]),n})),jI=function(){XC(this,jI,vI);var e,t,n,r,i,a,s,o,u,c=arguments.length>0?arguments[0]:void 0,l=this,f=[];if(mI(l,{type:vI,entries:f,updateURL:function(){},updateSearchParams:OI}),void 0!==c)if(rI(c))if("function"==typeof(e=uI(c)))for(n=(t=oI(c,e)).next;!(r=n.call(t)).done;){if((s=(a=(i=oI(nI(r.value))).next).call(i)).done||(o=a.call(i)).done||!a.call(i).done)throw TypeError("Expected sequence with length 2");f.push({key:iI(s.value),value:iI(o.value)})}else for(u in c)ZC(c,u)&&f.push({key:u,value:iI(c[u])});else II(f,"string"==typeof c?"?"===c.charAt(0)?c.slice(1):c:iI(c))},MI=jI.prototype;if(KC(MI,{append:function(e,t){PI(arguments.length,2);var n=gI(this);n.entries.push({key:iI(e),value:iI(t)}),n.updateURL()},delete:function(e){PI(arguments.length,1);for(var t=gI(this),n=t.entries,r=iI(e),i=0;i<n.length;)n[i].key===r?n.splice(i,1):i++;t.updateURL()},get:function(e){PI(arguments.length,1);for(var t=gI(this).entries,n=iI(e),r=0;r<t.length;r++)if(t[r].key===n)return t[r].value;return null},getAll:function(e){PI(arguments.length,1);for(var t=gI(this).entries,n=iI(e),r=[],i=0;i<t.length;i++)t[i].key===n&&r.push(t[i].value);return r},has:function(e){PI(arguments.length,1);for(var t=gI(this).entries,n=iI(e),r=0;r<t.length;)if(t[r++].key===n)return!0;return!1},set:function(e,t){PI(arguments.length,1);for(var n,r=gI(this),i=r.entries,a=!1,s=iI(e),o=iI(t),u=0;u<i.length;u++)(n=i[u]).key===s&&(a?i.splice(u--,1):(a=!0,n.value=o));a||i.push({key:s,value:o}),r.updateURL()},sort:function(){var e,t,n,r=gI(this),i=r.entries,a=i.slice();for(i.length=0,n=0;n<a.length;n++){for(e=a[n],t=0;t<n;t++)if(i[t].key>e.key){i.splice(t,0,e);break}t===n&&i.push(e)}r.updateURL()},forEach:function(e){for(var t,n=gI(this).entries,r=eI(e,arguments.length>1?arguments[1]:void 0,3),i=0;i<n.length;)r((t=n[i++]).value,t.key,this)},keys:function(){return new AI(this,"keys")},values:function(){return new AI(this,"values")},entries:function(){return new AI(this,"entries")}},{enumerable:!0}),JC(MI,hI,MI.entries),JC(MI,"toString",(function(){for(var e,t=gI(this).entries,n=[],r=0;r<t.length;)e=t[r++],n.push(CI(e.key)+"="+CI(e.value));return n.join("&")}),{enumerable:!0}),HC(jI,vI),GC({global:!0,forced:!VC},{URLSearchParams:jI}),!VC&&"function"==typeof pI){var LI=function(e){if(rI(e)){var t,n=e.body;if(tI(n)===vI)return(t=e.headers?new pI(e.headers):new pI).has("content-type")||t.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),aI(e,{body:sI(0,String(n)),headers:sI(0,t)})}return e};if("function"==typeof lI&&GC({global:!0,enumerable:!0,forced:!0},{fetch:function(e){return lI(e,arguments.length>1?LI(arguments[1]):{})}}),"function"==typeof fI){var NI=function(e){return XC(this,NI,"Request"),new fI(e,arguments.length>1?LI(arguments[1]):{})};dI.constructor=NI,NI.prototype=dI,GC({global:!0,forced:!0},{Request:NI})}}var UI,DI={URLSearchParams:jI,getState:gI},FI=Cn,BI=u,qI=MC,zI=a,WI=Wn,GI=Ke.exports,$I=us,VI=te,JI=$E,KI=wl,HI=Il.codeAt,YI=function(e){var t,n,r=[],i=e.toLowerCase().replace(UC,".").split(".");for(t=0;t<i.length;t++)n=i[t],r.push(NC.test(n)?"xn--"+WC(n):n);return r.join(".")},QI=Er,XI=An,ZI=DI,eO=_t,tO=zI.URL,nO=ZI.URLSearchParams,rO=ZI.getState,iO=eO.set,aO=eO.getterFor("URL"),sO=Math.floor,oO=Math.pow,uO="Invalid scheme",cO="Invalid host",lO="Invalid port",fO=/[A-Za-z]/,dO=/[\d+-.A-Za-z]/,pO=/\d/,hO=/^0x/i,vO=/^[0-7]+$/,yO=/^\d+$/,mO=/^[\dA-Fa-f]+$/,gO=/[\0\t\n\r #%/:<>?@[\\\]^|]/,bO=/[\0\t\n\r #/:<>?@[\\\]^|]/,wO=/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g,kO=/[\t\n\r]/g,xO=function(e,t){var n,r,i;if("["==t.charAt(0)){if("]"!=t.charAt(t.length-1))return cO;if(!(n=SO(t.slice(1,-1))))return cO;e.host=n}else if(AO(e)){if(t=YI(t),gO.test(t))return cO;if(null===(n=_O(t)))return cO;e.host=n}else{if(bO.test(t))return cO;for(n="",r=KI(t),i=0;i<r.length;i++)n+=OO(r[i],TO);e.host=n}},_O=function(e){var t,n,r,i,a,s,o,u=e.split(".");if(u.length&&""==u[u.length-1]&&u.pop(),(t=u.length)>4)return e;for(n=[],r=0;r<t;r++){if(""==(i=u[r]))return e;if(a=10,i.length>1&&"0"==i.charAt(0)&&(a=hO.test(i)?16:8,i=i.slice(8==a?1:2)),""===i)s=0;else{if(!(10==a?yO:8==a?vO:mO).test(i))return e;s=parseInt(i,a)}n.push(s)}for(r=0;r<t;r++)if(s=n[r],r==t-1){if(s>=oO(256,5-t))return null}else if(s>255)return null;for(o=n.pop(),r=0;r<n.length;r++)o+=n[r]*oO(256,3-r);return o},SO=function(e){var t,n,r,i,a,s,o,u=[0,0,0,0,0,0,0,0],c=0,l=null,f=0,d=function(){return e.charAt(f)};if(":"==d()){if(":"!=e.charAt(1))return;f+=2,l=++c}for(;d();){if(8==c)return;if(":"!=d()){for(t=n=0;n<4&&mO.test(d());)t=16*t+parseInt(d(),16),f++,n++;if("."==d()){if(0==n)return;if(f-=n,c>6)return;for(r=0;d();){if(i=null,r>0){if(!("."==d()&&r<4))return;f++}if(!pO.test(d()))return;for(;pO.test(d());){if(a=parseInt(d(),10),null===i)i=a;else{if(0==i)return;i=10*i+a}if(i>255)return;f++}u[c]=256*u[c]+i,2!=++r&&4!=r||c++}if(4!=r)return;break}if(":"==d()){if(f++,!d())return}else if(d())return;u[c++]=t}else{if(null!==l)return;f++,l=++c}}if(null!==l)for(s=c-l,c=7;0!=c&&s>0;)o=u[c],u[c--]=u[l+s-1],u[l+--s]=o;else if(8!=c)return;return u},EO=function(e){var t,n,r,i;if("number"==typeof e){for(t=[],n=0;n<4;n++)t.unshift(e%256),e=sO(e/256);return t.join(".")}if("object"==typeof e){for(t="",r=function(e){for(var t=null,n=1,r=null,i=0,a=0;a<8;a++)0!==e[a]?(i>n&&(t=r,n=i),r=null,i=0):(null===r&&(r=a),++i);return i>n&&(t=r,n=i),t}(e),n=0;n<8;n++)i&&0===e[n]||(i&&(i=!1),r===n?(t+=n?":":"::",i=!0):(t+=e[n].toString(16),n<7&&(t+=":")));return"["+t+"]"}return e},TO={},RO=JI({},TO,{" ":1,'"':1,"<":1,">":1,"`":1}),CO=JI({},RO,{"#":1,"?":1,"{":1,"}":1}),IO=JI({},CO,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),OO=function(e,t){var n=HI(e,0);return n>32&&n<127&&!VI(t,e)?e:encodeURIComponent(e)},PO={ftp:21,file:null,http:80,https:443,ws:80,wss:443},AO=function(e){return VI(PO,e.scheme)},jO=function(e){return""!=e.username||""!=e.password},MO=function(e){return!e.host||e.cannotBeABaseURL||"file"==e.scheme},LO=function(e,t){var n;return 2==e.length&&fO.test(e.charAt(0))&&(":"==(n=e.charAt(1))||!t&&"|"==n)},NO=function(e){var t;return e.length>1&&LO(e.slice(0,2))&&(2==e.length||"/"===(t=e.charAt(2))||"\\"===t||"?"===t||"#"===t)},UO=function(e){var t=e.path,n=t.length;!n||"file"==e.scheme&&1==n&&LO(t[0],!0)||t.pop()},DO=function(e){return"."===e||"%2e"===e.toLowerCase()},FO={},BO={},qO={},zO={},WO={},GO={},$O={},VO={},JO={},KO={},HO={},YO={},QO={},XO={},ZO={},eP={},tP={},nP={},rP={},iP={},aP={},sP=function(e,t,n,r){var i,a,s,o,u,c=n||FO,l=0,f="",d=!1,p=!1,h=!1;for(n||(e.scheme="",e.username="",e.password="",e.host=null,e.port=null,e.path=[],e.query=null,e.fragment=null,e.cannotBeABaseURL=!1,t=t.replace(wO,"")),t=t.replace(kO,""),i=KI(t);l<=i.length;){switch(a=i[l],c){case FO:if(!a||!fO.test(a)){if(n)return uO;c=qO;continue}f+=a.toLowerCase(),c=BO;break;case BO:if(a&&(dO.test(a)||"+"==a||"-"==a||"."==a))f+=a.toLowerCase();else{if(":"!=a){if(n)return uO;f="",c=qO,l=0;continue}if(n&&(AO(e)!=VI(PO,f)||"file"==f&&(jO(e)||null!==e.port)||"file"==e.scheme&&!e.host))return;if(e.scheme=f,n)return void(AO(e)&&PO[e.scheme]==e.port&&(e.port=null));f="","file"==e.scheme?c=XO:AO(e)&&r&&r.scheme==e.scheme?c=zO:AO(e)?c=VO:"/"==i[l+1]?(c=WO,l++):(e.cannotBeABaseURL=!0,e.path.push(""),c=rP)}break;case qO:if(!r||r.cannotBeABaseURL&&"#"!=a)return uO;if(r.cannotBeABaseURL&&"#"==a){e.scheme=r.scheme,e.path=r.path.slice(),e.query=r.query,e.fragment="",e.cannotBeABaseURL=!0,c=aP;break}c="file"==r.scheme?XO:GO;continue;case zO:if("/"!=a||"/"!=i[l+1]){c=GO;continue}c=JO,l++;break;case WO:if("/"==a){c=KO;break}c=nP;continue;case GO:if(e.scheme=r.scheme,a==UI)e.username=r.username,e.password=r.password,e.host=r.host,e.port=r.port,e.path=r.path.slice(),e.query=r.query;else if("/"==a||"\\"==a&&AO(e))c=$O;else if("?"==a)e.username=r.username,e.password=r.password,e.host=r.host,e.port=r.port,e.path=r.path.slice(),e.query="",c=iP;else{if("#"!=a){e.username=r.username,e.password=r.password,e.host=r.host,e.port=r.port,e.path=r.path.slice(),e.path.pop(),c=nP;continue}e.username=r.username,e.password=r.password,e.host=r.host,e.port=r.port,e.path=r.path.slice(),e.query=r.query,e.fragment="",c=aP}break;case $O:if(!AO(e)||"/"!=a&&"\\"!=a){if("/"!=a){e.username=r.username,e.password=r.password,e.host=r.host,e.port=r.port,c=nP;continue}c=KO}else c=JO;break;case VO:if(c=JO,"/"!=a||"/"!=f.charAt(l+1))continue;l++;break;case JO:if("/"!=a&&"\\"!=a){c=KO;continue}break;case KO:if("@"==a){d&&(f="%40"+f),d=!0,s=KI(f);for(var v=0;v<s.length;v++){var y=s[v];if(":"!=y||h){var m=OO(y,IO);h?e.password+=m:e.username+=m}else h=!0}f=""}else if(a==UI||"/"==a||"?"==a||"#"==a||"\\"==a&&AO(e)){if(d&&""==f)return"Invalid authority";l-=KI(f).length+1,f="",c=HO}else f+=a;break;case HO:case YO:if(n&&"file"==e.scheme){c=eP;continue}if(":"!=a||p){if(a==UI||"/"==a||"?"==a||"#"==a||"\\"==a&&AO(e)){if(AO(e)&&""==f)return cO;if(n&&""==f&&(jO(e)||null!==e.port))return;if(o=xO(e,f))return o;if(f="",c=tP,n)return;continue}"["==a?p=!0:"]"==a&&(p=!1),f+=a}else{if(""==f)return cO;if(o=xO(e,f))return o;if(f="",c=QO,n==YO)return}break;case QO:if(!pO.test(a)){if(a==UI||"/"==a||"?"==a||"#"==a||"\\"==a&&AO(e)||n){if(""!=f){var g=parseInt(f,10);if(g>65535)return lO;e.port=AO(e)&&g===PO[e.scheme]?null:g,f=""}if(n)return;c=tP;continue}return lO}f+=a;break;case XO:if(e.scheme="file","/"==a||"\\"==a)c=ZO;else{if(!r||"file"!=r.scheme){c=nP;continue}if(a==UI)e.host=r.host,e.path=r.path.slice(),e.query=r.query;else if("?"==a)e.host=r.host,e.path=r.path.slice(),e.query="",c=iP;else{if("#"!=a){NO(i.slice(l).join(""))||(e.host=r.host,e.path=r.path.slice(),UO(e)),c=nP;continue}e.host=r.host,e.path=r.path.slice(),e.query=r.query,e.fragment="",c=aP}}break;case ZO:if("/"==a||"\\"==a){c=eP;break}r&&"file"==r.scheme&&!NO(i.slice(l).join(""))&&(LO(r.path[0],!0)?e.path.push(r.path[0]):e.host=r.host),c=nP;continue;case eP:if(a==UI||"/"==a||"\\"==a||"?"==a||"#"==a){if(!n&&LO(f))c=nP;else if(""==f){if(e.host="",n)return;c=tP}else{if(o=xO(e,f))return o;if("localhost"==e.host&&(e.host=""),n)return;f="",c=tP}continue}f+=a;break;case tP:if(AO(e)){if(c=nP,"/"!=a&&"\\"!=a)continue}else if(n||"?"!=a)if(n||"#"!=a){if(a!=UI&&(c=nP,"/"!=a))continue}else e.fragment="",c=aP;else e.query="",c=iP;break;case nP:if(a==UI||"/"==a||"\\"==a&&AO(e)||!n&&("?"==a||"#"==a)){if(".."===(u=(u=f).toLowerCase())||"%2e."===u||".%2e"===u||"%2e%2e"===u?(UO(e),"/"==a||"\\"==a&&AO(e)||e.path.push("")):DO(f)?"/"==a||"\\"==a&&AO(e)||e.path.push(""):("file"==e.scheme&&!e.path.length&&LO(f)&&(e.host&&(e.host=""),f=f.charAt(0)+":"),e.path.push(f)),f="","file"==e.scheme&&(a==UI||"?"==a||"#"==a))for(;e.path.length>1&&""===e.path[0];)e.path.shift();"?"==a?(e.query="",c=iP):"#"==a&&(e.fragment="",c=aP)}else f+=OO(a,CO);break;case rP:"?"==a?(e.query="",c=iP):"#"==a?(e.fragment="",c=aP):a!=UI&&(e.path[0]+=OO(a,TO));break;case iP:n||"#"!=a?a!=UI&&("'"==a&&AO(e)?e.query+="%27":e.query+="#"==a?"%23":OO(a,TO)):(e.fragment="",c=aP);break;case aP:a!=UI&&(e.fragment+=OO(a,RO))}l++}},oP=function(e){var t,n,r=$I(this,oP,"URL"),i=arguments.length>1?arguments[1]:void 0,a=QI(e),s=iO(r,{type:"URL"});if(void 0!==i)if(i instanceof oP)t=aO(i);else if(n=sP(t={},QI(i)))throw TypeError(n);if(n=sP(s,a,null,t))throw TypeError(n);var o=s.searchParams=new nO,u=rO(o);u.updateSearchParams(s.query),u.updateURL=function(){s.query=String(o)||null},BI||(r.href=cP.call(r),r.origin=lP.call(r),r.protocol=fP.call(r),r.username=dP.call(r),r.password=pP.call(r),r.host=hP.call(r),r.hostname=vP.call(r),r.port=yP.call(r),r.pathname=mP.call(r),r.search=gP.call(r),r.searchParams=bP.call(r),r.hash=wP.call(r))},uP=oP.prototype,cP=function(){var e=aO(this),t=e.scheme,n=e.username,r=e.password,i=e.host,a=e.port,s=e.path,o=e.query,u=e.fragment,c=t+":";return null!==i?(c+="//",jO(e)&&(c+=n+(r?":"+r:"")+"@"),c+=EO(i),null!==a&&(c+=":"+a)):"file"==t&&(c+="//"),c+=e.cannotBeABaseURL?s[0]:s.length?"/"+s.join("/"):"",null!==o&&(c+="?"+o),null!==u&&(c+="#"+u),c},lP=function(){var e=aO(this),t=e.scheme,n=e.port;if("blob"==t)try{return new oP(t.path[0]).origin}catch(e){return"null"}return"file"!=t&&AO(e)?t+"://"+EO(e.host)+(null!==n?":"+n:""):"null"},fP=function(){return aO(this).scheme+":"},dP=function(){return aO(this).username},pP=function(){return aO(this).password},hP=function(){var e=aO(this),t=e.host,n=e.port;return null===t?"":null===n?EO(t):EO(t)+":"+n},vP=function(){var e=aO(this).host;return null===e?"":EO(e)},yP=function(){var e=aO(this).port;return null===e?"":String(e)},mP=function(){var e=aO(this),t=e.path;return e.cannotBeABaseURL?t[0]:t.length?"/"+t.join("/"):""},gP=function(){var e=aO(this).query;return e?"?"+e:""},bP=function(){return aO(this).searchParams},wP=function(){var e=aO(this).fragment;return e?"#"+e:""},kP=function(e,t){return{get:e,set:t,configurable:!0,enumerable:!0}};if(BI&&WI(uP,{href:kP(cP,(function(e){var t=aO(this),n=QI(e),r=sP(t,n);if(r)throw TypeError(r);rO(t.searchParams).updateSearchParams(t.query)})),origin:kP(lP),protocol:kP(fP,(function(e){var t=aO(this);sP(t,QI(e)+":",FO)})),username:kP(dP,(function(e){var t=aO(this),n=KI(QI(e));if(!MO(t)){t.username="";for(var r=0;r<n.length;r++)t.username+=OO(n[r],IO)}})),password:kP(pP,(function(e){var t=aO(this),n=KI(QI(e));if(!MO(t)){t.password="";for(var r=0;r<n.length;r++)t.password+=OO(n[r],IO)}})),host:kP(hP,(function(e){var t=aO(this);t.cannotBeABaseURL||sP(t,QI(e),HO)})),hostname:kP(vP,(function(e){var t=aO(this);t.cannotBeABaseURL||sP(t,QI(e),YO)})),port:kP(yP,(function(e){var t=aO(this);MO(t)||(""==(e=QI(e))?t.port=null:sP(t,e,QO))})),pathname:kP(mP,(function(e){var t=aO(this);t.cannotBeABaseURL||(t.path=[],sP(t,QI(e),tP))})),search:kP(gP,(function(e){var t=aO(this);""==(e=QI(e))?t.query=null:("?"==e.charAt(0)&&(e=e.slice(1)),t.query="",sP(t,e,iP)),rO(t.searchParams).updateSearchParams(t.query)})),searchParams:kP(bP),hash:kP(wP,(function(e){var t=aO(this);""!=(e=QI(e))?("#"==e.charAt(0)&&(e=e.slice(1)),t.fragment="",sP(t,e,aP)):t.fragment=null}))}),GI(uP,"toJSON",(function(){return cP.call(this)}),{enumerable:!0}),GI(uP,"toString",(function(){return cP.call(this)}),{enumerable:!0}),tO){var xP=tO.createObjectURL,_P=tO.revokeObjectURL;xP&&GI(oP,"createObjectURL",(function(e){return xP.apply(tO,arguments)})),_P&&GI(oP,"revokeObjectURL",(function(e){return _P.apply(tO,arguments)}))}XI(oP,"URL"),FI({global:!0,forced:!qI,sham:!BI},{URL:oP}),function(e){var t=void 0!==t?t:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};Object.defineProperty(e,"__esModule",{value:!0});var n=pv.exports,r=dv.exports,i=hv.exports,a=yv.exports,s=gv.exports,o=sE.exports,u=jy.exports,c=Vg.exports,l=Jg,f=Hh.exports,d=Sf.exports,p=sg,h=gh;function v(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}function y(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach((function(n){if("default"!==n){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return e[n]}})}})),t.default=e,Object.freeze(t)}var m=v(n),g=v(r),b=v(i),w=v(a),k=v(s),x=v(o),_=v(u),S=v(c),E=v(l),T=v(f),R=y(d),C={exports:{}},I="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);if(I){var O=new Uint8Array(16);C.exports=function(){return I(O),O}}else{var P=new Array(16);C.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),P[t]=e>>>((3&t)<<3)&255;return P}}for(var A=[],j=0;j<256;++j)A[j]=(j+256).toString(16).substr(1);var M,L,N=function(e,t){var n=t||0,r=A;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++]]].join("")},U=C.exports,D=N,F=0,B=0;var q=function(e,t,n){var r=t&&n||0,i=t||[],a=(e=e||{}).node||M,s=void 0!==e.clockseq?e.clockseq:L;if(null==a||null==s){var o=U();null==a&&(a=M=[1|o[0],o[1],o[2],o[3],o[4],o[5]]),null==s&&(s=L=16383&(o[6]<<8|o[7]))}var u=void 0!==e.msecs?e.msecs:(new Date).getTime(),c=void 0!==e.nsecs?e.nsecs:B+1,l=u-F+(c-B)/1e4;if(l<0&&void 0===e.clockseq&&(s=s+1&16383),(l<0||u>F)&&void 0===e.nsecs&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");F=u,B=c,L=s;var f=(1e4*(268435455&(u+=122192928e5))+c)%4294967296;i[r++]=f>>>24&255,i[r++]=f>>>16&255,i[r++]=f>>>8&255,i[r++]=255&f;var d=u/4294967296*1e4&268435455;i[r++]=d>>>8&255,i[r++]=255&d,i[r++]=d>>>24&15|16,i[r++]=d>>>16&255,i[r++]=s>>>8|128,i[r++]=255&s;for(var p=0;p<6;++p)i[r+p]=a[p];return t||D(i)},z=C.exports,W=N;var G=function(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var i=(e=e||{}).random||(e.rng||z)();if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t)for(var a=0;a<16;++a)t[r+a]=i[a];return t||W(i)},$=q,V=G,J=V;J.v1=$,J.v4=V;var K=J;function H(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=k.default(e);if(t){var i=k.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return w.default(this,n)}}var Y=function(e){b.default(n,e);var t=H(n);function n(e){var r;m.default(this,n);var i,a=K.v4();return(r=t.call(this,(function(t,r){return i=r,e((function(e){n.cancellationMap.delete(a),t(e)}),(function(e){n.cancellationMap.delete(a),r(e)}),(function(e){n.cancellationMap.set(a,e)}))}))).id=a,r.rejectPromise=i,r}return g.default(n,[{key:"cancel",value:function(){var e=n.cancellationMap.get(this.id);return null==e||e(),this.rejectPromise&&(this.catch((function(){})),this.rejectPromise(new Error("Promise was cancelled"))),this}}]),n}(x.default(Promise));function Q(e,t,n,r){var i,a=arguments.length,s=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"===("undefined"==typeof Reflect?"undefined":T.default(Reflect))&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var o=e.length-1;o>=0;o--)(i=e[o])&&(s=(a<3?i(s):a>3?i(t,n,s):i(t,n))||s);return a>3&&s&&Object.defineProperty(t,n,s),s}function X(e,t){if("object"===("undefined"==typeof Reflect?"undefined":T.default(Reflect))&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}function Z(e,t){return["".concat((new Date).toISOString()," MCS Client ").concat(e,":")].concat(Array.from(t))}_.default(Y,"cancellationMap",new Map);var ee=function(){function e(t){m.default(this,e),_.default(this,"prefix",""),this.prefix=null!=t&&t.length>0?t+" ":""}return g.default(e,[{key:"setLevel",value:function(e){R.setLevel(e)}},{key:"trace",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.trace.apply(null,Z(this.prefix+"T",t))}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.debug.apply(null,Z(this.prefix+"D",t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.info.apply(null,Z(this.prefix+"I",t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.warn.apply(null,Z(this.prefix+"W",t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.error.apply(null,Z(this.prefix+"E",t))}}],[{key:"scope",value:function(t){return new e(t)}},{key:"setLevel",value:function(e){R.setLevel(e)}},{key:"trace",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.trace.apply(null,Z("T",t))}},{key:"debug",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.debug.apply(null,Z("D",t))}},{key:"info",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.info.apply(null,Z("I",t))}},{key:"warn",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.warn.apply(null,Z("W",t))}},{key:"error",value:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];R.error.apply(null,Z("E",t))}}]),e}(),te=function(e,t){return"".concat((n=e,n.startsWith("http")?"":function(e){return"https://mcs.".concat(null!=e?e:"us1",".twilio.com")}(t))).concat(e);var n},ne=function(){function e(t,n,r,i){var a,s,o,u,c,l;m.default(this,e);var f=null!==(a=null!==(s=i.MCS)&&void 0!==s?s:i)&&void 0!==a?a:{};this.region=null!==(o=null!==(u=f.region)&&void 0!==u?u:i.region)&&void 0!==o?o:"us1",this.mediaUrl=te(n,this.region),this.mediaSetUrl=r?te(r):"".concat(this.mediaUrl,"Set"),this.token=t,this.retryWhenThrottledOverride=null===(c=f.retryWhenThrottledOverride)||void 0===c||c,this.backoffConfigOverride=null!==(l=f.backoffConfigOverride)&&void 0!==l?l:e.backoffConfigDefault}return g.default(e,[{key:"updateToken",value:function(e){this.token=e}}],[{key:"backoffConfigDefault",get:function(){return{min:1e3,max:4e3,maxAttemptsCount:3}}},{key:"retryWhenThrottledDefault",get:function(){return true}}]),e}(),Media=function(){function Media(e,t,n){m.default(this,Media),this.config=e,this.network=t,this._update(n)}return g.default(Media,[{key:"sid",get:function(){return this.state.sid}},{key:"serviceSid",get:function(){return this.state.serviceSid}},{key:"dateCreated",get:function(){return this.state.dateCreated}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"contentType",get:function(){return this.state.contentType}},{key:"size",get:function(){return this.state.size}},{key:"fileName",get:function(){return this.state.filename}},{key:"filename",get:function(){return this.state.filename}},{key:"category",get:function(){return this.state.category}},{key:"getContentUrl",value:function(){var e=this;return new Y(function(){var t=S.default(E.default.mark((function t(n,r,i){var a,s;return E.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return a=e.network.get("".concat(e.config.mediaUrl,"/").concat(e.sid)),i((function(){return a.cancel()})),t.prev=2,t.next=5,a;case 5:s=t.sent,e._update(s.body),n(e.state.contentDirectUrl),t.next=13;break;case 10:t.prev=10,t.t0=t.catch(2),r(t.t0);case 13:case"end":return t.stop()}}),t,null,[[2,10]])})));return function(e,n,r){return t.apply(this,arguments)}}())}},{key:"_update",value:function(e){var t,n,r,i;this.state={sid:e.sid,serviceSid:e.service_sid,channelSid:e.channel_sid,messageSid:e.message_sid,dateCreated:e.date_created?new Date(e.date_created):null,dateUploadUpdated:e.date_upload_updated?new Date(e.date_upload_updated):null,dateUpdated:e.date_updated?new Date(e.date_updated):null,size:e.size,contentType:e.content_type,author:e.author,url:e.url,contentUrl:e.links.content,contentDirectUrl:null!==(t=e.links.content_direct_temporary)&&void 0!==t?t:null,filename:null!==(n=e.filename)&&void 0!==n?n:null,category:null!==(r=e.category)&&void 0!==r?r:"media",isMultipartUpstream:null!==(i=e.is_multipart_upstream)&&void 0!==i&&i}}}]),Media}();function re(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=k.default(e);if(t){var i=k.default(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return w.default(this,n)}}var ie=function(e){b.default(n,e);var t=re(n);function n(e,r,i,a,s){var o;return m.default(this,n),(o=t.call(this,e)).code=r,o.body=i,o.status=a,o.headers=s,o}return g.default(n)}(x.default(Error)),ae=t.XMLHttpRequest||{};var se,oe=function(){function e(){m.default(this,e)}return g.default(e,[{key:"get",value:function(t,n){return e.request("GET",t,n)}},{key:"post",value:function(t,n,r){return e.request("POST",t,n,r)}}],[{key:"request",value:function(e,t,n,r){return new Y((function(i,a,s){var o=new ae,u=!1;for(var c in s((function(){o.abort(),u=!0})),o.open(e,t,!0),o.onreadystatechange=function(){if(4===o.readyState&&!u){var e,t=(e=o.getAllResponseHeaders())?e.split("\r\n").map((function(e){return e.split(": ")})).filter((function(e){return 2===e.length&&e[1].length>0})).reduce((function(e,t){return e[t[0]]=t[1],e}),{}):{},n=function(e){var t=e.getResponseHeader("Content-Type");if(!t||0!==t.indexOf("application/json")||0===e.responseText.length)return e.responseText;try{return JSON.parse(e.responseText)}catch(t){return e.responseText}}(o);if(200<=o.status&&o.status<300)i({status:o.status,headers:t,body:n});else{var r,s,c=null!==(r=o.statusText)&&void 0!==r?r:"NONE";if("string"==typeof n)if(n&&1===n.split("\n",2).length)s=n;else{var l,f=null===(l=n.replace(/<.*?>/g,"").split(/\r\n/g).filter((function(e){return e.length}))[0])||void 0===l?void 0:l.split(" ");s=(null==f?void 0:f.length)>2?null==f?void 0:f.slice(1).join(" "):""}else s=JSON.stringify(n);var d="".concat(o.status,": [").concat(c,"] ").concat(s);a(new ie(d,o.status,n,c,t))}}},n)o.setRequestHeader(c,n[c]),"Content-Type"===c&&"application/json"===n[c]&&(r=JSON.stringify(r));o.send(r)}))}}]),e}(),ue=ee.scope("Network"),ce=function(){function e(t,n){m.default(this,e),this.config=t,this.transport=n}return g.default(e,[{key:"backoffConfig",value:function(){return Object.assign(ne.backoffConfigDefault,this.config.backoffConfigOverride)}},{key:"retryWhenThrottled",value:function(){var e,t;return null!==(e=null!==(t=this.config.retryWhenThrottledOverride)&&void 0!==t?t:ne.retryWhenThrottledDefault)&&void 0!==e&&e}},{key:"executeWithRetry",value:function(e,t){var n=this;return new Y(function(){var r=S.default(E.default.mark((function r(i,a,s){var o,u;return E.default.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:o=new p.Retrier(n.backoffConfig()),u=[502,503,504],t&&u.push(429),s((function(){o.cancel(),o.removeAllListeners()})),o.on("attempt",S.default(E.default.mark((function t(){var n,r;return E.default.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.prev=0,n=e(),s((function(){n.cancel(),o.cancel(),o.removeAllListeners()})),t.next=5,n;case 5:r=t.sent,o.succeeded(r),t.next=12;break;case 9:t.prev=9,t.t0=t.catch(0),u.indexOf(t.t0.status)>-1||"Twilsock disconnected"===t.t0.message?o.failed(t.t0):(o.removeAllListeners(),o.cancel(),a(t.t0));case 12:case"end":return t.stop()}}),t,null,[[0,9]])})))),o.on("succeeded",(function(e){i(e)})),o.on("cancelled",(function(e){return a(e)})),o.on("failed",(function(e){return a(e)})),o.start();case 9:case"end":return r.stop()}}),r)})));return function(e,t,n){return r.apply(this,arguments)}}())}},{key:"get",value:function(e){var t=this;return new Y(function(){var n=S.default(E.default.mark((function n(r,i,a){var s,o,u;return E.default.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return s={"X-Twilio-Token":t.config.token},o=t.executeWithRetry((function(){return t.transport.get(e,s)}),t.retryWhenThrottled()),ue.trace("sending GET request to ",e," headers ",s),a((function(){return o.cancel()})),n.prev=4,n.next=7,o;case 7:u=n.sent,ue.trace("response",u),r(u),n.next=16;break;case 12:n.prev=12,n.t0=n.catch(4),ue.debug("get() error ".concat(n.t0)),i(n.t0);case 16:case"end":return n.stop()}}),n,null,[[4,12]])})));return function(e,t,r){return n.apply(this,arguments)}}())}},{key:"post",value:function(e,n,r,i,a){var s=this,o={"X-Twilio-Token":this.config.token};"undefined"!=typeof FormData&&r instanceof FormData||!i||Object.assign(o,{"Content-Type":i});var u=new URL(e);return n&&u.searchParams.append("Category",n),a&&u.searchParams.append("Filename",a),new Y(function(){var n=S.default(E.default.mark((function n(i,a,c){var l,f;return E.default.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return l=s.transport.post(u.href,o,r),c((function(){return l.cancel()})),ue.trace("sending POST request to ".concat(e," with headers ").concat(o)),n.prev=3,n.next=6,l;case 6:f=n.sent,n.next=17;break;case 9:if(n.prev=9,n.t0=n.catch(3),!(void 0===t.XMLHttpRequest&&r instanceof FormData)){n.next=14;break}return a(new TypeError("Posting FormData supported only with browser engine's FormData")),n.abrupt("return");case 14:return ue.debug("post() error ".concat(n.t0)),a(n.t0),n.abrupt("return");case 17:ue.trace("response",f),i(f);case 19:case"end":return n.stop()}}),n,null,[[3,9]])})));return function(e,t,r){return n.apply(this,arguments)}}())}}]),e}(),le=ee.scope("");e.default=(se=function(){function Client(e,t,n){var r,i,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};m.default(this,Client),this.options=a,this.options.logLevel=null!==(r=this.options.logLevel)&&void 0!==r?r:"silent",this.config=new ne(e,t,n,this.options),le.setLevel(this.options.logLevel),this.options.transport=null!==(i=this.options.transport)&&void 0!==i?i:new oe,this.transport=this.options.transport,this.network=new ce(this.config,this.transport)}return g.default(Client,[{key:"updateToken",value:function(e){le.info("updateToken"),this.config.updateToken(e)}},{key:"get",value:function(e){var t=this;return new Y(function(){var n=S.default(E.default.mark((function n(r,i,a){var s,o;return E.default.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return s=t.network.get("".concat(t.config.mediaUrl,"/").concat(e)),a((function(){return s.cancel()})),n.prev=2,n.next=5,s;case 5:o=n.sent,r(new Media(t.config,t.network,o.body)),n.next=12;break;case 9:n.prev=9,n.t0=n.catch(2),i(n.t0);case 12:case"end":return n.stop()}}),n,null,[[2,9]])})));return function(e,t,r){return n.apply(this,arguments)}}())}},{key:"post",value:function(e,t,n,r){var i=this;return new Y(function(){var a=S.default(E.default.mark((function a(s,o,u){var c,l;return E.default.wrap((function(a){for(;;)switch(a.prev=a.next){case 0:return c=i.network.post(i.config.mediaUrl,null!=n?n:"media",t,e,r),u((function(){return c.cancel()})),a.prev=2,a.next=5,c;case 5:l=a.sent,s(new Media(i.config,i.network,l.body)),a.next=12;break;case 9:a.prev=9,a.t0=a.catch(2),o(a.t0);case 12:case"end":return a.stop()}}),a,null,[[2,9]])})));return function(e,t,n){return a.apply(this,arguments)}}())}},{key:"postFormData",value:function(e,t){var n=this;return new Y(function(){var r=S.default(E.default.mark((function r(i,a,s){var o,u;return E.default.wrap((function(r){for(;;)switch(r.prev=r.next){case 0:return o=n.network.post(n.config.mediaUrl,null!=t?t:"media",e),s((function(){return o.cancel()})),r.prev=2,r.next=5,o;case 5:u=r.sent,i(new Media(n.config,n.network,u.body)),r.next=12;break;case 9:r.prev=9,r.t0=r.catch(2),a(r.t0);case 12:case"end":return r.stop()}}),r,null,[[2,9]])})));return function(e,t,n){return r.apply(this,arguments)}}())}},{key:"mediaSetGet",value:function(e){var t=this;return new Y(function(){var n=S.default(E.default.mark((function n(r,i,a){var s,o,u,c;return E.default.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return s={command:"get",list:e.map((function(e){return{media_sid:e}}))},o=t.network.post("".concat(t.config.mediaSetUrl),null,s,"application/json"),a((function(){return o.cancel()})),n.prev=3,n.next=6,o;case 6:u=n.sent,c=u.body.map((function(e){if(200===e.code)return new Media(t.config,t.network,e.media_record);i("Failed to obtain detailed information about Media items (failed SID ".concat(e.media_record.sid,")"))})),r(c),n.next=14;break;case 11:n.prev=11,n.t0=n.catch(3),i(n.t0);case 14:case"end":return n.stop()}}),n,null,[[3,11]])})));return function(e,t,r){return n.apply(this,arguments)}}())}},{key:"mediaSetGetContentUrls",value:function(e){var t=this;return new Y(function(){var n=S.default(E.default.mark((function n(r,i,a){var s,o,u,c;return E.default.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return s={command:"get",list:e.map((function(e){return{media_sid:e}}))},o=t.network.post("".concat(t.config.mediaSetUrl),null,s,"application/json"),a((function(){return o.cancel()})),n.prev=3,n.next=6,o;case 6:u=n.sent,c=new Map,u.body.forEach((function(e){200===e.code?c.set(e.media_record.sid,e.media_record.links.content_direct_temporary):i("Failed to obtain detailed information about Media items (failed SID ".concat(e.media_record.sid,")"))})),r(c),n.next=15;break;case 12:n.prev=12,n.t0=n.catch(3),i(n.t0);case 15:case"end":return n.stop()}}),n,null,[[3,12]])})));return function(e,t,r){return n.apply(this,arguments)}}())}}]),Client}(),_.default(se,"version","0.6.5"),se),Q([h.validateTypes(h.nonEmptyString),X("design:type",Function),X("design:paramtypes",[String]),X("design:returntype",void 0)],e.default.prototype,"updateToken",null),Q([h.validateTypesAsync(h.nonEmptyString),X("design:type",Function),X("design:paramtypes",[String]),X("design:returntype",Y)],e.default.prototype,"get",null),e.default=Q([h.validateConstructorTypes(h.nonEmptyString,h.nonEmptyString,[h.nonEmptyString,h.literal(null)],[h.pureObject,"undefined"]),X("design:paramtypes",[String,String,Object,Object])],e.default),e.CancellablePromise=Y,e.Client=e.default,e.McsClient=e.default,e.McsMedia=Media,e.Media=Media}(mC);var SP=Dt,EP=Lt,TP=sw.aTypedArray;(0,sw.exportTypedArrayMethod)("at",(function(e){var t=TP(this),n=SP(t.length),r=EP(e),i=r>=0?r:n+r;return i<0||i>=n?void 0:t[i]}));var RP=os,CP="ArrayBuffer",IP=mk.ArrayBuffer;function OP(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}Cn({global:!0,forced:a.ArrayBuffer!==IP},{ArrayBuffer:IP}),RP(CP);var PP=If.scope("Participant"),Participant=function(e){Oa(Participant,e);var t,n,r,i=OP(Participant);function Participant(e,t,n,r,a){var s,o,u;if(Ua(this,Participant),(u=i.call(this)).conversation=n,u.links=r,u.services=a,u.state={attributes:yh(e.attributes,"Retrieved malformed attributes from the server for participant: "+t,PP),dateCreated:e.dateCreated?vh(e.dateCreated):null,dateUpdated:e.dateCreated?vh(e.dateUpdated):null,sid:t,typingTimeout:null,isTyping:!1,identity:e.identity,roleSid:null!==(s=e.roleSid)&&void 0!==s?s:"",lastReadMessageIndex:Number.isInteger(e.lastConsumedMessageIndex)?e.lastConsumedMessageIndex:null,lastReadTimestamp:e.lastConsumptionTimestamp?vh(e.lastConsumptionTimestamp):null,type:e.type||"chat",userInfo:e.userInfo,bindings:null!==(o=e.bindings)&&void 0!==o?o:{}},!e.identity&&!e.type)throw new Error("Received invalid Participant object from server: Missing identity or type of Participant.");return u}return Na(Participant,[{key:"sid",get:function(){return this.state.sid}},{key:"attributes",get:function(){return this.state.attributes}},{key:"dateCreated",get:function(){return this.state.dateCreated}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"identity",get:function(){return this.state.identity}},{key:"isTyping",get:function(){return this.state.isTyping}},{key:"lastReadMessageIndex",get:function(){return this.state.lastReadMessageIndex}},{key:"lastReadTimestamp",get:function(){return this.state.lastReadTimestamp}},{key:"roleSid",get:function(){return this.state.roleSid}},{key:"type",get:function(){return this.state.type}},{key:"bindings",get:function(){var e;return null!==(e=this.state.bindings)&&void 0!==e?e:{}}},{key:"_startTyping",value:function(e){var t=this;return this.state.typingTimeout&&clearTimeout(this.state.typingTimeout),this.state.isTyping=!0,this.emit("typingStarted",this),this.conversation.emit("typingStarted",this),this.state.typingTimeout=Number(setTimeout((function(){return t._endTyping()}),e)),this}},{key:"_endTyping",value:function(){this.state.typingTimeout&&(this.state.isTyping=!1,this.emit("typingEnded",this),this.conversation.emit("typingEnded",this),clearInterval(this.state.typingTimeout),this.state.typingTimeout=null)}},{key:"_update",value:function(e){var t=[],n=yh(e.attributes,"Retrieved malformed attributes from the server for participant: "+this.state.sid,PP);e.attributes&&!hm(this.state.attributes,n)&&(this.state.attributes=n,t.push("attributes"));var r=vh(e.dateUpdated);e.dateUpdated&&(null==r?void 0:r.getTime())!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=r,t.push("dateUpdated"));var i=vh(e.dateCreated);if(e.dateCreated&&(null==i?void 0:i.getTime())!==(this.state.dateCreated&&this.state.dateCreated.getTime())&&(this.state.dateCreated=i,t.push("dateCreated")),e.roleSid&&this.state.roleSid!==e.roleSid&&(this.state.roleSid=e.roleSid,t.push("roleSid")),!Number.isInteger(e.lastConsumedMessageIndex)&&null!==e.lastConsumedMessageIndex||this.state.lastReadMessageIndex===e.lastConsumedMessageIndex||(this.state.lastReadMessageIndex=e.lastConsumedMessageIndex,t.push("lastReadMessageIndex")),e.lastConsumptionTimestamp){var a=new Date(e.lastConsumptionTimestamp);this.state.lastReadTimestamp&&this.state.lastReadTimestamp.getTime()===a.getTime()||(this.state.lastReadTimestamp=a,t.push("lastReadTimestamp"))}return e.bindings&&!hm(this.state.bindings,e.bindings)&&(this.state.bindings=e.bindings,t.push("bindings")),t.length>0&&this.emit("updated",{participant:this,updateReasons:t}),this}},{key:"getUser",value:(r=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("chat"==this.type){e.next=2;break}throw new Error("Getting User is not supported for this Participant type: "+this.type);case 2:return e.abrupt("return",this.services.users.getUser(this.state.identity,this.state.userInfo));case 3:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"remove",value:(n=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.conversation.removeParticipant(this));case 1:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"updateAttributes",value:(t=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:JSON.stringify(t)});case 2:return e.abrupt("return",this);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),Participant}(dm);function AP(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}Ma(Participant,"typingStarted","typingStarted"),Ma(Participant,"typingEnded","typingEnded"),Ma(Participant,"updated","updated"),Vc([_y(Ry),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Promise)],Participant.prototype,"updateAttributes",null);var jP=If.scope("Participants"),MP=function(e){Oa(l,e);var t,n,r,i,a,s,o,u,c=AP(l);function l(e,t,n,r,i){var a;return Ua(this,l),Ma(Ca(a=c.call(this)),"rosterEntityPromise",null),a.conversation=e,a.participants=t,a.links=n,a.configuration=r,a.services=i,a}return Na(l,[{key:"unsubscribe",value:(u=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.rosterEntityPromise){e.next=6;break}return e.next=3,this.rosterEntityPromise;case 3:e.sent.close(),this.rosterEntityPromise=null;case 6:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"subscribe",value:function(e){var t=this,n="string"==typeof e?this.services.syncClient.map({id:e,mode:"open_existing"}):Promise.resolve(e);return this.rosterEntityPromise=this.rosterEntityPromise||n.then((function(e){e.on("itemAdded",(function(e){jP.debug(t.conversation.sid+" itemAdded: "+e.item.key),t.upsertParticipant(e.item.key,e.item.data).then((function(e){t.emit("participantJoined",e)}))})),e.on("itemRemoved",(function(e){jP.debug(t.conversation.sid+" itemRemoved: "+e.key);var n=e.key;if(t.participants.has(n)){var r=t.participants.get(n);t.participants.delete(n),r&&t.emit("participantLeft",r)}})),e.on("itemUpdated",(function(e){jP.debug(t.conversation.sid+" itemUpdated: "+e.item.key),t.upsertParticipant(e.item.key,e.item.data)}));var n=[];return e.getItems().then((function e(r){return r.items.forEach((function(e){n.push(t.upsertParticipant(e.key,e.data))})),r.hasNextPage?r.nextPage().then(e):null})).then((function(){return Promise.all(n)})).then((function(){return e}))})).catch((function(e){throw t.rosterEntityPromise=null,"disconnected"!=t.services.syncClient.connectionState&&jP.error("Failed to get roster object for conversation",t.conversation.sid,e),jP.debug("ERROR: Failed to get roster object for conversation",t.conversation.sid,e),e}))}},{key:"upsertParticipantFromResponse",value:(o=Ra(Gc.mark((function e(t){var n,r,i,a,s,o,u,c;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=t.sid,i=t.attributes,a=t.date_created,s=t.date_updated,o=t.identity,u=t.role_sid,c=t.messaging_binding,e.next=3,this.upsertParticipant(r,{attributes:i,dateCreated:new Date(a),dateUpdated:new Date(s),identity:o,roleSid:u,lastConsumedMessageIndex:null,lastConsumptionTimestamp:null,type:null!==(n=null==c?void 0:c.type)&&void 0!==n?n:"chat"});case 3:return e.abrupt("return",e.sent);case 4:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"upsertParticipant",value:(s=Ra(Gc.mark((function e(t,n){var r,i,a=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(r=this.participants.get(t))){e.next=3;break}return e.abrupt("return",r._update(n));case 3:return i={self:"".concat(this.links.participants,"/").concat(t)},r=new Participant(n,t,this.conversation,i,this.services),this.participants.set(t,r),r.on("updated",(function(e){return a.emit("participantUpdated",e)})),e.abrupt("return",r);case 8:case"end":return e.stop()}}),e,this)}))),function(e,t){return s.apply(this,arguments)})},{key:"getParticipants",value:(a=Ra(Gc.mark((function e(){var t=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then((function(){var e=[];return t.participants.forEach((function(t){return e.push(t)})),e})):[]);case 1:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"getParticipantBySid",value:(i=Ra(Gc.mark((function e(t){var n=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then((function(){var e=n.participants.get(t);if(!e)throw new Error("Participant with SID "+t+" was not found");return e})):null);case 1:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"getParticipantByIdentity",value:(r=Ra(Gc.mark((function e(t){var n,r=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=null,e.abrupt("return",this.rosterEntityPromise?this.rosterEntityPromise.then((function(){if(r.participants.forEach((function(e){e.identity===t&&(n=e)})),!n)throw new Error("Participant with identity "+t+" was not found");return n})):null);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"add",value:(n=Ra(Gc.mark((function e(t,n){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.commandExecutor.mutateResource("post",this.links.participants,{identity:t,attributes:void 0!==n?JSON.stringify(n):void 0});case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"addNonChatParticipant",value:(t=Ra(Gc.mark((function e(t,n){var r,i,a,s,o=arguments;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=o.length>2&&void 0!==o[2]?o[2]:{},s=o.length>3&&void 0!==o[3]?o[3]:{},e.next=4,this.services.commandExecutor.mutateResource("post",this.links.participants,{attributes:void 0!==a?JSON.stringify(a):void 0,messaging_binding:{address:n,proxy_address:t,name:null==s||null===(r=s.email)||void 0===r?void 0:r.name,level:null==s||null===(i=s.email)||void 0===i?void 0:i.level}});case 4:return e.abrupt("return",e.sent);case 5:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})},{key:"remove",value:function(e){return this.services.commandExecutor.mutateResource("delete","".concat(this.links.participants,"/").concat(encodeURIComponent(e)))}}]),l}(dm),LP=Cn,NP=Nn,UP=X,DP=Dt,FP=Er,BP=o,qP=tS,zP=ic,WP=rS,GP=iS,$P=N,VP=sS,JP=[],KP=JP.sort,HP=BP((function(){JP.sort(void 0)})),YP=BP((function(){JP.sort(null)})),QP=zP("sort"),XP=!BP((function(){if($P)return $P<70;if(!(WP&&WP>3)){if(GP)return!0;if(VP)return VP<603;var e,t,n,r,i="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(r=0;r<47;r++)JP.push({k:t+r,v:n})}for(JP.sort((function(e,t){return t.v-e.v})),r=0;r<JP.length;r++)t=JP[r].k.charAt(0),i.charAt(i.length-1)!==t&&(i+=t);return"DGBEFHACIJK"!==i}}));LP({target:"Array",proto:!0,forced:HP||!YP||!QP||!XP},{sort:function(e){void 0!==e&&NP(e);var t=UP(this);if(XP)return void 0===e?KP.call(t):KP.call(t,e);var n,r,i=[],a=DP(t.length);for(r=0;r<a;r++)r in t&&i.push(t[r]);for(i=qP(i,function(e){return function(t,n){return void 0===n?-1:void 0===t?1:void 0!==e?+e(t,n)||0:FP(t)>FP(n)?1:-1}}(e)),n=i.length,r=0;r<n;)t[r]=i[r++];for(;r<a;)delete t[r++];return t}});var ZP=bC,eA=k,tA=Er;Cn({target:"String",proto:!0,forced:!kC("includes")},{includes:function(e){return!!~tA(eA(this)).indexOf(tA(ZP(e)),arguments.length>1?arguments[1]:void 0)}});var Media=function(){function Media(e,t){Ua(this,Media),Ma(this,"mcsMedia",null),this.services=t,e instanceof mC.McsMedia&&(this.mcsMedia=e),this.state={sid:e.sid,category:e.category,filename:e.filename,contentType:e.contentType,size:e.size}}return Na(Media,[{key:"sid",get:function(){return this.state.sid}},{key:"filename",get:function(){return this.state.filename}},{key:"contentType",get:function(){return this.state.contentType}},{key:"size",get:function(){return this.state.size}},{key:"category",get:function(){return this.state.category}},{key:"getContentTemporaryUrl",value:function(){var e=this;return new mC.CancellablePromise(function(){var t=Ra(Gc.mark((function t(n,r,i){var a,s,o,u;return Gc.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(s=e._fetchMcsMedia(),o=null===(a=e.mcsMedia)||void 0===a?void 0:a.getContentUrl(),i((function(){s.cancel(),o&&o.cancel()})),t.prev=3,e.mcsMedia){t.next=9;break}return t.next=7,s;case 7:u=t.sent,o=u.getContentUrl();case 9:if(t.t0=n,!o){t.next=16;break}return t.next=13,o;case 13:t.t1=t.sent,t.next=17;break;case 16:t.t1=null;case 17:t.t2=t.t1,(0,t.t0)(t.t2),t.next=24;break;case 21:t.prev=21,t.t3=t.catch(3),r(t.t3);case 24:case"end":return t.stop()}}),t,null,[[3,21]])})));return function(e,n,r){return t.apply(this,arguments)}}())}},{key:"_fetchMcsMedia",value:function(){var e=this;return new mC.CancellablePromise(function(){var t=Ra(Gc.mark((function t(n,r,i){var a;return Gc.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(a=e.services.mcsClient.get(e.state.sid),!e.services.mcsClient){t.next=14;break}return i((function(){return a.cancel()})),t.prev=3,t.next=6,a;case 6:e.mcsMedia=t.sent,n(e.mcsMedia),t.next=13;break;case 10:t.prev=10,t.t0=t.catch(3),r(t.t0);case 13:return t.abrupt("return");case 14:r(new Error("Media Content Service is unavailable"));case 15:case"end":return t.stop()}}),t,null,[[3,10]])})));return function(e,n,r){return t.apply(this,arguments)}}())}}]),Media}(),AggregatedDeliveryReceipt=function(){function AggregatedDeliveryReceipt(e){Ua(this,AggregatedDeliveryReceipt),this.state=e}return Na(AggregatedDeliveryReceipt,[{key:"total",get:function(){return this.state.total}},{key:"sent",get:function(){return this.state.sent}},{key:"delivered",get:function(){return this.state.delivered}},{key:"read",get:function(){return this.state.read}},{key:"undelivered",get:function(){return this.state.undelivered}},{key:"failed",get:function(){return this.state.failed}},{key:"_update",value:function(e){this.state=e}},{key:"_isEquals",value:function(e){var t=this.total===e.total,n=this.sent===e.sent,r=this.delivered===e.delivered,i=this.read===e.read,a=this.undelivered===e.undelivered,s=this.failed===e.failed;return t&&n&&r&&i&&a&&s}}]),AggregatedDeliveryReceipt}(),nA=function(){function e(t,n,r,i){Ua(this,e),this.state={prevToken:r,nextToken:i,source:n,items:t}}return Na(e,[{key:"hasNextPage",get:function(){return!!this.state.nextToken}},{key:"hasPrevPage",get:function(){return!!this.state.prevToken}},{key:"items",get:function(){return this.state.items}},{key:"nextPage",value:function(){return this.hasNextPage?this.state.source(this.state.nextToken):Promise.reject(new Error("No next page"))}},{key:"prevPage",value:function(){return this.hasPrevPage?this.state.source(this.state.prevToken):Promise.reject(new Error("No previous page"))}}]),e}(),DetailedDeliveryReceipt=Na((function DetailedDeliveryReceipt(e){Ua(this,DetailedDeliveryReceipt),this.sid=e.sid,this.messageSid=e.message_sid,this.conversationSid=e.conversation_sid,this.channelMessageSid=e.channel_message_sid,this.participantSid=e.participant_sid,this.status=e.status||"queued",this.errorCode=e.error_code||0,this.dateCreated=e.date_created,this.dateUpdated=e.date_updated})),rA={};function iA(e){return e&&"object"===Pa(e)&&"default"in e?e:{default:e}}Object.defineProperty(rA,"__esModule",{value:!0});var aA=iA(Sf.exports),sA=function(e){var t=aA.default.getLevel();aA.default.setLevel("warn"),aA.default.warn(e),aA.default.setLevel(t)},oA=rA.deprecated=function(e,t,n){return function(r,i,a){if("function"!=typeof a.value&&void 0===(null==a?void 0:a.get))throw new Error("The deprecated decorator can only be applied to methods or getters");if("function"!=typeof a.value){var s=a.get;a.get=function(){return sA("The getter ".concat(e," is deprecated").concat(t?", use "+t+" instead":"").concat(n?", "+n:".")),null==s?void 0:s.apply(this)}}else{var o=a.value;a.value=function(){sA("The method ".concat(e," is deprecated").concat(t?", use "+t+" instead":"").concat(n?", "+n:"."));for(var r=arguments.length,i=new Array(r),a=0;a<r;a++)i[a]=arguments[a];return o.apply(this,i)}}}},uA=rA.deprecationWarning=sA,cA=function(e){return e.map((function(e){var t,n,r,i,a=JSON.stringify(e);switch(e.type){case"QUICK_REPLY":return{type:"reply",title:e.title,id:null!==(t=e.id)&&void 0!==t?t:"",index:null!==(n=e.index)&&void 0!==n?n:0,rawData:a};case"PHONE_NUMBER":return{type:"phone",title:e.title,phone:null!==(r=e.phone)&&void 0!==r?r:"",rawData:a};case"URL":return{type:"url",title:e.title,url:null!==(i=e.url)&&void 0!==i?i:"",rawData:a};default:return{type:"other",rawData:a}}}))},lA=function(e,t){var n=JSON.stringify(t);switch(e){case"twilio/text":return{type:"text",body:t.body,rawData:n};case"twilio/media":var r=t;return{type:"media",body:r.body,media:r.media,rawData:n};case"twilio/location":var i=t;return{type:"location",longitude:i.longitude,latitude:i.latitude,label:i.label,rawData:n};case"twilio/quick-reply":var a=t;return{type:"quickReply",body:a.body,replies:a.actions,rawData:n};case"twilio/call-to-action":var s=t;return{type:"callToAction",body:s.body,actions:cA(s.actions),rawData:n};case"twilio/list-picker":var o=t;return{type:"listPicker",body:o.body,button:o.button,items:o.items,rawData:n};case"twilio/card":var u,c,l=t;return{type:"card",title:l.title,subtitle:l.subtitle,media:null!==(u=l.media)&&void 0!==u?u:[],actions:cA(null!==(c=l.actions)&&void 0!==c?c:[]),rawData:n};default:return{type:"other",rawData:n}}},ContentTemplateVariable=function(){function ContentTemplateVariable(e,t){Ua(this,ContentTemplateVariable),this.name=e,this.value=t}return Na(ContentTemplateVariable,[{key:"copyWithValue",value:function(e){return new ContentTemplateVariable(this.name,e)}}]),ContentTemplateVariable}(),fA=Na((function e(t){Ua(this,e),this.sid=t.sid,this.friendlyName=t.friendly_name,this.variables=Object.entries(JSON.parse(t.variables)).map((function(e){var t=mm(e,2),n=t[0],r=t[1];return new ContentTemplateVariable(n,r)})),this.variants=function(e){for(var t=new Map,n=0,r=Object.entries(e);n<r.length;n++){var i=mm(r[n],2),a=i[0],s=i[1];t.set(a,lA(a,s))}return t}(t.variants),this.dateCreated=new Date(t.date_created),this.dateUpdated=new Date(t.date_updated)}));function dA(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 pA(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?dA(Object(n),!0).forEach((function(t){Ma(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dA(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function hA(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}var vA=If.scope("Message"),yA=t.XMLHttpRequest||{},Message=function(e){Oa(Message,e);var t,n,r,i,a,s,o,u,c,l=hA(Message);function Message(e,t,n,r,i,a){var s,o,u,c,f,d;return Ua(this,Message),(d=l.call(this)).conversation=n,d.links=r,d.configuration=i,d.services=a,d.state={sid:t.sid,index:e,author:t.author,subject:t.subject,contentSid:t.contentSid,body:null!==(s=t.text)&&void 0!==s?s:null,timestamp:t.timestamp?new Date(t.timestamp):null,dateUpdated:t.dateUpdated?new Date(t.dateUpdated):null,lastUpdatedBy:null!==(o=t.lastUpdatedBy)&&void 0!==o?o:null,attributes:yh(t.attributes,"Got malformed attributes for the message ".concat(t.sid),vA),type:null!==(u=t.type)&&void 0!==u?u:"text",media:"media"===t.type&&t.media?new Media(t.media,d.services):null,medias:"media"===t.type&&t.medias?t.medias.map((function(e){return new Media(e,d.services)})):"media"===t.type&&t.media&&!t.medias?[new Media(pA(pA({},t.media),{},{category:"media"}),d.services)]:null,participantSid:null!==(c=t.memberSid)&&void 0!==c?c:null,aggregatedDeliveryReceipt:t.delivery?new AggregatedDeliveryReceipt(t.delivery):null,hasChannelMetadata:null!==(f=t.channelMetadata)&&void 0!==f&&f},d}return Na(Message,[{key:"sid",get:function(){return this.state.sid}},{key:"author",get:function(){return this.state.author}},{key:"subject",get:function(){return this.state.subject}},{key:"contentSid",get:function(){return this.state.contentSid}},{key:"body",get:function(){return this.state.body}},{key:"dateUpdated",get:function(){return this.state.dateUpdated}},{key:"index",get:function(){return this.state.index}},{key:"lastUpdatedBy",get:function(){return this.state.lastUpdatedBy}},{key:"dateCreated",get:function(){return this.state.timestamp}},{key:"attributes",get:function(){return this.state.attributes}},{key:"type",get:function(){return this.state.type}},{key:"media",get:function(){return this.state.media}},{key:"attachedMedia",get:function(){return this.getMediaByCategories(["media"])}},{key:"participantSid",get:function(){return this.state.participantSid}},{key:"aggregatedDeliveryReceipt",get:function(){return this.state.aggregatedDeliveryReceipt}},{key:"getMediaByCategory",value:function(e){return this.getMediaByCategories(e)}},{key:"getMediaByCategories",value:function(e){var t;return(null!==(t=this.state.medias)&&void 0!==t?t:[]).filter((function(t){return e.includes(t.category)}))}},{key:"getEmailBody",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text/plain";return null!==(e=null===(t=this.getMediaByCategories(["body"]))||void 0===t?void 0:t.filter((function(e){return e.contentType==n})).shift())&&void 0!==e?e:null}},{key:"getEmailHistory",value:function(){var e,t,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text/plain";return null!==(e=null===(t=this.getMediaByCategories(["history"]))||void 0===t?void 0:t.filter((function(e){return e.contentType==n})).shift())&&void 0!==e?e:null}},{key:"_update",value:function(e){var t=[];!e.text&&"string"!=typeof e.text||e.text===this.state.body||(this.state.body=e.text,t.push("body")),e.subject&&e.subject!==this.state.subject&&(this.state.subject=e.subject,t.push("subject")),e.lastUpdatedBy&&e.lastUpdatedBy!==this.state.lastUpdatedBy&&(this.state.lastUpdatedBy=e.lastUpdatedBy,t.push("lastUpdatedBy")),e.author&&e.author!==this.state.author&&(this.state.author=e.author,t.push("author")),e.dateUpdated&&new Date(e.dateUpdated).getTime()!==(this.state.dateUpdated&&this.state.dateUpdated.getTime())&&(this.state.dateUpdated=new Date(e.dateUpdated),t.push("dateUpdated")),e.timestamp&&new Date(e.timestamp).getTime()!==(this.state.timestamp&&this.state.timestamp.getTime())&&(this.state.timestamp=new Date(e.timestamp),t.push("dateCreated"));var n=yh(e.attributes,"Got malformed attributes for the message ".concat(this.sid),vA);hm(this.state.attributes,n)||(this.state.attributes=n,t.push("attributes"));var r=e.delivery,i=this.state.aggregatedDeliveryReceipt;!!(r&&r.total&&r.delivered&&r.failed&&r.read&&r.sent&&r.undelivered)&&(i?i._isEquals(r)||(i._update(r),t.push("deliveryReceipt")):(this.state.aggregatedDeliveryReceipt=new AggregatedDeliveryReceipt(r),t.push("deliveryReceipt"))),t.length>0&&this.emit("updated",{message:this,updateReasons:t})}},{key:"getParticipant",value:(c=Ra(Gc.mark((function e(){var t,n,r=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t=null,!this.state.participantSid){e.next=5;break}return e.next=4,this.conversation.getParticipantBySid(this.state.participantSid).catch((function(){return vA.debug('Participant with sid "'.concat(r.participantSid,'" not found for message ').concat(r.sid)),null}));case 4:t=e.sent;case 5:if(t||!this.state.author){e.next=9;break}return e.next=8,this.conversation.getParticipantByIdentity(this.state.author).catch((function(){return vA.debug('Participant with identity "'.concat(r.author,'" not found for message ').concat(r.sid)),null}));case 8:t=e.sent;case 9:if(!t){e.next=11;break}return e.abrupt("return",t);case 11:throw n="Participant with ",this.state.participantSid&&(n+="SID '"+this.state.participantSid+"' "),this.state.author&&(this.state.participantSid&&(n+="or "),n+="identity '"+this.state.author+"' "),"Participant with "===n&&(n="Participant "),n+="was not found",new Error(n);case 17:case"end":return e.stop()}}),e,this)}))),function(){return c.apply(this,arguments)})},{key:"getDetailedDeliveryReceipts",value:(u=Ra(Gc.mark((function e(){var t,n;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._getDetailedDeliveryReceiptsPaginator();case 2:t=e.sent,n=t.items;case 4:if(!t.hasNextPage){e.next=11;break}return e.next=7,t.nextPage();case 7:t=e.sent,n=[].concat(Ty(n),Ty(t.items)),e.next=4;break;case 11:return e.abrupt("return",n);case 12:case"end":return e.stop()}}),e,this)}))),function(){return u.apply(this,arguments)})},{key:"remove",value:(o=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.commandExecutor.mutateResource("delete",this.links.self);case 2:return e.abrupt("return",this);case 3:case"end":return e.stop()}}),e,this)}))),function(){return o.apply(this,arguments)})},{key:"updateBody",value:(s=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{body:t});case 2:return e.abrupt("return",this);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"updateAttributes",value:(a=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.commandExecutor.mutateResource("post",this.links.self,{attributes:void 0!==t?JSON.stringify(t):void 0});case 2:return e.abrupt("return",this);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"attachTemporaryUrlsFor",value:(i=Ra(Gc.mark((function e(t){var n,r=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(n=null==t?void 0:t.map((function(e){return e.sid})),!this.services.mcsClient||!n){e.next=7;break}return e.next=4,this.services.mcsClient.mediaSetGet(n);case 4:return e.abrupt("return",e.sent.map((function(e){return new Media(e,r.services)})));case 7:throw new Error("Media Content Service is unavailable");case 8:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"getTemporaryContentUrlsForMedia",value:function(e){var t=e.map((function(e){return e.sid}));return this.getTemporaryContentUrlsForMediaSids(t)}},{key:"getTemporaryContentUrlsForMediaSids",value:function(e){var t=this;return new mC.CancellablePromise(function(){var n=Ra(Gc.mark((function n(r,i,a){var s,o;return Gc.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(s=t.services.mcsClient.mediaSetGetContentUrls(null!=e?e:[]),t.services.mcsClient&&e){n.next=4;break}return i(new Error("Media Content Service is unavailable")),n.abrupt("return");case 4:return a((function(){s.cancel()})),n.prev=5,n.next=8,s;case 8:o=n.sent,r(o),n.next=15;break;case 12:n.prev=12,n.t0=n.catch(5),i(n.t0);case 15:case"end":return n.stop()}}),n,null,[[5,12]])})));return function(e,t,r){return n.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForAttachedMedia",value:function(){var e,t=this.attachedMedia,n=null!==(e=null==t?void 0:t.map((function(e){return e.sid})))&&void 0!==e?e:[];return this.getTemporaryContentUrlsForMediaSids(n)}},{key:"_getDetailedDeliveryReceiptsPaginator",value:(r=Ra(Gc.mark((function e(t){var n,r,i,a=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=this.configuration.links.messagesReceipts.replace("%s",this.conversation.sid).replace("%s",this.sid),r=new mh(n).arg("PageToken",null==t?void 0:t.pageToken).arg("PageSize",null==t?void 0:t.pageSize).build(),e.next=4,this.services.network.get(r);case 4:return i=e.sent,e.abrupt("return",new nA(i.body.delivery_receipts.map((function(e){return new DetailedDeliveryReceipt(e)})),(function(e,t){return a._getDetailedDeliveryReceiptsPaginator({pageToken:e,pageSize:t})}),i.body.meta.previous_token,i.body.meta.next_token));case 6:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"getContentData",value:function(){var e=this;return new mC.CancellablePromise(function(){var t=Ra(Gc.mark((function t(n,r,i){var a,s,o,u,c,l,f,d,p,h;return Gc.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(null!==e.state.contentSid){t.next=3;break}return n(null),t.abrupt("return");case 3:if(null!==(a=e.getMediaByCategories(["body"]))){t.next=7;break}return n(null),t.abrupt("return");case 7:if(s="application/x-vnd.com.twilio.rich.",0!==(o=a.filter((function(e){return e.contentType.startsWith(s)}))).length){t.next=12;break}return n(null),t.abrupt("return");case 12:return u=o[0],c=u.getContentTemporaryUrl(),i((function(){c.cancel()})),t.prev=15,t.next=18,c;case 18:l=t.sent,t.next=25;break;case 21:return t.prev=21,t.t0=t.catch(15),r(t.t0),t.abrupt("return");case 25:if(null!==l){t.next=28;break}return n(null),t.abrupt("return");case 28:return f=new Promise((function(e,t){var n,r=!1,a=new yA;a.open("GET",null!==(n=l)&&void 0!==n?n:"",!0),a.responseType="text",a.onreadystatechange=function(){4!==a.readyState||r||e(a.responseText)},a.onerror=function(){t(a.statusText)},i((function(){r=!0,a.abort(),t(new Error("XHR has been aborted"))})),a.send()})),t.prev=29,t.next=32,f;case 32:p=t.sent,d=JSON.parse(p),t.next=40;break;case 36:return t.prev=36,t.t1=t.catch(29),r(t.t1),t.abrupt("return");case 40:h=u.contentType.replace(s,"").replace(".","/"),n(lA(h,d.data));case 42:case"end":return t.stop()}}),t,null,[[15,21],[29,36]])})));return function(e,n,r){return t.apply(this,arguments)}}())}},{key:"getChannelMetadata",value:(n=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.state.hasChannelMetadata){e.next=2;break}return e.abrupt("return",null);case 2:return e.next=4,this.services.channelMetadataClient.getChannelMetadata(this.conversation.sid,this.sid);case 4:return e.abrupt("return",e.sent);case 5:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"getMessageRecipients",value:(t=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.messageRecipientsClient.getRecipientsFromMessage(this.conversation.sid,this.sid);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),Message}(dm);function mA(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 gA(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?mA(Object(n),!0).forEach((function(t){Ma(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mA(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function bA(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return wA(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return wA(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function wA(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function kA(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}Ma(Message,"updated","updated"),Vc([oA("getMediaByCategory","getMediaByCategories"),Jc("design:type",Function),Jc("design:paramtypes",[Array]),Jc("design:returntype",Array)],Message.prototype,"getMediaByCategory",null),Vc([xy([my,"undefined"]),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Media)],Message.prototype,"getEmailBody",null),Vc([xy([my,"undefined"]),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Media)],Message.prototype,"getEmailHistory",null),Vc([_y("string"),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],Message.prototype,"updateBody",null),Vc([_y(Ry),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Promise)],Message.prototype,"updateAttributes",null),Vc([oA("attachTemporaryUrlsFor","getTemporaryContentUrlsForMedia"),Jc("design:type",Function),Jc("design:paramtypes",[Array]),Jc("design:returntype",Promise)],Message.prototype,"attachTemporaryUrlsFor",null),Vc([_y(yy("media",Media)),Jc("design:type",Function),Jc("design:paramtypes",[Array]),Jc("design:returntype",mC.CancellablePromise)],Message.prototype,"getTemporaryContentUrlsForMedia",null),Vc([_y(yy("strings","string")),Jc("design:type",Function),Jc("design:paramtypes",[Array]),Jc("design:returntype",mC.CancellablePromise)],Message.prototype,"getTemporaryContentUrlsForMediaSids",null);var xA=If.scope("Messages"),_A=function(e){Oa(u,e);var t,n,r,i,a,s,o=kA(u);function u(e,t,n){var r;return Ua(this,u),(r=o.call(this)).conversation=e,r.configuration=t,r.services=n,r.messagesByIndex=new Map,r.messagesListPromise=null,r}return Na(u,[{key:"subscribe",value:(s=Ra(Gc.mark((function e(t){var n,r=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this.messagesListPromise){e.next=2;break}return e.abrupt("return",this.messagesListPromise);case 2:return this.messagesListPromise="string"==typeof t?this.services.syncClient.list({id:t,mode:"open_existing"}):Promise.resolve(t),e.prev=3,e.next=6,this.messagesListPromise;case 6:return(n=e.sent).on("itemAdded",(function(e){xA.debug("".concat(r.conversation.sid," itemAdded: ").concat(e.item.index));var t={self:"".concat(r.conversation._links.messages,"/").concat(e.item.data.sid),conversation:r.conversation._links.self,messages_receipts:"".concat(r.conversation._links.messages,"/").concat(e.item.data.sid,"/Receipts")},n=new Message(e.item.index,e.item.data,r.conversation,t,r.configuration,r.services);r.messagesByIndex.has(n.index)?xA.debug("Message arrived, but is already known and ignored",r.conversation.sid,n.index):(r.messagesByIndex.set(n.index,n),n.on("updated",(function(e){return r.emit("messageUpdated",e)})),r.emit("messageAdded",n))})),n.on("itemRemoved",(function(e){xA.debug("#{this.conversation.sid} itemRemoved: ".concat(e.index));var t=e.index;if(r.messagesByIndex.has(t)){var n=r.messagesByIndex.get(t);if(!n)return;r.messagesByIndex.delete(n.index),n.removeAllListeners("updated"),r.emit("messageRemoved",n)}})),n.on("itemUpdated",(function(e){xA.debug("".concat(r.conversation.sid," itemUpdated: ").concat(e.item.index));var t=r.messagesByIndex.get(e.item.index);t&&t._update(e.item.data)})),e.abrupt("return",n);case 13:throw e.prev=13,e.t0=e.catch(3),this.messagesListPromise=null,"disconnected"!==this.services.syncClient.connectionState&&xA.error("Failed to get messages object for conversation",this.conversation.sid,e.t0),xA.debug("ERROR: Failed to get messages object for conversation",this.conversation.sid,e.t0),e.t0;case 19:case"end":return e.stop()}}),e,this,[[3,13]])}))),function(e){return s.apply(this,arguments)})},{key:"unsubscribe",value:(a=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.messagesListPromise){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,this.messagesListPromise;case 4:e.sent.close(),this.messagesListPromise=null;case 7:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"sendV2",value:function(e){var t=this;return xA.debug("Sending message V2",e.mediaContent,e.attributes,e.emailOptions),new mC.CancellablePromise(function(){var n=Ra(Gc.mark((function n(r,i,a){var s,o,u,c,l,f,d,p,h,v,y,m;return Gc.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:o=[],u=[],a((function(){u.forEach((function(e){return e.cancel()}))})),c=bA(e.mediaContent),n.prev=4,c.s();case 6:if((l=c.n()).done){n.next=25;break}return f=mm(l.value,2),d=f[0],p=f[1],n.prev=8,xA.debug("Adding media to a message as ".concat(p instanceof FormData?"FormData":"SendMediaOptions"),p),y=p instanceof FormData?t.services.mcsClient.postFormData(p,d):t.services.mcsClient.post(null!==(h=p.contentType)&&void 0!==h?h:"",null!==(v=p.media)&&void 0!==v?v:"",d,p.filename),u.push(y),n.t0=o,n.next=15,y;case 15:n.t1=n.sent,n.t0.push.call(n.t0,n.t1),n.next=23;break;case 19:return n.prev=19,n.t2=n.catch(8),i(n.t2),n.abrupt("return");case 23:n.next=6;break;case 25:n.next=30;break;case 27:n.prev=27,n.t3=n.catch(4),c.e(n.t3);case 30:return n.prev=30,c.f(),n.finish(30);case 33:return m=t.services.commandExecutor.mutateResource("post",t.conversation._links.messages,{body:e.text,subject:null===(s=e.emailOptions)||void 0===s?void 0:s.subject,media_sids:o.map((function(e){return e.sid})),attributes:void 0!==e.attributes?JSON.stringify(e.attributes):void 0,content_sid:e.contentSid,content_variables:void 0!==e.contentVariables?JSON.stringify(e.contentVariables.reduce((function(e,t){return gA(gA({},e),{},Ma({},t.name,t.value))}),{})):void 0}),n.prev=34,n.t4=r,n.next=38,m;case 38:n.t5=n.sent,(0,n.t4)(n.t5),n.next=45;break;case 42:n.prev=42,n.t6=n.catch(34),i(n.t6);case 45:case"end":return n.stop()}}),n,null,[[4,27,30,33],[8,19],[34,42]])})));return function(e,t,r){return n.apply(this,arguments)}}())}},{key:"send",value:(i=Ra(Gc.mark((function e(t){var n,r,i=arguments;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=i.length>1&&void 0!==i[1]?i[1]:{},r=i.length>2?i[2]:void 0,xA.debug("Sending text message",t,n,r),e.abrupt("return",this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{body:null!=t?t:"",attributes:void 0!==n?JSON.stringify(n):void 0,subject:null==r?void 0:r.subject}));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"sendMedia",value:(r=Ra(Gc.mark((function e(t){var n,r,i,a,s,o=arguments;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=o.length>1&&void 0!==o[1]?o[1]:{},a=o.length>2?o[2]:void 0,xA.debug("Sending media message",t,i,a),xA.debug("Sending media message as ".concat(t instanceof FormData?"FormData":"SendMediaOptions"),t,i),!(t instanceof FormData)){e.next=10;break}return e.next=7,this.services.mcsClient.postFormData(t);case 7:e.t0=e.sent,e.next=13;break;case 10:return e.next=12,this.services.mcsClient.post(null!==(n=t.contentType)&&void 0!==n?n:"",null!==(r=t.media)&&void 0!==r?r:"","media",t.filename);case 12:e.t0=e.sent;case 13:return s=e.t0,e.next=16,this.services.commandExecutor.mutateResource("post",this.conversation._links.messages,{media_sids:[s.sid],attributes:void 0!==i?JSON.stringify(i):void 0});case 16:return e.abrupt("return",e.sent);case 17:case"end":return e.stop()}}),e,this)}))),function(e){return r.apply(this,arguments)})},{key:"getMessages",value:(n=Ra(Gc.mark((function e(t,n){var r,i=arguments;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=i.length>2&&void 0!==i[2]?i[2]:"backwards",e.abrupt("return",this._getMessages(t,n,r));case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"_wrapPaginator",value:function(e,t,n){var r=this,i="desc"===e,a=function(){return t.nextPage().then((function(t){return r._wrapPaginator(e,t,n)}))},s=function(){return t.prevPage().then((function(t){return r._wrapPaginator(e,t,n)}))};return n(t.items).then((function(e){return{items:e.sort((function(e,t){return e.index-t.index})),hasPrevPage:i?t.hasNextPage:t.hasPrevPage,hasNextPage:i?t.hasPrevPage:t.hasNextPage,prevPage:i?a:s,nextPage:i?s:a}}))}},{key:"_upsertMessage",value:function(e,t){var n=this,r=this.messagesByIndex.get(e);if(r)return r;var i={self:"".concat(this.conversation._links.messages,"/").concat(t.sid),conversation:this.conversation._links.self,messages_receipts:"".concat(this.conversation._links.messages,"/").concat(t.sid,"/Receipts")},a=new Message(e,t,this.conversation,i,this.configuration,this.services);return this.messagesByIndex.set(a.index,a),a.on("updated",(function(e){return n.emit("messageUpdated",e)})),a}},{key:"_getMessages",value:(t=Ra(Gc.mark((function e(){var t,n,r,i,a,s,o=this,u=arguments;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=u.length>0&&void 0!==u[0]?u[0]:30,n=u.length>1&&void 0!==u[1]?u[1]:"end",r=u.length>2&&void 0!==u[2]?u[2]:"forward",i="backwards"===r?"desc":"asc",e.next=6,this.messagesListPromise;case 6:return a=e.sent,e.next=9,null==a?void 0:a.getItems({from:"end"!==n?n:void 0,pageSize:t,order:i,limit:t});case 9:return s=e.sent,e.next=12,this._wrapPaginator(i,s,(function(e){return Promise.all(e.map((function(e){return o._upsertMessage(e.index,e.data)})))}));case 12:return e.abrupt("return",e.sent);case 13:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})}]),u}(dm),SA=function(){function e(t){Ua(this,e),Ma(this,"attributes",{}),Ma(this,"mediaContent",[]),Ma(this,"emailOptions",{}),this.messagesEntity=t}return Na(e,[{key:"send",value:function(){var e=this;return new mC.CancellablePromise(function(){var t=Ra(Gc.mark((function t(n,r,i){var a,s;return Gc.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return a=e.messagesEntity.sendV2(e),i((function(){return a.cancel()})),t.prev=2,t.next=5,a;case 5:s=t.sent,n(hh(s.index)),t.next=12;break;case 9:t.prev=9,t.t0=t.catch(2),r(t.t0);case 12:case"end":return t.stop()}}),t,null,[[2,9]])})));return function(e,n,r){return t.apply(this,arguments)}}())}}]),e}(),EA=function(){function e(t,n){Ua(this,e),this.limits=t,this.message=new SA(n),this.emailBodies=new Map,this.emailHistories=new Map}return Na(e,[{key:"setBody",value:function(e){return this.message.text=e,this}},{key:"setSubject",value:function(e){return this.message.emailOptions.subject=e,this}},{key:"setAttributes",value:function(e){return this.message.attributes=e,this}},{key:"setEmailBody",value:function(e,t){return this.emailBodies.set(e,t),this}},{key:"setEmailHistory",value:function(e,t){return this.emailHistories.set(e,t),this}},{key:"setContentTemplate",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return this.message.contentSid=e,this.message.contentVariables=t,this}},{key:"addMedia",value:function(e){if("undefined"==typeof FormData&&e instanceof FormData)throw new Error("Could not add FormData content whilst not in a browser");if(!(e instanceof FormData)){var t=e;if(!t.contentType||!t.media)throw new Error("Media content in SendMediaOptions must contain non-empty contentType and media")}return this.message.mediaContent.push(["media",e]),this}},{key:"build",value:function(){var e=this;if(this.emailBodies.forEach((function(t,n){if(!e.limits.emailBodiesAllowedContentTypes.includes(n))throw new Error("Unsupported email body content type ".concat(n))})),this.emailHistories.forEach((function(t,n){if(!e.limits.emailHistoriesAllowedContentTypes.includes(n))throw new Error("Unsupported email history content type ".concat(n))})),this.emailBodies.size>this.limits.emailBodiesAllowedContentTypes.length)throw new Error("Too many email bodies attached to the message (".concat(this.emailBodies.size," > ").concat(this.limits.emailBodiesAllowedContentTypes.length,")"));if(this.emailHistories.size>this.limits.emailHistoriesAllowedContentTypes.length)throw new Error("Too many email histories attached to the message (".concat(this.emailHistories.size," > ").concat(this.limits.emailHistoriesAllowedContentTypes.length,")"));if(this.message.mediaContent.length>this.limits.mediaAttachmentsCountLimit)throw new Error("Too many media attachments in the message (".concat(this.message.mediaContent.length," > ").concat(this.limits.mediaAttachmentsCountLimit,")"));return this.emailBodies.forEach((function(t){e.message.mediaContent.push(["body",t])})),this.emailHistories.forEach((function(t){e.message.mediaContent.push(["history",t])})),this.message}},{key:"buildAndSend",value:function(){return this.build().send()}}]),e}();function TA(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return RA(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return RA(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function RA(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function CA(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}Vc([xy("string"),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",EA)],EA.prototype,"setBody",null),Vc([xy("string"),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",EA)],EA.prototype,"setSubject",null),Vc([xy(Ry),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",EA)],EA.prototype,"setAttributes",null),Vc([xy("string",[FormData,Iy]),Jc("design:type",Function),Jc("design:paramtypes",[String,Object]),Jc("design:returntype",EA)],EA.prototype,"setEmailBody",null),Vc([xy("string",[FormData,Iy]),Jc("design:type",Function),Jc("design:paramtypes",[String,Object]),Jc("design:returntype",EA)],EA.prototype,"setEmailHistory",null),Vc([xy("string",[py("content variables",ContentTemplateVariable),"undefined"]),Jc("design:type",Function),Jc("design:paramtypes",[String,Array]),Jc("design:returntype",EA)],EA.prototype,"setContentTemplate",null),Vc([xy([FormData,Iy]),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",EA)],EA.prototype,"addMedia",null);var IA={lastMessage:"lastMessage",attributes:"attributes",createdBy:"createdBy",dateCreated:"dateCreated",dateUpdated:"dateUpdated",friendlyName:"friendlyName",lastConsumedMessageIndex:"lastConsumedMessageIndex",notificationLevel:"notificationLevel",sid:"sid",status:"status",uniqueName:"uniqueName",state:"state",bindings:"bindings"},Conversation=function(e){Oa(Conversation,e);var t,n,r,i,a,s,o,u,c,l,f,d,p,h,v,y,m,g,b,w,k,x,_,S,E,T,R,C,I,O=CA(Conversation);function Conversation(e,t,n,r,i){var a,s,o;Ua(this,Conversation),(o=O.call(this)).sid=t,o._links=n,o._configuration=r,o._services=i,o._entityName=e.channel,o._internalState={uniqueName:e.uniqueName||null,status:"notParticipating",attributes:null!==(a=e.attributes)&&void 0!==a?a:{},createdBy:e.createdBy,dateCreated:vh(e.dateCreated),dateUpdated:vh(e.dateUpdated),friendlyName:e.friendlyName||null,lastReadMessageIndex:Number.isInteger(e.lastConsumedMessageIndex)?e.lastConsumedMessageIndex:null,bindings:null!==(s=e.bindings)&&void 0!==s?s:{}},e.notificationLevel&&(o._internalState.notificationLevel=e.notificationLevel);var u={participants:o._links.participants};return o._participants=new Map,o._participantsEntity=new MP(Ca(o),o._participants,u,o._configuration,o._services),o._participantsEntity.on("participantJoined",(function(e){return o.emit("participantJoined",e)})),o._participantsEntity.on("participantLeft",(function(e){return o.emit("participantLeft",e)})),o._participantsEntity.on("participantUpdated",(function(e){return o.emit("participantUpdated",e)})),o._messagesEntity=new _A(Ca(o),r,i),o._messagesEntity.on("messageAdded",(function(e){return o._onMessageAdded(e)})),o._messagesEntity.on("messageUpdated",(function(e){return o.emit("messageUpdated",e)})),o._messagesEntity.on("messageRemoved",(function(e){return o.emit("messageRemoved",e)})),o}return Na(Conversation,[{key:"uniqueName",get:function(){return this._internalState.uniqueName}},{key:"status",get:function(){return this._internalState.status}},{key:"friendlyName",get:function(){return this._internalState.friendlyName}},{key:"dateUpdated",get:function(){return this._internalState.dateUpdated}},{key:"dateCreated",get:function(){return this._internalState.dateCreated}},{key:"createdBy",get:function(){var e;return null!==(e=this._internalState.createdBy)&&void 0!==e?e:""}},{key:"attributes",get:function(){return this._internalState.attributes}},{key:"lastReadMessageIndex",get:function(){return this._internalState.lastReadMessageIndex}},{key:"lastMessage",get:function(){var e;return null!==(e=this._internalState.lastMessage)&&void 0!==e?e:void 0}},{key:"notificationLevel",get:function(){var e;return null!==(e=this._internalState.notificationLevel)&&void 0!==e?e:"default"}},{key:"bindings",get:function(){return this._internalState.bindings}},{key:"limits",get:function(){return this._configuration.limits}},{key:"state",get:function(){return this._internalState.state}},{key:"_statusSource",get:function(){return this._dataSource}},{key:"add",value:(I=Ra(Gc.mark((function e(t,n){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this._participantsEntity.add(t,null!=n?n:{}));case 1:case"end":return e.stop()}}),e,this)}))),function(e,t){return I.apply(this,arguments)})},{key:"addNonChatParticipant",value:(C=Ra(Gc.mark((function e(t,n){var r,i,a=arguments;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=a.length>2&&void 0!==a[2]?a[2]:{},i=a.length>3&&void 0!==a[3]?a[3]:{},e.abrupt("return",this._participantsEntity.addNonChatParticipant(t,n,null!=r?r:{},null!=i?i:{}));case 3:case"end":return e.stop()}}),e,this)}))),function(e,t){return C.apply(this,arguments)})},{key:"advanceLastReadMessageIndex",value:(R=Ra(Gc.mark((function e(t){var n;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribeStreams();case 2:if(!(t<(null!==(n=this.lastReadMessageIndex)&&void 0!==n?n:0))){e.next=6;break}return e.next=5,this._setLastReadMessageIndex(this.lastReadMessageIndex);case 5:case 8:return e.abrupt("return",e.sent);case 6:return e.next=8,this._setLastReadMessageIndex(t);case 9:case"end":return e.stop()}}),e,this)}))),function(e){return R.apply(this,arguments)})},{key:"delete",value:(T=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.commandExecutor.mutateResource("delete",this._links.self);case 2:return e.abrupt("return",this);case 3:case"end":return e.stop()}}),e,this)}))),function(){return T.apply(this,arguments)})},{key:"getAttributes",value:(E=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribe();case 2:return e.abrupt("return",this.attributes);case 3:case"end":return e.stop()}}),e,this)}))),function(){return E.apply(this,arguments)})},{key:"getMessages",value:(S=Ra(Gc.mark((function e(t,n,r){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribeStreams();case 2:return e.abrupt("return",this._messagesEntity.getMessages(t,n,r));case 3:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return S.apply(this,arguments)})},{key:"getParticipants",value:(_=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribeStreams();case 2:return e.abrupt("return",this._participantsEntity.getParticipants());case 3:case"end":return e.stop()}}),e,this)}))),function(){return _.apply(this,arguments)})},{key:"getParticipantsCount",value:(x=Ra(Gc.mark((function e(){var t,n,r;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new mh(this._configuration.links.conversations).path(this.sid).build(),e.next=3,this._services.network.get(n);case 3:return r=e.sent,e.abrupt("return",null!==(t=r.body.participants_count)&&void 0!==t?t:0);case 5:case"end":return e.stop()}}),e,this)}))),function(){return x.apply(this,arguments)})},{key:"getParticipantBySid",value:(k=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.abrupt("return",this._participantsEntity.getParticipantBySid(t));case 1:case"end":return e.stop()}}),e,this)}))),function(e){return k.apply(this,arguments)})},{key:"getParticipantByIdentity",value:(w=Ra(Gc.mark((function e(){var t,n=arguments;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=n.length>0&&void 0!==n[0]?n[0]:"",e.abrupt("return",this._participantsEntity.getParticipantByIdentity(null!=t?t:""));case 2:case"end":return e.stop()}}),e,this)}))),function(){return w.apply(this,arguments)})},{key:"getMessagesCount",value:(b=Ra(Gc.mark((function e(){var t,n,r;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new mh(this._configuration.links.conversations).path(this.sid).build(),e.next=3,this._services.network.get(n);case 3:return r=e.sent,e.abrupt("return",null!==(t=r.body.messages_count)&&void 0!==t?t:0);case 5:case"end":return e.stop()}}),e,this)}))),function(){return b.apply(this,arguments)})},{key:"getUnreadMessagesCount",value:(g=Ra(Gc.mark((function e(){var t,n,r;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=new mh(this._configuration.links.myConversations).path(this.sid).build(),e.next=3,this._services.network.get(t);case 3:if((n=e.sent).body.conversation_sid===this.sid){e.next=6;break}throw new Error("Conversation was not found in the user conversations list");case 6:if("number"!=typeof(r=n.body.unread_messages_count)){e.next=9;break}return e.abrupt("return",r);case 9:return e.abrupt("return",null);case 10:case"end":return e.stop()}}),e,this)}))),function(){return g.apply(this,arguments)})},{key:"join",value:(m=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.commandExecutor.mutateResource("post",this._links.participants,{identity:this._configuration.userIdentity});case 2:return e.abrupt("return",this);case 3:case"end":return e.stop()}}),e,this)}))),function(){return m.apply(this,arguments)})},{key:"leave",value:(y=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("joined"!==this._internalState.status){e.next=3;break}return e.next=3,this._services.commandExecutor.mutateResource("delete","".concat(this._links.participants,"/").concat(encodeURIComponent(this._configuration.userIdentity)));case 3:return e.abrupt("return",this);case 4:case"end":return e.stop()}}),e,this)}))),function(){return y.apply(this,arguments)})},{key:"removeParticipant",value:(v=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._participantsEntity.remove("string"==typeof t?t:t.sid);case 2:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"sendMessage",value:(h=Ra(Gc.mark((function e(t,n,r){var i,a,s,o;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if("string"!=typeof t&&null!==t){e.next=5;break}return e.next=3,this._messagesEntity.send(t,n,r);case 3:return s=e.sent,e.abrupt("return",null!==(a=hh(s.index))&&void 0!==a?a:0);case 5:return e.next=7,this._messagesEntity.sendMedia(t,n,r);case 7:return o=e.sent,e.abrupt("return",null!==(i=hh(o.index))&&void 0!==i?i:0);case 9:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return h.apply(this,arguments)})},{key:"prepareMessage",value:function(){return new EA(this.limits,this._messagesEntity)}},{key:"setAllMessagesRead",value:(p=Ra(Gc.mark((function e(){var t;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribeStreams();case 2:return e.next=4,this.getMessages(1);case 4:if(!((t=e.sent).items.length>0)){e.next=7;break}return e.abrupt("return",this.advanceLastReadMessageIndex(t.items[0].index));case 7:return e.abrupt("return",0);case 8:case"end":return e.stop()}}),e,this)}))),function(){return p.apply(this,arguments)})},{key:"setAllMessagesUnread",value:(d=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribeStreams();case 2:return e.next=4,this._setLastReadMessageIndex(null);case 4:return e.abrupt("return",e.sent);case 5:case"end":return e.stop()}}),e,this)}))),function(){return d.apply(this,arguments)})},{key:"setUserNotificationLevel",value:(f=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.commandExecutor.mutateResource("post","".concat(this._configuration.links.myConversations,"/").concat(this.sid),{notification_level:t});case 2:case"end":return e.stop()}}),e,this)}))),function(e){return f.apply(this,arguments)})},{key:"typing",value:function(){return this._services.typingIndicator.send(this.sid)}},{key:"updateAttributes",value:(l=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.commandExecutor.mutateResource("post",this._links.self,{attributes:void 0!==t?JSON.stringify(t):void 0});case 2:return e.abrupt("return",this);case 3:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"updateFriendlyName",value:(c=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._internalState.friendlyName===t){e.next=3;break}return e.next=3,this._services.commandExecutor.mutateResource("post",this._links.self,{friendly_name:t});case 3:return e.abrupt("return",this);case 4:case"end":return e.stop()}}),e,this)}))),function(e){return c.apply(this,arguments)})},{key:"updateLastReadMessageIndex",value:(u=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribeStreams();case 2:return e.abrupt("return",this._setLastReadMessageIndex(t));case 3:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"updateUniqueName",value:(o=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this._internalState.uniqueName===t){e.next=4;break}return t||(t=""),e.next=4,this._services.commandExecutor.mutateResource("post",this._links.self,{unique_name:t});case 4:return e.abrupt("return",this);case 5:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"getMessageRecipients",value:(s=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.messageRecipientsClient.getRecipientsFromConversation(this.sid);case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e,this)}))),function(){return s.apply(this,arguments)})},{key:"_subscribe",value:(a=Ra(Gc.mark((function e(){var t=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._entityPromise){e.next=2;break}return e.abrupt("return",this._entityPromise);case 2:return this._entityPromise=this._services.syncClient.document({id:this._entityName,mode:"open_existing"}),e.prev=3,e.next=6,this._entityPromise;case 6:return this._entity=e.sent,this._entity.on("updated",(function(e){return t._update(e.data)})),this._entity.on("removed",(function(){return t.emit("removed",t)})),this._update(this._entity.data),e.abrupt("return",this._entity);case 13:throw e.prev=13,e.t0=e.catch(3),this._entity=null,this._entityPromise=null,"disconnected"!=this._services.syncClient.connectionState&&Conversation._logger.error("Failed to get conversation object",e.t0),Conversation._logger.debug("ERROR: Failed to get conversation object",e.t0),e.t0;case 20:case"end":return e.stop()}}),e,this,[[3,13]])}))),function(){return a.apply(this,arguments)})},{key:"_fetchStreams",value:(i=Ra(Gc.mark((function e(){var t,n,r;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._subscribe();case 2:return Conversation._logger.trace("_streamsAvailable, this.entity.data=",null===(t=this._entity)||void 0===t?void 0:t.data),r=null===(n=this._entity)||void 0===n?void 0:n.data,e.next=6,this._services.syncClient.list({id:r.messages,mode:"open_existing"});case 6:return this._messagesList=e.sent,e.next=9,this._services.syncClient.map({id:r.roster,mode:"open_existing"});case 9:this._participantsMap=e.sent;case 10:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"_subscribeStreams",value:(r=Ra(Gc.mark((function e(){var t,n,r,i,a,s,o;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this._subscribe();case 3:return Conversation._logger.trace("_subscribeStreams, this.entity.data=",null===(t=this._entity)||void 0===t?void 0:t.data),a=null===(n=this._entity)||void 0===n?void 0:n.data,s=a.messages,o=a.roster,e.next=9,Promise.all([this._messagesEntity.subscribe(null!==(r=this._messagesList)&&void 0!==r?r:s),this._participantsEntity.subscribe(null!==(i=this._participantsMap)&&void 0!==i?i:o)]);case 9:e.next=16;break;case 11:throw e.prev=11,e.t0=e.catch(0),"disconnected"!==this._services.syncClient.connectionState&&Conversation._logger.error("Failed to subscribe on conversation objects",this.sid,e.t0),Conversation._logger.debug("ERROR: Failed to subscribe on conversation objects",this.sid,e.t0),e.t0;case 16:case"end":return e.stop()}}),e,this,[[0,11]])}))),function(){return r.apply(this,arguments)})},{key:"_unsubscribe",value:(n=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!this._entity){e.next=5;break}return e.next=3,this._entity.close();case 3:this._entity=null,this._entityPromise=null;case 5:return e.abrupt("return",Promise.all([this._participantsEntity.unsubscribe(),this._messagesEntity.unsubscribe()]));case 6:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"_setStatus",value:function(e,t){var n=this;this._dataSource=t,this._internalState.status!==e&&(this._internalState.status=e,"joined"!==e?this._entityPromise&&this._unsubscribe().catch((function(t){if(Conversation._logger.debug("ERROR while setting conversation status "+e,t),"disconnected"!==n._services.syncClient.connectionState)throw t})):this._subscribeStreams().catch((function(t){if(Conversation._logger.debug("ERROR while setting conversation status "+e,t),"disconnected"!==n._services.syncClient.connectionState)throw t})))}},{key:"_update",value:function(e){var t,n,r,i,a;Conversation._logger.trace("_update",e),Conversation.preprocessUpdate(e,this.sid);for(var s=new Set,o=0,u=Object.keys(e);o<u.length;o++){var c=u[o],l=IA[c];if(l)switch(l){case IA.status:if(!e.status||"unknown"===e.status||this._internalState.status===e.status)break;this._internalState.status=e.status,s.add(l);break;case IA.attributes:if(hm(this._internalState.attributes,e.attributes))break;this._internalState.attributes=e.attributes,s.add(l);break;case IA.lastConsumedMessageIndex:if(void 0===e.lastConsumedMessageIndex||e.lastConsumedMessageIndex===this._internalState.lastReadMessageIndex)break;this._internalState.lastReadMessageIndex=e.lastConsumedMessageIndex,s.add("lastReadMessageIndex");break;case IA.lastMessage:if(this._internalState.lastMessage&&!e.lastMessage){delete this._internalState.lastMessage,s.add(l);break}this._internalState.lastMessage=this._internalState.lastMessage||{},void 0!==(null===(t=e.lastMessage)||void 0===t?void 0:t.index)&&e.lastMessage.index!==this._internalState.lastMessage.index&&(this._internalState.lastMessage.index=e.lastMessage.index,s.add(l)),void 0!==(null===(n=e.lastMessage)||void 0===n?void 0:n.timestamp)&&(null===(r=this._internalState.lastMessage)||void 0===r||null===(i=r.dateCreated)||void 0===i?void 0:i.getTime())!==e.lastMessage.timestamp.getTime()&&(this._internalState.lastMessage.dateCreated=e.lastMessage.timestamp,s.add(l)),hm(this._internalState.lastMessage,{})&&delete this._internalState.lastMessage;break;case IA.state:var f=e.state||void 0;if(void 0!==f&&(f.dateUpdated=new Date(f.dateUpdated)),hm(this._internalState.state,f))break;this._internalState.state=f,s.add(l);break;case IA.bindings:if(hm(this._internalState.bindings,e.bindings))break;this._internalState.bindings=e.bindings,s.add(l);break;default:var d=e[c]instanceof Date,p=d&&(null===(a=this._internalState[l])||void 0===a?void 0:a.getTime())===e[c].getTime(),h=!d&&this[l]===e[c];if(p||h)break;this._internalState[l]=e[c],s.add(l)}}s.size>0&&this.emit("updated",{conversation:this,updateReasons:Ty(s)})}},{key:"_onMessageAdded",value:function(e){var t,n=TA(this._participants.values());try{for(n.s();!(t=n.n()).done;){var r=t.value;if(r.identity===e.author){r._endTyping();break}}}catch(e){n.e(e)}finally{n.f()}this.emit("messageAdded",e)}},{key:"_setLastReadMessageIndex",value:(t=Ra(Gc.mark((function e(t){var n;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.commandExecutor.mutateResource("post","".concat(this._configuration.links.myConversations,"/").concat(this.sid),{last_read_message_index:t});case 2:return n=e.sent,e.abrupt("return",n.unread_messages_count);case 4:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}],[{key:"preprocessUpdate",value:function(e,t){try{"string"==typeof e.attributes?e.attributes=JSON.parse(e.attributes):e.attributes&&JSON.stringify(e.attributes)}catch(n){Conversation._logger.warn("Retrieved malformed attributes from the server for conversation: "+t),e.attributes={}}try{e.dateCreated&&(e.dateCreated=new Date(e.dateCreated))}catch(n){Conversation._logger.warn("Retrieved malformed dateCreated from the server for conversation: "+t),delete e.dateCreated}try{e.dateUpdated&&(e.dateUpdated=new Date(e.dateUpdated))}catch(n){Conversation._logger.warn("Retrieved malformed dateUpdated from the server for conversation: "+t),delete e.dateUpdated}try{e.lastMessage&&e.lastMessage.timestamp&&(e.lastMessage.timestamp=new Date(e.lastMessage.timestamp))}catch(n){Conversation._logger.warn("Retrieved malformed lastMessage.timestamp from the server for conversation: "+t),delete e.lastMessage.timestamp}}}]),Conversation}(dm);Ma(Conversation,"participantJoined","participantJoined"),Ma(Conversation,"participantLeft","participantLeft"),Ma(Conversation,"participantUpdated","participantUpdated"),Ma(Conversation,"messageAdded","messageAdded"),Ma(Conversation,"messageRemoved","messageRemoved"),Ma(Conversation,"messageUpdated","messageUpdated"),Ma(Conversation,"typingEnded","typingEnded"),Ma(Conversation,"typingStarted","typingStarted"),Ma(Conversation,"updated","updated"),Ma(Conversation,"removed","removed"),Ma(Conversation,"_logger",If.scope("Conversation")),Vc([_y(my,Cy),Jc("design:type",Function),Jc("design:paramtypes",[String,Object]),Jc("design:returntype",Promise)],Conversation.prototype,"add",null),Vc([_y(my,my,Cy),Jc("design:type",Function),Jc("design:paramtypes",[String,String,Object,Object]),Jc("design:returntype",Promise)],Conversation.prototype,"addNonChatParticipant",null),Vc([_y(gy),Jc("design:type",Function),Jc("design:paramtypes",[Number]),Jc("design:returntype",Promise)],Conversation.prototype,"advanceLastReadMessageIndex",null),Vc([_y(["undefined",gy],["undefined",gy],["undefined",vy("backwards","forward")]),Jc("design:type",Function),Jc("design:paramtypes",[Number,Number,String]),Jc("design:returntype",Promise)],Conversation.prototype,"getMessages",null),Vc([_y(my),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],Conversation.prototype,"getParticipantBySid",null),Vc([_y(my),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],Conversation.prototype,"getParticipantByIdentity",null),Vc([_y([my,Participant]),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Promise)],Conversation.prototype,"removeParticipant",null),Vc([_y(["string",FormData,vy(null),by("media options",{contentType:my,media:hy((function(e){var t="string"==typeof e&&e.length>0||e instanceof Uint8Array||e instanceof ArrayBuffer;return"function"==typeof Blob&&(t=t||e instanceof Blob),[t,"a non-empty string, an instance of Buffer or an instance of Blob"]}))})],Cy,["undefined",vy(null),by("email attributes",{subject:[my,"undefined"]})]),Jc("design:type",Function),Jc("design:paramtypes",[Object,Object,Object]),Jc("design:returntype",Promise)],Conversation.prototype,"sendMessage",null),Vc([_y(vy("default","muted")),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],Conversation.prototype,"setUserNotificationLevel",null),Vc([_y(Ry),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Promise)],Conversation.prototype,"updateAttributes",null),Vc([_y("string"),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],Conversation.prototype,"updateFriendlyName",null),Vc([_y([vy(null),gy]),Jc("design:type",Function),Jc("design:paramtypes",[Number]),Jc("design:returntype",Promise)],Conversation.prototype,"updateLastReadMessageIndex",null),Vc([_y(["string",vy(null)]),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],Conversation.prototype,"updateUniqueName",null);var OA=function(){function e(){var t=this;Ua(this,e),this._promise=new Promise((function(e,n){t._resolve=e,t._reject=n}))}return Na(e,[{key:"promise",get:function(){return this._promise}},{key:"update",value:function(e){this._resolve(e)}},{key:"set",value:function(e){this.current=e,this._resolve(e)}},{key:"fail",value:function(e){this._reject(e)}}]),e}();function PA(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return AA(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return AA(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function AA(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function jA(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 MA(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?jA(Object(n),!0).forEach((function(t){Ma(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jA(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function LA(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}var NA=If.scope("Conversations"),UA=function(e){Oa(p,e);var t,n,r,i,a,s,o,u,c,l,f,d=LA(p);function p(e,t){var n;return Ua(this,p),Ma(Ca(n=d.call(this)),"conversations",new Map),Ma(Ca(n),"myConversationsRead",new OA),Ma(Ca(n),"tombstones",new Set),Ma(Ca(n),"myConversationsFetched",!1),n.configuration=e,n.services=t,n}return Na(p,[{key:"addConversation",value:(f=Ra(Gc.mark((function e(t){var n,r,i,a,s,o,u,c,l,f;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=void 0!==(null==t?void 0:t.attributes)?t.attributes:{},e.next=3,this.services.commandExecutor.mutateResource("post",this.configuration.links.conversations,{friendly_name:t.friendlyName,unique_name:t.uniqueName,attributes:void 0!==a?JSON.stringify(a):void 0});case 3:if(s=e.sent,o=null!==(n=s.sid)&&void 0!==n?n:null,u=null!==(r=null===(i=s.sync_objects)||void 0===i?void 0:i.conversation)&&void 0!==r?r:null,c=MA({self:s.url},s.links),!(l=this.conversations.get(o))){e.next=12;break}return e.next=11,l._subscribe();case 11:return e.abrupt("return",l);case 12:return f=new Conversation({channel:u,entityName:"",uniqueName:"",attributes:null,createdBy:"",friendlyName:"",lastConsumedMessageIndex:0,dateCreated:null,dateUpdated:null},o,c,this.configuration,this.services),this.conversations.set(f.sid,f),this._registerForEvents(f),e.next=17,f._subscribe();case 17:return this.emit("conversationAdded",f),e.abrupt("return",f);case 19:case"end":return e.stop()}}),e,this)}))),function(e){return f.apply(this,arguments)})},{key:"fetchConversations",value:(l=Ra(Gc.mark((function e(){var t,n,r,i,a,s,o,u=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,this._getMap();case 3:return(t=e.sent).on("itemAdded",(function(e){NA.debug("itemAdded: ".concat(e.item.key)),u._upsertConversation("sync",e.item.key,e.item.data)})),t.on("itemRemoved",(function(e){NA.debug("itemRemoved: ".concat(e.key));var t=e.key;u.myConversationsFetched||u.tombstones.add(t);var n=u.conversations.get(t);n&&("joined"===n.status&&(n._setStatus("notParticipating","sync"),u.emit("conversationLeft",n)),u.conversations.delete(t),u.emit("conversationRemoved",n),n.emit("removed",n))})),t.on("itemUpdated",(function(e){NA.debug("itemUpdated: ".concat(e.item.key)),u._upsertConversation("sync",e.item.key,e.item.data)})),e.next=9,this._fetchMyConversations();case 9:n=e.sent,r=[],i=PA(n);try{for(i.s();!(a=i.n()).done;)s=a.value,r.push(this._upsertConversation("rest",s.channel_sid,s))}catch(e){i.e(e)}finally{i.f()}return this.myConversationsRead.set(!0),e.next=16,Promise.all(r);case 16:return this.myConversationsFetched=!0,this.tombstones.clear(),NA.debug("The conversations list has been successfully fetched"),e.abrupt("return",this);case 22:throw e.prev=22,e.t0=e.catch(0),o="Failed to fetch the conversations list","disconnected"!==this.services.syncClient.connectionState&&NA.error(o,e.t0),NA.debug("ERROR: ".concat(o),e.t0),e.t0;case 28:case"end":return e.stop()}}),e,this,[[0,22]])}))),function(){return l.apply(this,arguments)})},{key:"getConversations",value:(c=Ra(Gc.mark((function e(){var t,n,r=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._getMap();case 2:return t=e.sent,e.next=5,t.getItems();case 5:return n=e.sent,e.abrupt("return",this._wrapPaginator(n,(function(e){return Promise.all(e.map((function(e){return r._upsertConversation("sync",e.key,e.data)})))})));case 7:case"end":return e.stop()}}),e,this)}))),function(){return c.apply(this,arguments)})},{key:"getConversation",value:(u=Ra(Gc.mark((function e(t){var n,r,i,a=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._getMap();case 2:return n=e.sent,e.next=5,n.getItems({key:t});case 5:return r=e.sent,i=r.items.map((function(e){return a._upsertConversation("sync",e.key,e.data)})),e.abrupt("return",i.length>0?i[0]:null);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"getConversationByUniqueName",value:(o=Ra(Gc.mark((function e(t){var n,r,i,a,s;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new mh(this.configuration.links.myConversations).path(t).build(),e.next=3,this.services.network.get(n);case 3:return r=e.sent,i=r.body,a=i.conversation_sid,s={entityName:null,lastConsumedMessageIndex:i.last_read_message_index,status:(null==i?void 0:i.status)||"unknown",friendlyName:i.friendly_name,dateUpdated:i.date_updated,dateCreated:i.date_created,uniqueName:i.unique_name,createdBy:i.created_by,attributes:i.attributes,channel:i.sync_objects.conversation,notificationLevel:null==i?void 0:i.notification_level,sid:a},e.abrupt("return",a?this._upsertConversation("sync",a,s):null);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return o.apply(this,arguments)})},{key:"peekConversation",value:(s=Ra(Gc.mark((function e(t){var n,r,i,a;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return n=new mh(this.configuration.links.conversations).path(t).build(),e.next=3,this.services.network.get(n);case 3:return r=e.sent,i=r.body,a={entityName:null,status:(null==i?void 0:i.status)||"unknown",friendlyName:i.friendly_name,dateUpdated:i.date_updated,dateCreated:i.date_created,uniqueName:i.unique_name,createdBy:i.created_by,attributes:i.attributes,channel:"".concat(t,".channel"),sid:t},e.abrupt("return",this._upsertConversation("sync",t,a));case 7:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"_getMap",value:(a=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.services.syncClient.map({id:this.configuration.myConversations,mode:"open_existing"});case 2:return e.abrupt("return",e.sent);case 3:case"end":return e.stop()}}),e,this)}))),function(){return a.apply(this,arguments)})},{key:"_wrapPaginator",value:(i=Ra(Gc.mark((function e(t,n){var r,i=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n(t.items);case 2:return r=e.sent,e.abrupt("return",{items:r.filter((function(e){return null!==e})),hasNextPage:t.hasNextPage,hasPrevPage:t.hasPrevPage,nextPage:function(){return t.nextPage().then((function(e){return i._wrapPaginator(e,n)}))},prevPage:function(){return t.prevPage().then((function(e){return i._wrapPaginator(e,n)}))}});case 4:case"end":return e.stop()}}),e)}))),function(e,t){return i.apply(this,arguments)})},{key:"_updateConversation",value:(r=Ra(Gc.mark((function e(t,n,r){var i,a,s;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=void 0!==n._statusSource&&t!==n._statusSource,a="rest"!==t||"sync"===n._statusSource,!i||!a||"sync"===t){e.next=5;break}return NA.trace("upsertConversation: conversation is known from sync and came from REST, ignoring",{sid:n.sid,data:r.status,conversation:n.status}),e.abrupt("return");case 5:if("joined"!==r.status||"joined"===n.status){e.next=15;break}return n._setStatus("joined",t),s={},void 0!==r.notificationLevel&&(s.notificationLevel=r.notificationLevel),void 0!==r.lastConsumedMessageIndex&&(s.lastConsumedMessageIndex=r.lastConsumedMessageIndex),hm(s,{})||n._update(s),e.next=13,n._subscribe();case 13:return this.emit("conversationJoined",n),e.abrupt("return");case 15:if("notParticipating"!==r.status||"joined"!==n.status){e.next=22;break}return n._setStatus("notParticipating",t),n._update(r),e.next=20,n._subscribe();case 20:return this.emit("conversationLeft",n),e.abrupt("return");case 22:if("notParticipating"!==r.status){e.next=26;break}return e.next=25,n._subscribe();case 25:return e.abrupt("return");case 26:n._update(r);case 27:case"end":return e.stop()}}),e,this)}))),function(e,t,n){return r.apply(this,arguments)})},{key:"_upsertConversation",value:(n=Ra(Gc.mark((function e(t,n,r){var i,a,s,o;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(NA.trace("upsertConversation called for ".concat(n),r),!(i=this.conversations.get(n))){e.next=9;break}return NA.trace("upsertConversation: the conversation ".concat(i.sid," is known;")+"its status is known from the source ".concat(i._statusSource," ")+"and the update came from the source ".concat(t),i),e.next=6,this._updateConversation(t,i,r);case 6:return e.next=8,i._subscribe();case 8:return e.abrupt("return",i);case 9:if("rest"!==t||!this.tombstones.has(n)){e.next=12;break}return NA.trace("upsertChannel: the conversation is deleted but reappeared again from REST, ignoring",n),e.abrupt("return",null);case 12:return NA.trace("upsertConversation: creating a local conversation object with sid "+n,r),a="".concat(this.configuration.links.conversations,"/").concat(n),s={self:a,messages:"".concat(a,"/Messages"),participants:"".concat(a,"/Participants")},o=new Conversation(r,n,s,this.configuration,this.services),this.conversations.set(n,o),e.prev=17,e.next=20,o._subscribe();case 20:if("joined"!==r.status){e.next=23;break}return e.next=23,o._fetchStreams();case 23:e.next=32;break;case 25:if(e.prev=25,e.t0=e.catch(17),"SyncError"===e.t0.name){e.next=29;break}throw e.t0;case 29:return NA.trace("upsertChannel: the conversation is missing some Sync entity(ies), ignoring",n,e.t0),this.conversations.delete(n),e.abrupt("return",null);case 32:return this._registerForEvents(o),this.emit("conversationAdded",o),"joined"===r.status&&(o._setStatus("joined",t),this.emit("conversationJoined",o)),e.abrupt("return",o);case 36:case"end":return e.stop()}}),e,this,[[17,25]])}))),function(e,t,r){return n.apply(this,arguments)})},{key:"_fetchMyConversations",value:(t=Ra(Gc.mark((function e(){var t,n,r,i,a,s;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=[],n=null;case 2:return i=new mh(this.configuration.links.myConversations),n&&i.arg("PageToken",n),e.next=6,this.services.network.get(i.build());case 6:a=e.sent,s=null===(r=a.body)||void 0===r?void 0:r.conversations.map((function(e){return{descriptor:e,channel_sid:e.conversation_sid,status:e.status,channel:e.sync_objects.conversation,messages:e.sync_objects.messages,roster:"".concat(e.conversation_sid,".roster"),lastConsumedMessageIndex:e.last_read_message_index,notificationLevel:e.notification_level}})),n=a.body.meta.next_token,t=[].concat(Ty(t),Ty(s));case 10:if(n){e.next=2;break}case 11:return e.abrupt("return",t);case 12:case"end":return e.stop()}}),e,this)}))),function(){return t.apply(this,arguments)})},{key:"_onConversationRemoved",value:function(e){var t=this.conversations.get(e);t&&(this.conversations.delete(e),this.emit("conversationRemoved",t))}},{key:"_registerForEvents",value:function(e){var t=this;e.on("removed",(function(){return t._onConversationRemoved(e.sid)})),e.on("updated",(function(e){return t.emit("conversationUpdated",e)})),e.on("participantJoined",(function(e){return t.emit("participantJoined",e)})),e.on("participantLeft",(function(e){return t.emit("participantLeft",e)})),e.on("participantUpdated",(function(e){return t.emit("participantUpdated",e)})),e.on("messageAdded",(function(e){return t.emit("messageAdded",e)})),e.on("messageUpdated",(function(e){return t.emit("messageUpdated",e)})),e.on("messageRemoved",(function(e){return t.emit("messageRemoved",e)})),e.on("typingStarted",(function(e){return t.emit("typingStarted",e)})),e.on("typingEnded",(function(e){return t.emit("typingEnded",e)}))}}]),p}(dm),DA=Cn,FA=Xr.find,BA=$f,qA="find",zA=!0;function WA(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}qA in[]&&Array(1).find((function(){zA=!1})),DA({target:"Array",proto:!0,forced:zA},{find:function(e){return FA(this,e,arguments.length>1?arguments[1]:void 0)}}),BA(qA);var GA=function(e){Oa(a,e);var t,n,r,i=WA(a);function a(e,t,n){var r;return Ua(this,a),(r=i.call(this)).configuration=t,r.services=n,r.fifoStack=[],r.myself=e,r.myself.on("updated",(function(e){return r.emit("userUpdated",e)})),r.myself.on("userSubscribed",(function(){return r.emit("userSubscribed",r.myself)})),r.myself.on("userUnsubscribed",(function(){r.emit("userUnsubscribed",r.myself),r.myself._ensureFetched()})),r.subscribedUsers=new Map,r}return Na(a,[{key:"handleUnsubscribeUser",value:function(e){this.subscribedUsers.has(e.identity)&&this.subscribedUsers.delete(e.identity);var t=0;this.fifoStack.find((function(n,r){return n==e.identity&&(t=r,!0)}))&&this.fifoStack.splice(t,1),this.emit("userUnsubscribed",e)}},{key:"handleSubscribeUser",value:function(e){if(!this.subscribedUsers.has(e.identity)){if(this.fifoStack.length>=this.configuration.userInfosToSubscribe){var t,n,r=this.fifoStack.shift();null===(t=this.subscribedUsers)||void 0===t||null===(n=t.get(r))||void 0===n||n.unsubscribe()}this.fifoStack.push(e.identity),this.subscribedUsers.set(e.identity,e),this.emit("userSubscribed",e)}}},{key:"getUser",value:(r=Ra(Gc.mark((function e(t,n){var r,i,a,s=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.myself._ensureFetched();case 2:if(t!=this.myself.identity){e.next=4;break}return e.abrupt("return",this.myself);case 4:if(!(i=this.subscribedUsers.get(t))){e.next=7;break}return e.abrupt("return",i);case 7:if(null===(r=n)||void 0===r){e.next=11;break}e.next=14;break;case 11:return e.next=13,this.getSyncUniqueName(t);case 13:n=e.sent;case 14:return(a=new User(t,n,this.configuration,this.services)).on("updated",(function(e){return s.emit("userUpdated",e)})),a.on("userSubscribed",(function(){return s.handleSubscribeUser(a)})),a.on("userUnsubscribed",(function(){return s.handleUnsubscribeUser(a)})),e.next=20,a._ensureFetched();case 20:return e.abrupt("return",a);case 21:case"end":return e.stop()}}),e,this)}))),function(e,t){return r.apply(this,arguments)})},{key:"getSubscribedUsers",value:(n=Ra(Gc.mark((function e(){var t;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this.myself._ensureFetched();case 2:return t=[this.myself],this.subscribedUsers.forEach((function(e){return t.push(e)})),e.abrupt("return",t);case 5:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"getSyncUniqueName",value:(t=Ra(Gc.mark((function e(t){var n,r,i,a;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=new mh(this.configuration.links.users).path(t).build(),e.next=3,this.services.network.get(i);case 3:return a=e.sent,e.abrupt("return",null!==(n=null===(r=a.body)||void 0===r?void 0:r.sync_objects.user_info_map)&&void 0!==n?n:"");case 5:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),a}(dm),$A=If.scope("TypingIndicator"),VA=function(){function e(t,n,r){Ua(this,e),this.configuration=n,this.services=r,this.getConversation=t,this.serviceTypingTimeout=null,this.sentUpdates=new Map}var t;return Na(e,[{key:"typingTimeout",get:function(){return this.configuration.typingIndicatorTimeoutOverride||this.serviceTypingTimeout||this.configuration.typingIndicatorTimeoutDefault}},{key:"initialize",value:function(){var e=this;this.services.notificationClient.on("message",function(){var t=Ra(Gc.mark((function t(n,r){return Gc.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:if(n!==Gg.TYPING_INDICATOR){t.next=3;break}return t.next=3,e._handleRemoteTyping(r);case 3:case"end":return t.stop()}}),t)})));return function(e,n){return t.apply(this,arguments)}}())}},{key:"_handleRemoteTyping",value:(t=Ra(Gc.mark((function e(t){var n=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:$A.trace("Got new typing indicator ",t),this.getConversation(t.channel_sid).then((function(e){e&&e._participants.forEach((function(e){if(e.identity===t.identity){var r=n.configuration.typingIndicatorTimeoutOverride?n.configuration.typingIndicatorTimeoutOverride+1e3:1e3*t.typing_timeout;e._startTyping(r)}}))})).catch((function(e){throw $A.error(e),e}));case 2:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})},{key:"send",value:function(e){var t=this.sentUpdates.get(e);return t&&t>Date.now()-this.typingTimeout?Promise.resolve():(this.sentUpdates.set(e,Date.now()),this._send(e))}},{key:"_send",value:function(e){var t=this;$A.trace("Sending typing indicator");var n=this.configuration.links.typing,r="ChannelSid=".concat(e);return this.services.twilsockClient.post(n,{"Content-Type":"application/x-www-form-urlencoded"},r,this.configuration.productId).then((function(e){e.body.hasOwnProperty("typing_timeout")&&(t.serviceTypingTimeout=1e3*e.body.typing_timeout)})).catch((function(e){throw $A.error("Failed to send typing indicator:",e),e}))}}]),e}(),PushNotification=Na((function PushNotification(e){Ua(this,PushNotification),this.title=e.title||null,this.body=e.body||null,this.sound=e.sound||null,this.badge=e.badge||null,this.action=e.action||null,this.type=e.type||null,this.data=e.data||{}})),JA="3.0.1-rc.103";function KA(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function HA(e,t,n){return HA=KA()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&Ia(i,n.prototype),i},HA.apply(null,arguments)}function YA(e){var t="function"==typeof Map?new Map:void 0;return YA=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return HA(e,arguments,ja(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),Ia(r,e)},YA(e)}function QA(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 XA(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?QA(Object(n),!0).forEach((function(t){Ma(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):QA(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function ZA(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}var ej=function(e){return e.replace(/(^\/+|\/+$)/g,"")},tj=function(e){Oa(n,e);var t=ZA(n);function n(e){return Ua(this,n),t.call(this,e)}return Na(n)}(YA(Error)),nj=function(){function e(t,n,r){Ua(this,e),this._serviceUrl=t,this._services=n,this._productId=r}var t,n,r;return Na(e,[{key:"_preProcessUrl",value:function(e){var t=ej(e);return/^https?:\/\//.test(e)?t:"".concat(ej(this._serviceUrl),"/").concat(t)}},{key:"_makeRequest",value:(r=Ra(Gc.mark((function e(t,n,r,i){var a,s,o,u;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:a=this._preProcessUrl(n),s=XA({"Content-Type":"application/json; charset=utf-8"},i||{}),e.t0=t,e.next="get"===e.t0?5:"post"===e.t0?11:"delete"===e.t0?15:19;break;case 5:return u=a,r&&(u+="?"+Object.entries(r).map((function(e){return e.map(encodeURIComponent).join("=")})).join("&")),e.next=9,this._services.transport.get(u,s,this._productId);case 9:case 13:case 17:return o=e.sent,e.abrupt("break",19);case 11:return e.next=13,this._services.transport.post(a,s,JSON.stringify(r),this._productId);case 15:return e.next=17,this._services.transport.delete(a,s,{},this._productId);case 19:if(!(o.status.code<200||o.status.code>=300)){e.next=21;break}throw new Error("Request responded with a non-success code ".concat(o.status.code));case 21:return e.abrupt("return",o);case 22:case"end":return e.stop()}}),e,this)}))),function(e,t,n,i){return r.apply(this,arguments)})},{key:"fetchResource",value:(n=Ra(Gc.mark((function e(t,n){var r,i,a=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=new Fg({min:50,max:1600,maxAttemptsCount:6}),e.prev=2,e.next=5,r.run(Ra(Gc.mark((function e(){var r,i,s;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,a._makeRequest("get",t,n);case 3:return r=e.sent,e.abrupt("return",{type:"success",data:r.body});case 7:if(e.prev=7,e.t0=e.catch(0),404!==(null===e.t0||void 0===e.t0||null===(i=e.t0.body)||void 0===i?void 0:i.status)||50530!==(null===e.t0||void 0===e.t0||null===(s=e.t0.body)||void 0===s?void 0:s.code)){e.next=11;break}return e.abrupt("return",{type:"noMetadata"});case 11:throw e.t0;case 12:case"end":return e.stop()}}),e,null,[[0,7]])}))));case 5:i=e.sent,e.next=11;break;case 8:throw e.prev=8,e.t0=e.catch(2),new Error('Fetch resource from "'.concat(t,'" failed.'));case 11:if("noMetadata"!==i.type){e.next=13;break}throw new tj("No metadata found.");case 13:return e.abrupt("return",i.data);case 14:case"end":return e.stop()}}),e,null,[[2,8]])}))),function(e,t){return n.apply(this,arguments)})},{key:"mutateResource",value:(t=Ra(Gc.mark((function e(t,n,r){var i;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._makeRequest(t,n,r,{"X-Twilio-Mutation-Id":Cb.v4()});case 2:if(202!==(i=e.sent).status.code){e.next=7;break}return e.next=6,this.fetchResource(i.body.resource_url);case 6:return e.abrupt("return",e.sent);case 7:return e.abrupt("return",i.body);case 8:case"end":return e.stop()}}),e,this)}))),function(e,n,r){return t.apply(this,arguments)})}]),e}(),rj=Cn,ij=bm,aj=o,sj=E,oj=gm.exports.onFreeze,uj=Object.freeze;rj({target:"Object",stat:!0,forced:aj((function(){uj(1)})),sham:!ij},{freeze:function(e){return uj&&sj(e)?uj(oj(e)):e}});var cj=function(){function e(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:100,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:5e3;Ua(this,e),Ma(this,"_cachedTemplates",null),this._services=t,this._pageSize=n,this._cacheTtlMs=r}var t,n;return Na(e,[{key:"getContentTemplates",value:(n=Ra(Gc.mark((function e(){var t,n,r,i,a,s,o,u=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null===this._cachedTemplates){e.next=2;break}return e.abrupt("return",this._cachedTemplates);case 2:return e.next=4,this._fetchContentTemplates();case 4:t=e.sent,n=mm(t,2),r=n[0],i=n[1],a=r;case 9:if(null===i){e.next=19;break}return e.next=12,this._fetchContentTemplates(i);case 12:s=e.sent,o=mm(s,2),r=o[0],i=o[1],a=[].concat(Ty(a),Ty(r)),e.next=9;break;case 19:return this._cachedTemplates=Object.freeze(a),setTimeout((function(){u._cachedTemplates=null}),this._cacheTtlMs),e.abrupt("return",a);case 22:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"_fetchContentTemplates",value:(t=Ra(Gc.mark((function e(t){var n,r;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return(n=new mh("Client/v2/ContentTemplates")).arg("PageSize",this._pageSize),void 0!==t&&n.arg("PageToken",t),e.next=6,this._services.commandExecutor.fetchResource(n.build());case 6:return r=e.sent,e.abrupt("return",[r.templates.map((function(e){return new fA(e)})),r.meta.next_token]);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return t.apply(this,arguments)})}]),e}();function lj(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return fj(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return fj(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function fj(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var dj=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(Ua(this,t),!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}return Na(t,[{key:"_set",value:function(e,t){if(this.cache.set(e,t),this._size++,this._size>=this.maxSize){if(this._size=0,"function"==typeof this.onEviction){var n,r=lj(this.oldCache.entries());try{for(r.s();!(n=r.n()).done;){var i=mm(n.value,2),a=i[0],s=i[1];this.onEviction(a,s)}}catch(e){r.e(e)}finally{r.f()}}this.oldCache=this.cache,this.cache=new Map}}},{key:"get",value:function(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){var t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}},{key:"set",value:function(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}},{key:"has",value:function(e){return this.cache.has(e)||this.oldCache.has(e)}},{key:"peek",value:function(e){return this.cache.has(e)?this.cache.get(e):this.oldCache.has(e)?this.oldCache.get(e):void 0}},{key:"delete",value:function(e){var t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}},{key:"clear",value:function(){this.cache.clear(),this.oldCache.clear(),this._size=0}},{key:"keys",value:Gc.mark((function e(){var t,n,r,i;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=lj(this),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=9;break}return r=mm(n.value,1),i=r[0],e.next=7,i;case 7:e.next=3;break;case 9:e.next=14;break;case 11:e.prev=11,e.t0=e.catch(1),t.e(e.t0);case 14:return e.prev=14,t.f(),e.finish(14);case 17:case"end":return e.stop()}}),e,this,[[1,11,14,17]])}))},{key:"values",value:Gc.mark((function e(){var t,n,r,i;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=lj(this),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=9;break}return r=mm(n.value,2),i=r[1],e.next=7,i;case 7:e.next=3;break;case 9:e.next=14;break;case 11:e.prev=11,e.t0=e.catch(1),t.e(e.t0);case 14:return e.prev=14,t.f(),e.finish(14);case 17:case"end":return e.stop()}}),e,this,[[1,11,14,17]])}))},{key:e,value:Gc.mark((function e(){var t,n,r,i,a,s,o,u;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:t=lj(this.cache),e.prev=1,t.s();case 3:if((n=t.n()).done){e.next=9;break}return r=n.value,e.next=7,r;case 7:e.next=3;break;case 9:e.next=14;break;case 11:e.prev=11,e.t0=e.catch(1),t.e(e.t0);case 14:return e.prev=14,t.f(),e.finish(14);case 17:i=lj(this.oldCache),e.prev=18,i.s();case 20:if((a=i.n()).done){e.next=28;break}if(s=a.value,o=mm(s,1),u=o[0],this.cache.has(u)){e.next=26;break}return e.next=26,s;case 26:e.next=20;break;case 28:e.next=33;break;case 30:e.prev=30,e.t1=e.catch(18),i.e(e.t1);case 33:return e.prev=33,i.f(),e.finish(33);case 36:case"end":return e.stop()}}),e,this,[[1,11,14,17],[18,30,33,36]])}))},{key:"size",get:function(){var e,t=0,n=lj(this.oldCache.keys());try{for(n.s();!(e=n.n()).done;){var r=e.value;this.cache.has(r)||t++}}catch(e){n.e(e)}finally{n.f()}return Math.min(this._size+t,this.maxSize)}}]),t}(Symbol.iterator),pj=dj,hj=Na((function e(t,n){Ua(this,e),this.type=t,this.data=n,Object.freeze(n)})),vj=function(){function e(t,n){Ua(this,e),this._services=t,this._configuration=n,this._cache=new pj({maxSize:n.channelMetadataCacheCapacity})}var t;return Na(e,[{key:"getChannelMetadata",value:(t=Ra(Gc.mark((function e(t,n){var r,i,a,s,o;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r="".concat(t,",").concat(n),!(i=this._cache.get(r))){e.next=4;break}return e.abrupt("return",i.item);case 4:return a="".concat(this._configuration.links.conversations,"/").concat(t,"/Messages/").concat(n,"/ChannelMetadata"),e.prev=5,e.next=8,this._services.commandExecutor.fetchResource(a);case 8:s=e.sent,e.next=17;break;case 11:if(e.prev=11,e.t0=e.catch(5),!(e.t0 instanceof tj)){e.next=16;break}return this._cache.set(r,{item:null}),e.abrupt("return",null);case 16:throw new Error(e.t0);case 17:return o=new hj(s.type,s.data),this._cache.set(r,{item:o}),e.abrupt("return",o);case 20:case"end":return e.stop()}}),e,this,[[5,11]])}))),function(e,n){return t.apply(this,arguments)})}]),e}();function yj(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(!e)return;if("string"==typeof e)return mj(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);"Object"===n&&e.constructor&&(n=e.constructor.name);if("Map"===n||"Set"===n)return Array.from(e);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return mj(e,t)}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==n.return||n.return()}finally{if(o)throw a}}}}function mj(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}var gj,bj,wj=Na((function e(t){Ua(this,e),Ma(this,"type","email"),this.messageSid=t.message_sid,this.level=t.level,this.name=t.name,this.address=t.address})),kj=Na((function e(t){Ua(this,e),this.type=t.type,this.messageSid=t.message_sid,this.rawData=JSON.stringify(t)})),xj=function(){function e(t,n){Ua(this,e),this._services=t,this._configuration=n,this._cache=new pj({maxSize:n.messageRecipientsCacheCapacity})}var t,n;return Na(e,[{key:"getRecipientsFromMessage",value:(n=Ra(Gc.mark((function e(t,n){var r,i,a,s,o,u=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r="".concat(t,",").concat(n),!(i=this._cache.get(r))){e.next=4;break}return e.abrupt("return",i.item);case 4:return a=new mh(this._configuration.links.conversations).path(t).path("MessageRecipients").arg("MessageSid",n).build(),e.next=7,this._services.commandExecutor.fetchResource(a);case 7:return s=e.sent,(o=s.message_recipients.map((function(e){return u._wrapResponse(e)}))).length>0&&this._cache.set(r,{item:o}),e.abrupt("return",o);case 11:case"end":return e.stop()}}),e,this)}))),function(e,t){return n.apply(this,arguments)})},{key:"getRecipientsFromConversation",value:(t=Ra(Gc.mark((function e(t,n){var r,i,a,s,o,u,c,l,f,d,p,h,v=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return a=new mh(this._configuration.links.conversations).path(t).path("MessageRecipients").arg("PageToken",null!==(r=null==n?void 0:n.pageToken)&&void 0!==r?r:"").arg("PageSize",null!==(i=null==n?void 0:n.pageSize)&&void 0!==i?i:"").build(),e.next=3,this._services.commandExecutor.fetchResource(a);case 3:s=e.sent,o=s.message_recipients.map((function(e){return v._wrapResponse(e)})),u=yj(o);try{for(u.s();!(c=u.n()).done;)d=c.value,p="".concat(t,",").concat(d.messageSid),h=null!==(l=null===(f=this._cache.get(p))||void 0===f?void 0:f.item)&&void 0!==l?l:[],this._cache.set(p,{item:[].concat(Ty(h),[d])})}catch(e){u.e(e)}finally{u.f()}return e.abrupt("return",new nA(o,(function(e,n){return v.getRecipientsFromConversation(t,{pageToken:e,pageSize:n})}),s.meta.previous_token,s.meta.next_token));case 8:case"end":return e.stop()}}),e,this)}))),function(e,n){return t.apply(this,arguments)})},{key:"_wrapResponse",value:function(e){return"email"===e.type?new wj(e):new kj(e)}}]),e}();function _j(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 Sj(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?_j(Object(n),!0).forEach((function(t){Ma(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_j(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Ej(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,r=ja(e);if(t){var i=ja(this).constructor;n=Reflect.construct(r,arguments,i)}else n=r.apply(this,arguments);return Aa(this,n)}}var Tj=Na((function e(){Ua(this,e)}));return e.Client=(gj=function(e){Oa(Client,e);var t,n,r,i,a,s,o,u,c,l,f,d,p,h,v,y,m=Ej(Client);function Client(e){var t,n,r,i,a,s,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(Ua(this,Client),Ma(Ca(s=m.call(this)),"version",JA),Ma(Ca(s),"connectionState","unknown"),Ma(Ca(s),"parsePushNotification",bj.parsePushNotification),s._fpaToken=null!=e?e:"",s._options=null!=o?o:{},!s._options.disableDeepClone){var u=Sj(Sj({},s._options),{},{transport:void 0,twilsockClient:void 0});(u=ph(u)).transport=s._options.transport,u.twilsockClient=s._options.twilsockClient,s._options=u}s._options.logLevel=null!==(t=s._options.logLevel)&&void 0!==t?t:"silent",bj._logger.setLevel(s._options.logLevel);var c=s._options.productId="ip_messaging";if(s._options.clientMetadata=s._options.clientMetadata||{},s._options.clientMetadata.hasOwnProperty("type")||(s._options.clientMetadata.type="conversations"),s._options.clientMetadata.hasOwnProperty("sdk")||(s._options.clientMetadata.sdk="JS",s._options.clientMetadata.sdkv=JA),s._options.Sync=s._options.Sync||{},void 0===s._options.Sync.enableSessionStorage&&(s._options.Sync.enableSessionStorage=!0),s._options.region&&(s._options.Sync.region=s._options.region),!e)throw new Error("A valid Twilio token should be provided");s._services=new Tj,s._myself=new User("","",null,s._services);var l=!s._options.twilsockClient;if(!s._options.initRegistrations){var f=new $g.InitRegistration(c);bj.populateInitRegistrations(f),s._options.initRegistrations=[f]}s._services.twilsockClient=s._options.twilsockClient=null!==(n=s._options.twilsockClient)&&void 0!==n?n:new $g.TwilsockClient(e,c,s._options),s._services.twilsockClient.on("tokenAboutToExpire",(function(){return s.emit("tokenAboutToExpire")})),s._services.twilsockClient.on("tokenExpired",(function(){return s.emit("tokenExpired")})),s._services.twilsockClient.on("connectionError",(function(e){return s.emit("connectionError",e)})),s._services.twilsockClient.on("stateChanged",(function(e){bj._logger.debug("Handling stateChanged for ConversationsClient: new state ".concat(e)),e!==s.connectionState&&(s.connectionState=e,s.emit("connectionStateChanged",s.connectionState))})),s._services.transport=s._options.transport=null!==(r=s._options.transport)&&void 0!==r?r:s._options.twilsockClient,s._services.notificationClient=s._options.notificationsClient=null!==(i=s._options.notificationsClient)&&void 0!==i?i:new LE.Notifications(e,s._options),s._services.syncClient=s._options.syncClient=null!==(a=s._options.syncClient)&&void 0!==a?a:new vC(e,s._options);var d=(null==o?void 0:o.Chat)||(null==o?void 0:o.IPMessaging)||o||{},p=d.region||(null==o?void 0:o.region),h=d.apiUri||d.typingUri||"https://aim.".concat(p||"us1",".twilio.com");s._services.commandExecutor=new nj(h,{transport:s._options.transport},c),s._services.contentClient=new cj(s._services);var v=function(e){s._rejectEnsureReady(e),s.emit("stateChanged","failed"),s.emit("initFailed",{error:e})},y=function(){v({terminal:!0,message:"Twilsock has disconnected."})};return s._services.twilsockClient.once("connectionError",v),s._services.twilsockClient.once("disconnected",y),s._services.twilsockClient.once("connected",Ra(Gc.mark((function e(){var t,n;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return bj._logger.debug("ConversationsClient started INITIALIZING"),s._services.twilsockClient.off("connectionError",v),s._services.twilsockClient.off("disconnected",y),e.prev=3,t="conversations.client.startup",s._services.twilsockClient.addPartialTelemetryEvent(new $g.TelemetryEventDescription(t,"Conversations client startup",new Date),t,$g.TelemetryPoint.Start),e.next=8,s._initialize();case 8:s._services.twilsockClient.addPartialTelemetryEvent(new $g.TelemetryEventDescription("","",new Date),t,$g.TelemetryPoint.End),e.next=17;break;case 11:e.prev=11,e.t0=e.catch(3),n={terminal:!0,message:e.t0.message},s._rejectEnsureReady(n),s.emit("stateChanged","failed"),s.emit("initFailed",{error:n});case 17:case"end":return e.stop()}}),e,null,[[3,11]])})))),s._ensureReady=new Promise((function(e,t){s._resolveEnsureReady=e,s._rejectEnsureReady=t})).catch((function(){})),l&&s._services.twilsockClient.connect(),s}return Na(Client,[{key:"user",get:function(){return this._myself}},{key:"reachabilityEnabled",get:function(){if(!this._configuration)throw new Error("Reachability information could not yet be accessed as the client has not yet been initialized. Subscribe to the 'stateChanged' event to properly react to the client initialization.");return this._configuration.reachabilityEnabled}},{key:"token",get:function(){return this._fpaToken}},{key:"shutdown",value:(y=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.next=4,this._services.twilsockClient.disconnect();case 4:case"end":return e.stop()}}),e,this)}))),function(){return y.apply(this,arguments)})},{key:"updateToken",value:(v=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:if(bj._logger.info("updateToken"),this._fpaToken!==t){e.next=5;break}return e.abrupt("return",this);case 5:return e.next=7,this._services.twilsockClient.updateToken(t);case 7:return e.next=9,this._services.notificationClient.updateToken(t);case 9:return e.next=11,this._services.mcsClient.updateToken(t);case 11:return this._fpaToken=t,e.abrupt("return",this);case 13:case"end":return e.stop()}}),e,this)}))),function(e){return v.apply(this,arguments)})},{key:"getConversationBySid",value:(h=Ra(Gc.mark((function e(t){var n;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return e.next=6,this._conversationsEntity.getConversation(t);case 6:if(n=e.sent){e.next=12;break}return e.next=10,this.peekConversationBySid(t);case 10:(n=e.sent)&&uA("The method getConversationBySid is deprecated to retrieve conversations you're not part of. Use peekConversationBySid instead.");case 12:if(n){e.next=14;break}throw new Error("Conversation with SID ".concat(t," was not found."));case 14:return e.abrupt("return",n);case 15:case"end":return e.stop()}}),e,this)}))),function(e){return h.apply(this,arguments)})},{key:"peekConversationBySid",value:(p=Ra(Gc.mark((function e(t){var n;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.next=4,this._conversationsEntity.peekConversation(t);case 4:if(n=e.sent){e.next=7;break}throw new Error("Conversation with SID ".concat(t," was not found."));case 7:return e.abrupt("return",n);case 8:case"end":return e.stop()}}),e,this)}))),function(e){return p.apply(this,arguments)})},{key:"getConversationByUniqueName",value:(d=Ra(Gc.mark((function e(t){var n;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.next=4,this._conversationsEntity.myConversationsRead.promise;case 4:return e.next=6,this._conversationsEntity.getConversationByUniqueName(t);case 6:if(n=e.sent){e.next=9;break}throw new Error("Conversation with unique name ".concat(t," was not found."));case 9:return e.abrupt("return",n);case 10:case"end":return e.stop()}}),e,this)}))),function(e){return d.apply(this,arguments)})},{key:"getSubscribedConversations",value:(f=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.abrupt("return",this._conversationsPromise.then((function(e){return e.getConversations()})));case 3:case"end":return e.stop()}}),e,this)}))),function(){return f.apply(this,arguments)})},{key:"createConversation",value:(l=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return t=t||{},e.abrupt("return",this._conversationsPromise.then((function(e){return e.addConversation(t)})));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return l.apply(this,arguments)})},{key:"setPushRegistrationId",value:(c=Ra(Gc.mark((function e(t,n){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return this._subscribeToPushNotifications(t),this._services.notificationClient.setPushRegistrationId(t,n),e.next=6,this._services.notificationClient.commitChanges();case 6:case"end":return e.stop()}}),e,this)}))),function(e,t){return c.apply(this,arguments)})},{key:"unsetPushRegistrationId",value:(u=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return this._unsubscribeFromPushNotifications(t),e.next=5,this._services.notificationClient.commitChanges();case 5:case"end":return e.stop()}}),e,this)}))),function(e){return u.apply(this,arguments)})},{key:"removePushRegistrations",value:(o=Ra(Gc.mark((function e(t,n){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.notificationClient.removeRegistrations(t,n);case 2:case"end":return e.stop()}}),e,this)}))),function(e,t){return o.apply(this,arguments)})},{key:"handlePushNotification",value:(s=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:bj._logger.debug("handlePushNotification, notificationPayload=",t),this.emit("pushNotification",bj.parsePushNotification(t));case 4:case"end":return e.stop()}}),e,this)}))),function(e){return s.apply(this,arguments)})},{key:"getUser",value:(a=Ra(Gc.mark((function e(t){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.abrupt("return",this._services.users.getUser(t));case 3:case"end":return e.stop()}}),e,this)}))),function(e){return a.apply(this,arguments)})},{key:"getSubscribedUsers",value:(i=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.abrupt("return",this._services.users.getSubscribedUsers());case 3:case"end":return e.stop()}}),e,this)}))),function(){return i.apply(this,arguments)})},{key:"getTemporaryContentUrlsForMediaSids",value:function(e){var t=this;return new mC.CancellablePromise(function(){var n=Ra(Gc.mark((function n(r,i,a){var s,o;return Gc.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(t._services.mcsClient&&e){n.next=3;break}return i(new Error("Media Content Service is unavailable")),n.abrupt("return");case 3:return s=t._services.mcsClient.mediaSetGetContentUrls(e),a((function(){s.cancel()})),n.prev=5,n.next=8,s;case 8:o=n.sent,r(o),n.next=15;break;case 12:n.prev=12,n.t0=n.catch(5),i(n.t0);case 15:case"end":return n.stop()}}),n,null,[[5,12]])})));return function(e,t,r){return n.apply(this,arguments)}}())}},{key:"getTemporaryContentUrlsForMedia",value:function(e){var t=e.map((function(e){return e.sid}));return this.getTemporaryContentUrlsForMediaSids(t)}},{key:"getContentTemplates",value:(r=Ra(Gc.mark((function e(){return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._ensureReady;case 2:return e.next=4,this._services.contentClient.getContentTemplates();case 4:return e.abrupt("return",e.sent);case 5:case"end":return e.stop()}}),e,this)}))),function(){return r.apply(this,arguments)})},{key:"_initialize",value:(n=Ra(Gc.mark((function e(){var t,n=this;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,this._services.commandExecutor.fetchResource("Client/v2/Configuration");case 2:return t=e.sent,this._configuration=new Bf(this._options,t,bj._logger),this._services.channelMetadataClient=new vj(this._services,this._configuration),this._services.messageRecipientsClient=new xj(this._services,this._configuration),this._myself._resolveInitialization(this._configuration,this._configuration.userIdentity,this._configuration.userInfo,!0),this._services.typingIndicator=new VA(this.getConversationBySid.bind(this),this._configuration,this._services),this._services.network=new Wg(this._configuration,this._services),this._services.users=new GA(this._myself,this._configuration,this._services),this._services.users.on("userSubscribed",(function(e){n.emit("userSubscribed",e)})),this._services.users.on("userUpdated",(function(e){return n.emit("userUpdated",e)})),this._services.users.on("userUnsubscribed",(function(e){n.emit("userUnsubscribed",e)})),this._conversationsEntity=new UA(this._configuration,this._services),this._conversationsEntity.on("conversationAdded",(function(e){n.emit("conversationAdded",e)})),this._conversationsEntity.on("conversationRemoved",(function(e){n.emit("conversationRemoved",e)})),this._conversationsEntity.on("conversationJoined",(function(e){n.emit("conversationJoined",e)})),this._conversationsEntity.on("conversationLeft",(function(e){n.emit("conversationLeft",e)})),this._conversationsEntity.on("conversationUpdated",(function(e){return n.emit("conversationUpdated",e)})),this._conversationsEntity.on("participantJoined",(function(e){n.emit("participantJoined",e)})),this._conversationsEntity.on("participantLeft",(function(e){n.emit("participantLeft",e)})),this._conversationsEntity.on("participantUpdated",(function(e){return n.emit("participantUpdated",e)})),this._conversationsEntity.on("messageAdded",(function(e){return n.emit("messageAdded",e)})),this._conversationsEntity.on("messageUpdated",(function(e){return n.emit("messageUpdated",e)})),this._conversationsEntity.on("messageRemoved",(function(e){return n.emit("messageRemoved",e)})),this._conversationsEntity.on("typingStarted",(function(e){return n.emit("typingStarted",e)})),this._conversationsEntity.on("typingEnded",(function(e){return n.emit("typingEnded",e)})),this._conversationsPromise=this._conversationsEntity.fetchConversations().then((function(){return n._conversationsEntity})).catch((function(e){throw e})),e.next=30,this._services.users.myself._ensureFetched();case 30:bj._supportedPushChannels.forEach((function(e){return n._subscribeToPushNotifications(e)})),this._services.typingIndicator.initialize(),this._services.mcsClient=new mC.McsClient(this._fpaToken,this._configuration.links.mediaService,this._configuration.links.mediaSetService,Sj(Sj({},this._options),{},{transport:void 0})),this._resolveEnsureReady(),this.emit("stateChanged","initialized"),this.emit("initialized");case 36:case"end":return e.stop()}}),e,this)}))),function(){return n.apply(this,arguments)})},{key:"_subscribeToPushNotifications",value:function(e){var t=this;[Gg.NEW_MESSAGE,Gg.ADDED_TO_CONVERSATION,Gg.REMOVED_FROM_CONVERSATION,Gg.TYPING_INDICATOR,Gg.CONSUMPTION_UPDATE].forEach((function(n){t._services.notificationClient.subscribe(e,n)}))}},{key:"_unsubscribeFromPushNotifications",value:function(e){var t=this;[Gg.NEW_MESSAGE,Gg.ADDED_TO_CONVERSATION,Gg.REMOVED_FROM_CONVERSATION,Gg.TYPING_INDICATOR,Gg.CONSUMPTION_UPDATE].forEach((function(n){t._services.notificationClient.unsubscribe(e,n)}))}}],[{key:"create",value:(t=Ra(Gc.mark((function e(t,n){var r;return Gc.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null==n||!n.twilsockClient){e.next=2;break}throw new Error("Obsolete usage of ConversationsClient.create() factory method: if you pass twilsock from the outside then you must use ConversationsClient constructor and be prepared to work with uninitialized client.");case 2:return r=new bj(t,n),e.next=5,r._ensureReady;case 5:return e.abrupt("return",r);case 6:case"end":return e.stop()}}),e)}))),function(e,n){return t.apply(this,arguments)})},{key:"parsePushNotification",value:function(e){if(bj._logger.debug("parsePushNotification, notificationPayload=",e),void 0!==e.aps){if(!e.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var t,n,r,i=bj._parsePushNotificationChatData(e),a=e.aps,s=null;if("string"==typeof a.alert)t=a.alert||null;else t=(null===(n=a.alert)||void 0===n?void 0:n.body)||null,s=(null===(r=a.alert)||void 0===r?void 0:r.title)||null;return new PushNotification({title:s,body:t,sound:a.sound||null,badge:a.badge||null,action:a.category||null,type:e.twi_message_type,data:i})}if(void 0!==e.data){var o=e.data;if(!o.twi_message_type)throw new Error("Provided push notification payload does not contain Programmable Chat push notification type");var u=bj._parsePushNotificationChatData(e.data);return new PushNotification({title:o.twi_title||null,body:o.twi_body||null,sound:o.twi_sound||null,badge:null,action:o.twi_action||null,type:o.twi_message_type,data:u})}throw new Error("Provided push notification payload is not Programmable Chat notification")}},{key:"_parsePushNotificationChatData",value:function(e){var t={};for(var n in bj._supportedPushDataFields){var r=e[n];if(null!=r)if("message_index"!==n&&"media_count"!==n){if("media"!==n)t[bj._supportedPushDataFields[n]]=r;else if("string"==typeof r)try{t[bj._supportedPushDataFields[n]]=JSON.parse(r)}catch(e){bj._logger.debug("Media message notification parsing error")}}else{var i=hh(r);null!==i&&(t[bj._supportedPushDataFields[n]]=i)}}return t}},{key:"populateInitRegistrations",value:function(e){e.populateInitRegistrations([Gg.TYPING_INDICATOR]),vC.populateInitRegistrations(e)}}]),Client}(dm),Ma(gj,"conversationAdded","conversationAdded"),Ma(gj,"conversationJoined","conversationJoined"),Ma(gj,"conversationLeft","conversationLeft"),Ma(gj,"conversationRemoved","conversationRemoved"),Ma(gj,"conversationUpdated","conversationUpdated"),Ma(gj,"participantJoined","participantJoined"),Ma(gj,"participantLeft","participantLeft"),Ma(gj,"participantUpdated","participantUpdated"),Ma(gj,"messageAdded","messageAdded"),Ma(gj,"messageRemoved","messageRemoved"),Ma(gj,"messageUpdated","messageUpdated"),Ma(gj,"tokenAboutToExpire","tokenAboutToExpire"),Ma(gj,"tokenExpired","tokenExpired"),Ma(gj,"typingEnded","typingEnded"),Ma(gj,"typingStarted","typingStarted"),Ma(gj,"pushNotification","pushNotification"),Ma(gj,"userSubscribed","userSubscribed"),Ma(gj,"userUnsubscribed","userUnsubscribed"),Ma(gj,"userUpdated","userUpdated"),Ma(gj,"stateChanged","stateChanged"),Ma(gj,"initialized","initialized"),Ma(gj,"initFailed","initFailed"),Ma(gj,"connectionStateChanged","connectionStateChanged"),Ma(gj,"connectionError","connectionError"),Ma(gj,"version",JA),Ma(gj,"_logger",If.scope("Client")),Ma(gj,"_supportedPushChannels",["fcm","apn"]),Ma(gj,"_supportedPushDataFields",{conversation_sid:"conversationSid",conversation_title:"conversationTitle",message_sid:"messageSid",message_index:"messageIndex",media_count:"mediaCount",media:"media"}),bj=gj),Vc([oA("token"),Jc("design:type",String),Jc("design:paramtypes",[])],e.Client.prototype,"token",null),Vc([_y(my),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],e.Client.prototype,"updateToken",null),Vc([_y(my),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],e.Client.prototype,"getConversationBySid",null),Vc([_y(my),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],e.Client.prototype,"peekConversationBySid",null),Vc([_y(my),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],e.Client.prototype,"getConversationByUniqueName",null),Vc([_y(["undefined",by("conversation options",{friendlyName:["string","undefined"],isPrivate:["boolean","undefined"],uniqueName:["string","undefined"]})]),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Promise)],e.Client.prototype,"createConversation",null),Vc([_y(vy("fcm","apn"),"string"),Jc("design:type",Function),Jc("design:paramtypes",[String,String]),Jc("design:returntype",Promise)],e.Client.prototype,"setPushRegistrationId",null),Vc([_y(vy("fcm","apn")),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],e.Client.prototype,"unsetPushRegistrationId",null),Vc([_y(vy("fcm","apn"),my),Jc("design:type",Function),Jc("design:paramtypes",[String,String]),Jc("design:returntype",Promise)],e.Client.prototype,"removePushRegistrations",null),Vc([_y(wy),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",Promise)],e.Client.prototype,"handlePushNotification",null),Vc([_y(my),Jc("design:type",Function),Jc("design:paramtypes",[String]),Jc("design:returntype",Promise)],e.Client.prototype,"getUser",null),Vc([_y(yy("strings","string")),Jc("design:type",Function),Jc("design:paramtypes",[Array]),Jc("design:returntype",mC.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMediaSids",null),Vc([_y(yy("media",Media)),Jc("design:type",Function),Jc("design:paramtypes",[Array]),Jc("design:returntype",mC.CancellablePromise)],e.Client.prototype,"getTemporaryContentUrlsForMedia",null),Vc([oA("Client.create()","new Client()"),_y("string",["undefined",wy]),Jc("design:type",Function),Jc("design:paramtypes",[String,Object]),Jc("design:returntype",Promise)],e.Client,"create",null),Vc([xy(wy),Jc("design:type",Function),Jc("design:paramtypes",[Object]),Jc("design:returntype",PushNotification)],e.Client,"parsePushNotification",null),e.Client=bj=Vc([ky(my,[wy,"undefined"]),Jc("design:paramtypes",[String,Object])],e.Client),e.AggregatedDeliveryReceipt=AggregatedDeliveryReceipt,e.CancellablePromise=mC.CancellablePromise,e.ChannelMetadata=hj,e.ContentTemplate=fA,e.ContentTemplateVariable=ContentTemplateVariable,e.Conversation=Conversation,e.DetailedDeliveryReceipt=DetailedDeliveryReceipt,e.EmailRecipientDescriptor=wj,e.Media=Media,e.Message=Message,e.MessageBuilder=EA,e.NotificationTypes=Gg,e.Participant=Participant,e.PushNotification=PushNotification,e.RestPaginator=nA,e.UnknownRecipientDescriptor=kj,e.UnsentMessage=SA,e.User=User,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
|