@foxford/services 1.2.7 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +2 -43
  2. package/api/interceptors/responseFail.js +1 -1
  3. package/api/interceptors/responseFail.mjs +1 -1
  4. package/captcha/cloudflare/index.js +1 -1
  5. package/captcha/cloudflare/index.mjs +1 -1
  6. package/captcha/google/index.js +1 -1
  7. package/captcha/google/index.mjs +1 -1
  8. package/dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.js +1 -0
  9. package/dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.mjs +1 -0
  10. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-util.js +1 -0
  11. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-util.mjs +1 -0
  12. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-web-lock.js +1 -0
  13. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-web-lock.mjs +1 -0
  14. package/dependencies/broadcast-channel/dist/esbrowser/leader-election.js +1 -0
  15. package/dependencies/broadcast-channel/dist/esbrowser/leader-election.mjs +1 -0
  16. package/dependencies/broadcast-channel/dist/esbrowser/method-chooser.js +1 -0
  17. package/dependencies/broadcast-channel/dist/esbrowser/method-chooser.mjs +1 -0
  18. package/dependencies/broadcast-channel/dist/esbrowser/methods/indexed-db.js +1 -0
  19. package/dependencies/broadcast-channel/dist/esbrowser/methods/indexed-db.mjs +1 -0
  20. package/dependencies/broadcast-channel/dist/esbrowser/methods/localstorage.js +1 -0
  21. package/dependencies/broadcast-channel/dist/esbrowser/methods/localstorage.mjs +1 -0
  22. package/dependencies/broadcast-channel/dist/esbrowser/methods/native.js +1 -0
  23. package/dependencies/broadcast-channel/dist/esbrowser/methods/native.mjs +1 -0
  24. package/dependencies/broadcast-channel/dist/esbrowser/methods/simulate.js +1 -0
  25. package/dependencies/broadcast-channel/dist/esbrowser/methods/simulate.mjs +1 -0
  26. package/dependencies/broadcast-channel/dist/esbrowser/options.js +1 -0
  27. package/dependencies/broadcast-channel/dist/esbrowser/options.mjs +1 -0
  28. package/dependencies/broadcast-channel/dist/esbrowser/util.js +1 -0
  29. package/dependencies/broadcast-channel/dist/esbrowser/util.mjs +1 -0
  30. package/dependencies/centrifuge/build/index.js +1 -0
  31. package/dependencies/centrifuge/build/index.mjs +1 -0
  32. package/dependencies/oblivious-set/dist/es/index.js +1 -0
  33. package/dependencies/oblivious-set/dist/es/index.mjs +1 -0
  34. package/dependencies/unload/dist/es/browser.js +1 -0
  35. package/dependencies/unload/dist/es/browser.mjs +1 -0
  36. package/dependencies/unload/dist/es/index.js +1 -0
  37. package/dependencies/unload/dist/es/index.mjs +1 -0
  38. package/dependencies/unload/dist/es/node.js +1 -0
  39. package/dependencies/unload/dist/es/node.mjs +1 -0
  40. package/index.d.ts +61 -5
  41. package/index.js +1 -1
  42. package/index.js.flow +59 -11
  43. package/index.mjs +1 -1
  44. package/package.json +35 -1
  45. package/socket/index.js +1 -0
  46. package/socket/index.mjs +1 -0
package/README.md CHANGED
@@ -8,47 +8,6 @@
8
8
  Сервис для работы с капчей.
9
9
  В зависимости от данных с бэка используется или Google-капча, или Cloudflare Turnstile
10
10
 
11
- ## Recaptcha Service
12
-
13
- Сервис для работы с Google-капчей.
14
-
15
- > Поставщиком сервиса рекапчи является `@foxford/foxford-js-sdk` (FoxfordService)
16
-
17
- Пример использования:
18
-
19
- ```js static
20
- import { Foxford } from '@foxford/foxford-js-sdk'
21
-
22
- const FoxfordService = new Foxford({
23
- recaptchaConfig: {
24
- locale: 'ru',
25
- sitekey: 'captchaSecretKey',
26
- },
27
- })
28
-
29
- const RecaptchaService: RecaptchaServiceInterface = FoxfordService.recaptcha
30
- ```
31
-
32
- А далее в необходимом месте:
33
-
34
- ```js static
35
- async function submitHandler() {
36
- const tokenPayload = await RecaptchaService.execute() // <TOKEN>
37
- }
38
- ```
39
-
40
- > В `stoege` сервис рекапчи доступен в `'services/recaptcha'`
41
-
42
- Пример использования в `stoege`
43
-
44
- ```js static
45
- import { RecaptchaService } from 'services/recaptcha'
46
-
47
- async function submitHandler() {
48
- const tokenPayload = await RecaptchaService.execute() // <TOKEN>
49
- }
50
- ```
51
-
52
11
  ---
53
12
 
54
13
  ## API Service
@@ -65,7 +24,7 @@ async function submitHandler() {
65
24
 
66
25
  ### Как обесепечивается единобразное использование HTTP-клиента?
67
26
 
68
- > Точкой правды, поставщиком HTTP-клиента является `@foxford/foxford-js-sdk (FoxfordService)`
27
+ > Точкой правды, поставщиком HTTP-клиента является `@foxford/foxford-js-sdk (FoxfordService)`
69
28
  > Все "потребители" должны использовать HTTP-клиент из `FoxfordService`
70
29
 
71
30
  `FoxfordService` использует пакет сервисов `@foxford/services` для получения инстанса Api
@@ -74,7 +33,7 @@ async function submitHandler() {
74
33
 
75
34
  1. `FoxfordService.foxApi` - инстанс Api, ориентированный на использование внутренних сервисов Фоксфорда, в нем:
76
35
 
77
- - Используются `Api Interceptors`
36
+ - Используются `Api Interceptors`
78
37
  По умолчанию используются два обязательных перехватчика(`camelize` и `referrer`) и один опциональный(`captcha`) в `interceptors.request`, это:
79
38
  - `camelize` - для преобразования кейса в ответе запроса
80
39
  - `referrer` - для проброса реферрера в запросе
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/objectSpread2.js');var t=[422,401];exports.ResponseInterceptorFail=function(r){var{config:s=null,response:a=null}=r;if(null===s||null===a)return Promise.reject(r);var u=s;t.includes(a.status)&&(u._retry=true);var o=e({errorText:r.toString(),headers:a.headers,status:a.status,statusText:a.statusText},'object'==typeof a.data?a.data:{data:a.data});return Promise.reject(o)};
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/objectSpread2.js');exports.ResponseInterceptorFail=function(t){var{config:r=null,response:s=null}=t;if(null===r||null===s)return Promise.reject(t);var a=e({data:s.data,errorText:t.toString(),headers:s.headers,originalRequest:r,status:s.status,statusText:s.statusText},'object'==typeof s.data?s.data:{});return Promise.reject(a)};
@@ -1 +1 @@
1
- import e from'./../../dependencies/@babel/runtime/helpers/esm/objectSpread2.mjs';var t=[422,401];function r(r){var{config:a=null,response:s=null}=r;if(null===a||null===s)return Promise.reject(r);var u=a;t.includes(s.status)&&(u._retry=true);var o=e({errorText:r.toString(),headers:s.headers,status:s.status,statusText:s.statusText},'object'==typeof s.data?s.data:{data:s.data});return Promise.reject(o)}export{r as ResponseInterceptorFail};
1
+ import e from'./../../dependencies/@babel/runtime/helpers/esm/objectSpread2.mjs';function t(t){var{config:r=null,response:a=null}=t;if(null===r||null===a)return Promise.reject(t);var s=e({data:a.data,errorText:t.toString(),headers:a.headers,originalRequest:r,status:a.status,statusText:a.statusText},'object'==typeof a.data?a.data:{});return Promise.reject(s)}export{t as ResponseInterceptorFail};
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var r=require('../error.js');var t=require('../log.js');var n=require('./constants.js');var o=require('./style.js');var l=require('./template.js');var i=function(){};class CloudflareTurnstile{constructor(e){var{sitekey:r,locale:t,notify:n,onRenderCaptcha:o,onSuccessChallenge:l,onErrorChallenge:a,onWarnChallenge:s,onBeforeInteractiveChallenge:c,onAfterInteractiveChallenge:d}=e;this.sitekey=null,this.locale='ru',this.provider='cloudflare_turnstile',this.container=null,this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.onBeforeInteractiveChallenge=void 0,this.onAfterInteractiveChallenge=void 0,this.notifyHandler=null!=n?n:i,this.sitekey=null!=r?r:null,this.onRenderCaptcha=null!=o?o:i,this.onSuccessChallenge=null!=l?l:i,this.onErrorChallenge=null!=a?a:i,this.onWarnChallenge=null!=s?s:i,this.onBeforeInteractiveChallenge=null!=c?c:i,this.onAfterInteractiveChallenge=null!=d?d:i,t&&(this.locale=t),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(n.CONTAINER_NODE_ID)||(document.body.insertAdjacentHTML('beforeend',l),document.body.insertAdjacentHTML('beforeend',"<style>".concat(o,"</style>")),this.container=document.getElementById(n.CONTAINER_NODE_ID))}appendScript(r){return e((function*(){if('string'!=typeof r||''===r)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=r,document.body&&document.body.appendChild(e),new Promise(((r,t)=>{e.addEventListener('load',(()=>{r(true)})),e.addEventListener('error',(()=>{t()}))}))}))()}show(){var e;null===(e=this.container)||void 0===e||e.classList.add('fox-cf-turnstile--showing'),this.bodyScrollLock()}hide(){var e,r;null===(e=this.container)||void 0===e||e.classList.remove('fox-cf-turnstile--show'),null===(r=this.container)||void 0===r||r.classList.remove('fox-cf-turnstile--showing'),this.bodyScrollUnlock()}loadScript(){var t=this;return e((function*(){if(window.turnstile)return Promise.resolve(window.turnstile);var n=function(){var r=e((function*(){return yield t.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return function(){return r.apply(this,arguments)}}();return new Promise(((e,o)=>{window.onloadTurnstileCallback=()=>{t.turnstileReady(),window.turnstile?e(window.turnstile):o(new r.CaptchaError('Cloudflare Turnstile is not available'))},n().catch((()=>o(new r.CaptchaError('Could not load Cloudflare Turnstile'))))}))}))()}turnstileReady(){var e,r;t.log('Cloudflare Turnstile is ready',window.turnstile),null===(e=this.container)||void 0===e||null===(r=e.querySelector('.fox-cf-turnstile__loader'))||void 0===r||r.remove()}normalizeLocation(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:'').substring(0,31).replace(/\//g,'_')}bodyScrollLock(){var e=document.body;e.style.setProperty('--st',"-".concat(document.documentElement.scrollTop,"px")),e.classList.add('fox-cf-turnstile__noscroll')}bodyScrollUnlock(){document.body.classList.remove('fox-cf-turnstile__noscroll')}renderWidget(r){var o=this;return e((function*(){return new Promise(((e,l)=>{var i;var a='';function s(){var e;null===(e=window.turnstile)||void 0===e||e.reset(a),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(a)}),500)}a=null===(i=window.turnstile)||void 0===i?void 0:i.render("#".concat(n.RENDER_NODE_ID),{action:o.normalizeLocation(null==r?void 0:r.location),'after-interactive-callback':()=>{t.log("after-interactive-callback"),o.onAfterInteractiveChallenge(o.provider)},'before-interactive-callback':()=>{t.log("before-interactive-callback"),o.onBeforeInteractiveChallenge(o.provider),o.show()},callback:r=>{t.log("Challenge Success"),o.hide(),e(r),s()},'error-callback':e=>{l(e),s()},'expired-callback':()=>{o.hide(),l('expired'),s()},language:o.locale,sitekey:o.sitekey,theme:'light','timeout-callback':()=>{o.hide(),l('timeout'),s()},'unsupported-callback':()=>{l('110500'),s()}})}))}))()}errorHandler(e){t.log("Captcha error with code:",e);var r=[...CloudflareTurnstile.NO_RETRY_ERROR_CODES];if('string'==typeof e){var n=e;switch(true){case n.startsWith('110500'):r=r.filter((e=>!e.startsWith('110500'))),this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.');break;case n.startsWith('110600'):r=r.filter((e=>!e.startsWith('110600'))),this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case n.startsWith('110510'):r=r.filter((e=>!e.startsWith('110510'))),this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку');break;case n.startsWith('200010'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.");break;case n.startsWith('200100'):r=r.filter((e=>!e.startsWith('200100'))),this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.');break;case n.startsWith('300'):case n.startsWith('600'):r=r.filter((e=>!e.startsWith('300')||!e.startsWith('600'))),this.notify('Потвердите еще раз что вы человек')}r.some((e=>n.startsWith(e)))&&this.notify("Что-то пошло не так, код ошибки — ".concat(n,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время."))}else this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}execute(n){var o=this;return e((function*(){if(o.sitekey){t.log('Load cloudflare script');try{yield o.loadScript()}catch(t){var e=t instanceof r.CaptchaError?t:new r.CaptchaError('Could not load captcha with error: '+t.toString());throw o.onErrorChallenge(o.provider,e),e}if(!window.turnstile){var l=new r.CaptchaError('Cloudflare Turnstile is not available in window');throw o.onErrorChallenge(o.provider,l),l}try{t.log('Render turnstile widget'),o.onRenderCaptcha(o.provider);var i=yield o.renderWidget(n);return o.onSuccessChallenge(o.provider),i}catch(e){if(o.errorHandler(e),'string'!=typeof e){var a=new r.CaptchaError('Could not execute captcha with error: '+e.toString());throw o.onErrorChallenge(o.provider,a),a}if(['110200','110100','110110'].some((r=>e.startsWith(r)))){var s=new r.CaptchaError('Invalid sitekey or domain is not allowed');throw s.code=e,o.onErrorChallenge(o.provider,s),s}if(CloudflareTurnstile.NO_RETRY_ERROR_CODES.some((r=>e.startsWith(r)))){var c=new r.CaptchaError("Captcha challenge is failed");c.reason='error',c.capture=false,c.code=e,o.onErrorChallenge(o.provider,c)}else{var d=new r.CaptchaError("Captcha challenge has error");d.reason=['timeout','expired'].includes(e)?e:'error',d.capture=false,d.code=e,o.onWarnChallenge(o.provider,d)}}}}))()}}CloudflareTurnstile.DEBUG=false,CloudflareTurnstile.NO_RETRY_ERROR_CODES=['100','105','106','110100','110110','110200','110420','110430','110500','110510','120','200010','200100'],exports.CloudflareTurnstile=CloudflareTurnstile;
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var r=require('./constants.js');var t=require('./style.js');var n=require('./template.js');var o=require('../error.js');var l=require('../log.js');var i=function(){};class CloudflareTurnstile{constructor(e){var{sitekey:r,locale:t,notify:n,onRenderCaptcha:o,onSuccessChallenge:l,onErrorChallenge:a,onWarnChallenge:s,onBeforeInteractiveChallenge:c,onAfterInteractiveChallenge:d}=e;this.sitekey=null,this.locale='ru',this.provider='cloudflare_turnstile',this.container=null,this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.onBeforeInteractiveChallenge=void 0,this.onAfterInteractiveChallenge=void 0,this.notifyHandler=null!=n?n:i,this.sitekey=null!=r?r:null,this.onRenderCaptcha=null!=o?o:i,this.onSuccessChallenge=null!=l?l:i,this.onErrorChallenge=null!=a?a:i,this.onWarnChallenge=null!=s?s:i,this.onBeforeInteractiveChallenge=null!=c?c:i,this.onAfterInteractiveChallenge=null!=d?d:i,t&&(this.locale=t),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(r.CONTAINER_NODE_ID)||(document.body.insertAdjacentHTML('beforeend',n),document.body.insertAdjacentHTML('beforeend',"<style>".concat(t,"</style>")),this.container=document.getElementById(r.CONTAINER_NODE_ID))}appendScript(r){return e((function*(){if('string'!=typeof r||''===r)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=r,document.body&&document.body.appendChild(e),new Promise(((r,t)=>{e.addEventListener('load',(()=>{r(true)})),e.addEventListener('error',(()=>{t()}))}))}))()}show(){var e;null===(e=this.container)||void 0===e||e.classList.add('fox-cf-turnstile--showing'),this.bodyScrollLock()}hide(){var e,r;null===(e=this.container)||void 0===e||e.classList.remove('fox-cf-turnstile--show'),null===(r=this.container)||void 0===r||r.classList.remove('fox-cf-turnstile--showing'),this.bodyScrollUnlock()}loadScript(){var r=this;return e((function*(){if(window.turnstile)return Promise.resolve(window.turnstile);var t=function(){var t=e((function*(){return yield r.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return function(){return t.apply(this,arguments)}}();return new Promise(((e,n)=>{window.onloadTurnstileCallback=()=>{r.turnstileReady(),window.turnstile?e(window.turnstile):n(new o.CaptchaError('Cloudflare Turnstile is not available'))},t().catch((()=>n(new o.CaptchaError('Could not load Cloudflare Turnstile'))))}))}))()}turnstileReady(){var e,r;l.log('Cloudflare Turnstile is ready',window.turnstile),null===(e=this.container)||void 0===e||null===(r=e.querySelector('.fox-cf-turnstile__loader'))||void 0===r||r.remove()}normalizeLocation(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:'').substring(0,31).replace(/\//g,'_')}bodyScrollLock(){var e=document.body;e.style.setProperty('--st',"-".concat(document.documentElement.scrollTop,"px")),e.classList.add('fox-cf-turnstile__noscroll')}bodyScrollUnlock(){document.body.classList.remove('fox-cf-turnstile__noscroll')}renderWidget(t){var n=this;return e((function*(){return new Promise(((e,o)=>{var i;var a='';function s(){var e;null===(e=window.turnstile)||void 0===e||e.reset(a),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(a)}),500)}a=null===(i=window.turnstile)||void 0===i?void 0:i.render("#".concat(r.RENDER_NODE_ID),{action:n.normalizeLocation(null==t?void 0:t.location),'after-interactive-callback':()=>{l.log("after-interactive-callback"),n.onAfterInteractiveChallenge(n.provider)},'before-interactive-callback':()=>{l.log("before-interactive-callback"),n.onBeforeInteractiveChallenge(n.provider),n.show()},callback:r=>{l.log("Challenge Success"),n.hide(),e(r),s()},'error-callback':e=>{o(e),s()},'expired-callback':()=>{n.hide(),o('expired'),s()},language:n.locale,sitekey:n.sitekey,theme:'light','timeout-callback':()=>{n.hide(),o('timeout'),s()},'unsupported-callback':()=>{o('110500'),s()}})}))}))()}errorHandler(e){l.log("Captcha error with code:",e);var r=[...CloudflareTurnstile.NO_RETRY_ERROR_CODES];if('string'==typeof e){var t=e;switch(true){case t.startsWith('110500'):r=r.filter((e=>!e.startsWith('110500'))),this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.');break;case t.startsWith('110600'):r=r.filter((e=>!e.startsWith('110600'))),this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case t.startsWith('110510'):r=r.filter((e=>!e.startsWith('110510'))),this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку');break;case t.startsWith('200010'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.");break;case t.startsWith('200100'):r=r.filter((e=>!e.startsWith('200100'))),this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.');break;case t.startsWith('300'):case t.startsWith('600'):r=r.filter((e=>!e.startsWith('300')||!e.startsWith('600'))),this.notify('Потвердите еще раз что вы человек')}r.some((e=>t.startsWith(e)))&&this.notify("Что-то пошло не так, код ошибки — ".concat(t,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время."))}else this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}execute(r){var t=this;return e((function*(){if(t.sitekey){l.log('Load cloudflare script');try{yield t.loadScript()}catch(r){var e=r instanceof o.CaptchaError?r:new o.CaptchaError('Could not load captcha with error: '+r.toString());throw t.onErrorChallenge(t.provider,e),e}if(!window.turnstile){var n=new o.CaptchaError('Cloudflare Turnstile is not available in window');throw t.onErrorChallenge(t.provider,n),n}try{l.log('Render turnstile widget'),t.onRenderCaptcha(t.provider);var i=yield t.renderWidget(r);return t.onSuccessChallenge(t.provider),i}catch(e){if(t.errorHandler(e),'string'!=typeof e){var a=new o.CaptchaError('Could not execute captcha with error: '+e.toString());throw t.onErrorChallenge(t.provider,a),a}if(['110200','110100','110110'].some((r=>e.startsWith(r)))){var s=new o.CaptchaError('Invalid sitekey or domain is not allowed');throw s.code=e,t.onErrorChallenge(t.provider,s),s}if(CloudflareTurnstile.NO_RETRY_ERROR_CODES.some((r=>e.startsWith(r)))){var c=new o.CaptchaError("Captcha challenge is failed");c.reason='error',c.capture=false,c.code=e,t.onErrorChallenge(t.provider,c)}else{var d=new o.CaptchaError("Captcha challenge has error");d.reason=['timeout','expired'].includes(e)?e:'error',d.capture=false,d.code=e,t.onWarnChallenge(t.provider,d)}}}}))()}}CloudflareTurnstile.DEBUG=false,CloudflareTurnstile.NO_RETRY_ERROR_CODES=['100','105','106','110100','110110','110200','110420','110430','110500','110510','120','200010','200100'],exports.CloudflareTurnstile=CloudflareTurnstile;
@@ -1 +1 @@
1
- import e from'./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{CaptchaError as t}from'../error.mjs';import{log as r}from'../log.mjs';import{CONTAINER_NODE_ID as n,RENDER_NODE_ID as o}from'./constants.mjs';import i from'./style.mjs';import l from'./template.mjs';var a=function(){};class CloudflareTurnstile{constructor(e){var{sitekey:t,locale:r,notify:n,onRenderCaptcha:o,onSuccessChallenge:i,onErrorChallenge:l,onWarnChallenge:s,onBeforeInteractiveChallenge:c,onAfterInteractiveChallenge:d}=e;this.sitekey=null,this.locale='ru',this.provider='cloudflare_turnstile',this.container=null,this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.onBeforeInteractiveChallenge=void 0,this.onAfterInteractiveChallenge=void 0,this.notifyHandler=null!=n?n:a,this.sitekey=null!=t?t:null,this.onRenderCaptcha=null!=o?o:a,this.onSuccessChallenge=null!=i?i:a,this.onErrorChallenge=null!=l?l:a,this.onWarnChallenge=null!=s?s:a,this.onBeforeInteractiveChallenge=null!=c?c:a,this.onAfterInteractiveChallenge=null!=d?d:a,r&&(this.locale=r),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(n)||(document.body.insertAdjacentHTML('beforeend',l),document.body.insertAdjacentHTML('beforeend',"<style>".concat(i,"</style>")),this.container=document.getElementById(n))}appendScript(t){return e((function*(){if('string'!=typeof t||''===t)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=t,document.body&&document.body.appendChild(e),new Promise(((t,r)=>{e.addEventListener('load',(()=>{t(true)})),e.addEventListener('error',(()=>{r()}))}))}))()}show(){var e;null===(e=this.container)||void 0===e||e.classList.add('fox-cf-turnstile--showing'),this.bodyScrollLock()}hide(){var e,t;null===(e=this.container)||void 0===e||e.classList.remove('fox-cf-turnstile--show'),null===(t=this.container)||void 0===t||t.classList.remove('fox-cf-turnstile--showing'),this.bodyScrollUnlock()}loadScript(){var r=this;return e((function*(){if(window.turnstile)return Promise.resolve(window.turnstile);var n=function(){var t=e((function*(){return yield r.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return function(){return t.apply(this,arguments)}}();return new Promise(((e,o)=>{window.onloadTurnstileCallback=()=>{r.turnstileReady(),window.turnstile?e(window.turnstile):o(new t('Cloudflare Turnstile is not available'))},n().catch((()=>o(new t('Could not load Cloudflare Turnstile'))))}))}))()}turnstileReady(){var e,t;r('Cloudflare Turnstile is ready',window.turnstile),null===(e=this.container)||void 0===e||null===(t=e.querySelector('.fox-cf-turnstile__loader'))||void 0===t||t.remove()}normalizeLocation(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:'').substring(0,31).replace(/\//g,'_')}bodyScrollLock(){var e=document.body;e.style.setProperty('--st',"-".concat(document.documentElement.scrollTop,"px")),e.classList.add('fox-cf-turnstile__noscroll')}bodyScrollUnlock(){document.body.classList.remove('fox-cf-turnstile__noscroll')}renderWidget(t){var n=this;return e((function*(){return new Promise(((e,i)=>{var l;var a='';function s(){var e;null===(e=window.turnstile)||void 0===e||e.reset(a),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(a)}),500)}a=null===(l=window.turnstile)||void 0===l?void 0:l.render("#".concat(o),{action:n.normalizeLocation(null==t?void 0:t.location),'after-interactive-callback':()=>{r("after-interactive-callback"),n.onAfterInteractiveChallenge(n.provider)},'before-interactive-callback':()=>{r("before-interactive-callback"),n.onBeforeInteractiveChallenge(n.provider),n.show()},callback:t=>{r("Challenge Success"),n.hide(),e(t),s()},'error-callback':e=>{i(e),s()},'expired-callback':()=>{n.hide(),i('expired'),s()},language:n.locale,sitekey:n.sitekey,theme:'light','timeout-callback':()=>{n.hide(),i('timeout'),s()},'unsupported-callback':()=>{i('110500'),s()}})}))}))()}errorHandler(e){r("Captcha error with code:",e);var t=[...CloudflareTurnstile.NO_RETRY_ERROR_CODES];if('string'==typeof e){var n=e;switch(true){case n.startsWith('110500'):t=t.filter((e=>!e.startsWith('110500'))),this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.');break;case n.startsWith('110600'):t=t.filter((e=>!e.startsWith('110600'))),this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case n.startsWith('110510'):t=t.filter((e=>!e.startsWith('110510'))),this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку');break;case n.startsWith('200010'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.");break;case n.startsWith('200100'):t=t.filter((e=>!e.startsWith('200100'))),this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.');break;case n.startsWith('300'):case n.startsWith('600'):t=t.filter((e=>!e.startsWith('300')||!e.startsWith('600'))),this.notify('Потвердите еще раз что вы человек')}t.some((e=>n.startsWith(e)))&&this.notify("Что-то пошло не так, код ошибки — ".concat(n,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время."))}else this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}execute(n){var o=this;return e((function*(){if(o.sitekey){r('Load cloudflare script');try{yield o.loadScript()}catch(r){var e=r instanceof t?r:new t('Could not load captcha with error: '+r.toString());throw o.onErrorChallenge(o.provider,e),e}if(!window.turnstile){var i=new t('Cloudflare Turnstile is not available in window');throw o.onErrorChallenge(o.provider,i),i}try{r('Render turnstile widget'),o.onRenderCaptcha(o.provider);var l=yield o.renderWidget(n);return o.onSuccessChallenge(o.provider),l}catch(e){if(o.errorHandler(e),'string'!=typeof e){var a=new t('Could not execute captcha with error: '+e.toString());throw o.onErrorChallenge(o.provider,a),a}if(['110200','110100','110110'].some((t=>e.startsWith(t)))){var s=new t('Invalid sitekey or domain is not allowed');throw s.code=e,o.onErrorChallenge(o.provider,s),s}if(CloudflareTurnstile.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){var c=new t("Captcha challenge is failed");c.reason='error',c.capture=false,c.code=e,o.onErrorChallenge(o.provider,c)}else{var d=new t("Captcha challenge has error");d.reason=['timeout','expired'].includes(e)?e:'error',d.capture=false,d.code=e,o.onWarnChallenge(o.provider,d)}}}}))()}}CloudflareTurnstile.DEBUG=false,CloudflareTurnstile.NO_RETRY_ERROR_CODES=['100','105','106','110100','110110','110200','110420','110430','110500','110510','120','200010','200100'];export{CloudflareTurnstile};
1
+ import e from'./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{CONTAINER_NODE_ID as t,RENDER_NODE_ID as r}from'./constants.mjs';import n from'./style.mjs';import o from'./template.mjs';import{CaptchaError as i}from'../error.mjs';import{log as l}from'../log.mjs';var a=function(){};class CloudflareTurnstile{constructor(e){var{sitekey:t,locale:r,notify:n,onRenderCaptcha:o,onSuccessChallenge:i,onErrorChallenge:l,onWarnChallenge:s,onBeforeInteractiveChallenge:c,onAfterInteractiveChallenge:d}=e;this.sitekey=null,this.locale='ru',this.provider='cloudflare_turnstile',this.container=null,this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.onBeforeInteractiveChallenge=void 0,this.onAfterInteractiveChallenge=void 0,this.notifyHandler=null!=n?n:a,this.sitekey=null!=t?t:null,this.onRenderCaptcha=null!=o?o:a,this.onSuccessChallenge=null!=i?i:a,this.onErrorChallenge=null!=l?l:a,this.onWarnChallenge=null!=s?s:a,this.onBeforeInteractiveChallenge=null!=c?c:a,this.onAfterInteractiveChallenge=null!=d?d:a,r&&(this.locale=r),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(t)||(document.body.insertAdjacentHTML('beforeend',o),document.body.insertAdjacentHTML('beforeend',"<style>".concat(n,"</style>")),this.container=document.getElementById(t))}appendScript(t){return e((function*(){if('string'!=typeof t||''===t)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=t,document.body&&document.body.appendChild(e),new Promise(((t,r)=>{e.addEventListener('load',(()=>{t(true)})),e.addEventListener('error',(()=>{r()}))}))}))()}show(){var e;null===(e=this.container)||void 0===e||e.classList.add('fox-cf-turnstile--showing'),this.bodyScrollLock()}hide(){var e,t;null===(e=this.container)||void 0===e||e.classList.remove('fox-cf-turnstile--show'),null===(t=this.container)||void 0===t||t.classList.remove('fox-cf-turnstile--showing'),this.bodyScrollUnlock()}loadScript(){var t=this;return e((function*(){if(window.turnstile)return Promise.resolve(window.turnstile);var r=function(){var r=e((function*(){return yield t.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return function(){return r.apply(this,arguments)}}();return new Promise(((e,n)=>{window.onloadTurnstileCallback=()=>{t.turnstileReady(),window.turnstile?e(window.turnstile):n(new i('Cloudflare Turnstile is not available'))},r().catch((()=>n(new i('Could not load Cloudflare Turnstile'))))}))}))()}turnstileReady(){var e,t;l('Cloudflare Turnstile is ready',window.turnstile),null===(e=this.container)||void 0===e||null===(t=e.querySelector('.fox-cf-turnstile__loader'))||void 0===t||t.remove()}normalizeLocation(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:'').substring(0,31).replace(/\//g,'_')}bodyScrollLock(){var e=document.body;e.style.setProperty('--st',"-".concat(document.documentElement.scrollTop,"px")),e.classList.add('fox-cf-turnstile__noscroll')}bodyScrollUnlock(){document.body.classList.remove('fox-cf-turnstile__noscroll')}renderWidget(t){var n=this;return e((function*(){return new Promise(((e,o)=>{var i;var a='';function s(){var e;null===(e=window.turnstile)||void 0===e||e.reset(a),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(a)}),500)}a=null===(i=window.turnstile)||void 0===i?void 0:i.render("#".concat(r),{action:n.normalizeLocation(null==t?void 0:t.location),'after-interactive-callback':()=>{l("after-interactive-callback"),n.onAfterInteractiveChallenge(n.provider)},'before-interactive-callback':()=>{l("before-interactive-callback"),n.onBeforeInteractiveChallenge(n.provider),n.show()},callback:t=>{l("Challenge Success"),n.hide(),e(t),s()},'error-callback':e=>{o(e),s()},'expired-callback':()=>{n.hide(),o('expired'),s()},language:n.locale,sitekey:n.sitekey,theme:'light','timeout-callback':()=>{n.hide(),o('timeout'),s()},'unsupported-callback':()=>{o('110500'),s()}})}))}))()}errorHandler(e){l("Captcha error with code:",e);var t=[...CloudflareTurnstile.NO_RETRY_ERROR_CODES];if('string'==typeof e){var r=e;switch(true){case r.startsWith('110500'):t=t.filter((e=>!e.startsWith('110500'))),this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.');break;case r.startsWith('110600'):t=t.filter((e=>!e.startsWith('110600'))),this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case r.startsWith('110510'):t=t.filter((e=>!e.startsWith('110510'))),this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку');break;case r.startsWith('200010'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.");break;case r.startsWith('200100'):t=t.filter((e=>!e.startsWith('200100'))),this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.');break;case r.startsWith('300'):case r.startsWith('600'):t=t.filter((e=>!e.startsWith('300')||!e.startsWith('600'))),this.notify('Потвердите еще раз что вы человек')}t.some((e=>r.startsWith(e)))&&this.notify("Что-то пошло не так, код ошибки — ".concat(r,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время."))}else this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}execute(t){var r=this;return e((function*(){if(r.sitekey){l('Load cloudflare script');try{yield r.loadScript()}catch(t){var e=t instanceof i?t:new i('Could not load captcha with error: '+t.toString());throw r.onErrorChallenge(r.provider,e),e}if(!window.turnstile){var n=new i('Cloudflare Turnstile is not available in window');throw r.onErrorChallenge(r.provider,n),n}try{l('Render turnstile widget'),r.onRenderCaptcha(r.provider);var o=yield r.renderWidget(t);return r.onSuccessChallenge(r.provider),o}catch(e){if(r.errorHandler(e),'string'!=typeof e){var a=new i('Could not execute captcha with error: '+e.toString());throw r.onErrorChallenge(r.provider,a),a}if(['110200','110100','110110'].some((t=>e.startsWith(t)))){var s=new i('Invalid sitekey or domain is not allowed');throw s.code=e,r.onErrorChallenge(r.provider,s),s}if(CloudflareTurnstile.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){var c=new i("Captcha challenge is failed");c.reason='error',c.capture=false,c.code=e,r.onErrorChallenge(r.provider,c)}else{var d=new i("Captcha challenge has error");d.reason=['timeout','expired'].includes(e)?e:'error',d.capture=false,d.code=e,r.onWarnChallenge(r.provider,d)}}}}))()}}CloudflareTurnstile.DEBUG=false,CloudflareTurnstile.NO_RETRY_ERROR_CODES=['100','105','106','110100','110110','110200','110420','110430','110500','110510','120','200010','200100'];export{CloudflareTurnstile};
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var r=require('../../utils/uuid.js');var a=require('../error.js');var t=require('../log.js');var o=require('./constants.js');var n=function(){};class GoogleCaptcha{constructor(e){var{sitekey:r,locale:a,notify:t,onRenderCaptcha:o,onSuccessChallenge:c,onWarnChallenge:i,onErrorChallenge:l}=e;this.sitekey=null,this.locale='ru',this.container=null,this.provider='recaptcha',this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.sitekey=null!=r?r:null,this.notifyHandler=null!=t?t:n,this.onRenderCaptcha=null!=o?o:n,this.onSuccessChallenge=null!=c?c:n,this.onWarnChallenge=null!=i?i:n,this.onErrorChallenge=null!=l?l:n,a&&(this.locale=a),this.addDomElements(),GoogleCaptcha.DEBUG&&(window.gr=this)}recaptchaReady(){t.log('Google recaptcha is ready',window.grecaptcha)}addDomElements(){if(!this.container&&!document.getElementById(o.NODE_ID)){document.body.insertAdjacentHTML('beforeend',"<div id=\"".concat(o.NODE_ID,"\"></div>"));var e=document.getElementById(o.NODE_ID);e.style.display='none',this.container=e}}getGrecaptchaCallbackNames(){return{error:"".concat(GoogleCaptcha.ERROR_FUNC_NAME),expired:"".concat(GoogleCaptcha.EXPIRED_FUNC_NAME),resolve:"".concat(GoogleCaptcha.RESOLVE_FUNC_NAME)}}appendScript(r){return e((function*(){if('string'!=typeof r||''===r)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=r,document.body&&document.body.appendChild(e),new Promise(((r,a)=>{e.addEventListener('load',(()=>{r(true)})),e.addEventListener('error',(()=>{a()}))}))}))()}loadScript(){var r=this;return e((function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);var t=function(){var a=e((function*(){return yield r.appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(r.locale,"&onload=onloadRecaptchaCallback"))}));return function(){return a.apply(this,arguments)}}();return new Promise(((e,o)=>{window.onloadRecaptchaCallback=()=>{r.recaptchaReady(),window.grecaptcha?e(window.grecaptcha):o(new a.CaptchaError('Recaptcha is not available'))},t().catch((()=>o(new a.CaptchaError('Could not load Recaptcha'))))}))}))()}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}errorHandler(e){switch(t.log("Recaptcha error:",e),e){case'expired':this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case'closed':this.notify('Вы не завершили прохождение проверки. Попробуйте еще раз.');break;case'timeout':this.notify('Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.');break;default:this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}}detectCaptchaChallengeIsShown(){return new Promise((function(e){var r=document.body;var a=new MutationObserver((function(r){r.forEach((r=>{if(r.addedNodes.length){var t=r.addedNodes[0];if(!t)return;if(t.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){var o=t.firstChild;o&&(a.disconnect(),e(o))}}}))}));a.observe(r,{attributeOldValue:false,attributes:false,characterData:false,characterDataOldValue:false,childList:true,subtree:false})}))}renderWidget(e){return new Promise(((e,a)=>{var t,n,c;var i=document.createElement('div');var l="".concat(o.NODE_ID,"_").concat(r.generateUUID());i.id=l,null===(t=document.getElementById(o.NODE_ID))||void 0===t||t.appendChild(i);var d=this.getGrecaptchaCallbackNames();var s=NaN;function h(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{i.remove()}),1e3)}this.detectCaptchaChallengeIsShown().then((e=>{if(e.parentElement){var r=new MutationObserver((function(){var t,o;'hidden'!==(null===(t=e.parentElement)||void 0===t?void 0:t.style.visibility)||null!==(o=window.grecaptcha)&&void 0!==o&&o.getResponse(s)||(r.disconnect(),a('closed'),h())}));r.observe(e.parentElement,{attributeFilter:['style'],attributes:true})}})),window[d.resolve]=()=>{var r;var a=null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(s);e(null!=a?a:''),h()},window[d.error]=()=>{a('error'),h()},window[d.expired]=()=>{a('expired'),h()},s=null===(n=window.grecaptcha)||void 0===n?void 0:n.render(l,{callback:d.resolve,'error-callback':d.error,'expired-callback':d.expired,sitekey:this.sitekey,size:'invisible'});var p=null===(c=window.grecaptcha)||void 0===c?void 0:c.execute(s);if(!p)return a(new Error('cannot call method execute from grecaptcha')),void h();p.catch((e=>{a(e instanceof Error?e:new Error(e.toString())),h()}))}))}execute(r){var o=this;return e((function*(){if(o.sitekey){t.log('Load recaptcha script');try{yield o.loadScript()}catch(r){var e=r instanceof a.CaptchaError?r:new a.CaptchaError('Could not load captcha with error: '+r.toString());throw o.onErrorChallenge(o.provider,e),e}if(!window.grecaptcha){var n=new a.CaptchaError('Recaptcha is not available in window');throw o.onErrorChallenge(o.provider,n),n}try{t.log('Render Recaptcha widget'),o.onRenderCaptcha(o.provider);var c=yield o.renderWidget(r);return o.onSuccessChallenge(o.provider),c}catch(e){if(o.errorHandler(e),'string'!=typeof e){var i=new a.CaptchaError('Could not execute captcha with error: '+e.toString());throw o.onErrorChallenge(o.provider,i),i}if('expired'===e){var l=new a.CaptchaError("Challenge or token expired");l.reason='expired',l.capture=false,o.onWarnChallenge(o.provider,l)}if('error'===e){var d=new a.CaptchaError("Error during captcha execution");d.reason='error',d.capture=false,o.onErrorChallenge(o.provider,d)}}}}))()}}GoogleCaptcha.RESOLVE_FUNC_NAME='grecaptcha_resolved',GoogleCaptcha.ERROR_FUNC_NAME='grecaptcha_error',GoogleCaptcha.EXPIRED_FUNC_NAME='grecaptcha_expired',GoogleCaptcha.DEBUG=false,exports.GoogleCaptcha=GoogleCaptcha;
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var r=require('./constants.js');var a=require('../../utils/uuid.js');var t=require('../error.js');var o=require('../log.js');var n=function(){};class GoogleCaptcha{constructor(e){var{sitekey:r,locale:a,notify:t,onRenderCaptcha:o,onSuccessChallenge:c,onWarnChallenge:i,onErrorChallenge:l}=e;this.sitekey=null,this.locale='ru',this.container=null,this.provider='recaptcha',this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.sitekey=null!=r?r:null,this.notifyHandler=null!=t?t:n,this.onRenderCaptcha=null!=o?o:n,this.onSuccessChallenge=null!=c?c:n,this.onWarnChallenge=null!=i?i:n,this.onErrorChallenge=null!=l?l:n,a&&(this.locale=a),this.addDomElements(),GoogleCaptcha.DEBUG&&(window.gr=this)}recaptchaReady(){o.log('Google recaptcha is ready',window.grecaptcha)}addDomElements(){if(!this.container&&!document.getElementById(r.NODE_ID)){document.body.insertAdjacentHTML('beforeend',"<div id=\"".concat(r.NODE_ID,"\"></div>"));var e=document.getElementById(r.NODE_ID);e.style.display='none',this.container=e}}getGrecaptchaCallbackNames(){return{error:"".concat(GoogleCaptcha.ERROR_FUNC_NAME),expired:"".concat(GoogleCaptcha.EXPIRED_FUNC_NAME),resolve:"".concat(GoogleCaptcha.RESOLVE_FUNC_NAME)}}appendScript(r){return e((function*(){if('string'!=typeof r||''===r)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=r,document.body&&document.body.appendChild(e),new Promise(((r,a)=>{e.addEventListener('load',(()=>{r(true)})),e.addEventListener('error',(()=>{a()}))}))}))()}loadScript(){var r=this;return e((function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);var a=function(){var a=e((function*(){return yield r.appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(r.locale,"&onload=onloadRecaptchaCallback"))}));return function(){return a.apply(this,arguments)}}();return new Promise(((e,o)=>{window.onloadRecaptchaCallback=()=>{r.recaptchaReady(),window.grecaptcha?e(window.grecaptcha):o(new t.CaptchaError('Recaptcha is not available'))},a().catch((()=>o(new t.CaptchaError('Could not load Recaptcha'))))}))}))()}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}errorHandler(e){switch(o.log("Recaptcha error:",e),e){case'expired':this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case'closed':this.notify('Вы не завершили прохождение проверки. Попробуйте еще раз.');break;case'timeout':this.notify('Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.');break;default:this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}}detectCaptchaChallengeIsShown(){return new Promise((function(e){var r=document.body;var a=new MutationObserver((function(r){r.forEach((r=>{if(r.addedNodes.length){var t=r.addedNodes[0];if(!t)return;if(t.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){var o=t.firstChild;o&&(a.disconnect(),e(o))}}}))}));a.observe(r,{attributeOldValue:false,attributes:false,characterData:false,characterDataOldValue:false,childList:true,subtree:false})}))}renderWidget(e){return new Promise(((e,t)=>{var o,n,c;var i=document.createElement('div');var l="".concat(r.NODE_ID,"_").concat(a.generateUUID());i.id=l,null===(o=document.getElementById(r.NODE_ID))||void 0===o||o.appendChild(i);var d=this.getGrecaptchaCallbackNames();var s=NaN;function h(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{i.remove()}),1e3)}this.detectCaptchaChallengeIsShown().then((e=>{if(e.parentElement){var r=new MutationObserver((function(){var a,o;'hidden'!==(null===(a=e.parentElement)||void 0===a?void 0:a.style.visibility)||null!==(o=window.grecaptcha)&&void 0!==o&&o.getResponse(s)||(r.disconnect(),t('closed'),h())}));r.observe(e.parentElement,{attributeFilter:['style'],attributes:true})}})),window[d.resolve]=()=>{var r;var a=null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(s);e(null!=a?a:''),h()},window[d.error]=()=>{t('error'),h()},window[d.expired]=()=>{t('expired'),h()},s=null===(n=window.grecaptcha)||void 0===n?void 0:n.render(l,{callback:d.resolve,'error-callback':d.error,'expired-callback':d.expired,sitekey:this.sitekey,size:'invisible'});var p=null===(c=window.grecaptcha)||void 0===c?void 0:c.execute(s);if(!p)return t(new Error('cannot call method execute from grecaptcha')),void h();p.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),h()}))}))}execute(r){var a=this;return e((function*(){if(a.sitekey){o.log('Load recaptcha script');try{yield a.loadScript()}catch(r){var e=r instanceof t.CaptchaError?r:new t.CaptchaError('Could not load captcha with error: '+r.toString());throw a.onErrorChallenge(a.provider,e),e}if(!window.grecaptcha){var n=new t.CaptchaError('Recaptcha is not available in window');throw a.onErrorChallenge(a.provider,n),n}try{o.log('Render Recaptcha widget'),a.onRenderCaptcha(a.provider);var c=yield a.renderWidget(r);return a.onSuccessChallenge(a.provider),c}catch(e){if(a.errorHandler(e),'string'!=typeof e){var i=new t.CaptchaError('Could not execute captcha with error: '+e.toString());throw a.onErrorChallenge(a.provider,i),i}if('expired'===e){var l=new t.CaptchaError("Challenge or token expired");l.reason='expired',l.capture=false,a.onWarnChallenge(a.provider,l)}if('error'===e){var d=new t.CaptchaError("Error during captcha execution");d.reason='error',d.capture=false,a.onErrorChallenge(a.provider,d)}}}}))()}}GoogleCaptcha.RESOLVE_FUNC_NAME='grecaptcha_resolved',GoogleCaptcha.ERROR_FUNC_NAME='grecaptcha_error',GoogleCaptcha.EXPIRED_FUNC_NAME='grecaptcha_expired',GoogleCaptcha.DEBUG=false,exports.GoogleCaptcha=GoogleCaptcha;
@@ -1 +1 @@
1
- import e from'./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{generateUUID as r}from'../../utils/uuid.mjs';import{CaptchaError as t}from'../error.mjs';import{log as a}from'../log.mjs';import{NODE_ID as o}from'./constants.mjs';var n=function(){};class GoogleCaptcha{constructor(e){var{sitekey:r,locale:t,notify:a,onRenderCaptcha:o,onSuccessChallenge:i,onWarnChallenge:c,onErrorChallenge:l}=e;this.sitekey=null,this.locale='ru',this.container=null,this.provider='recaptcha',this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.sitekey=null!=r?r:null,this.notifyHandler=null!=a?a:n,this.onRenderCaptcha=null!=o?o:n,this.onSuccessChallenge=null!=i?i:n,this.onWarnChallenge=null!=c?c:n,this.onErrorChallenge=null!=l?l:n,t&&(this.locale=t),this.addDomElements(),GoogleCaptcha.DEBUG&&(window.gr=this)}recaptchaReady(){a('Google recaptcha is ready',window.grecaptcha)}addDomElements(){if(!this.container&&!document.getElementById(o)){document.body.insertAdjacentHTML('beforeend',"<div id=\"".concat(o,"\"></div>"));var e=document.getElementById(o);e.style.display='none',this.container=e}}getGrecaptchaCallbackNames(){return{error:"".concat(GoogleCaptcha.ERROR_FUNC_NAME),expired:"".concat(GoogleCaptcha.EXPIRED_FUNC_NAME),resolve:"".concat(GoogleCaptcha.RESOLVE_FUNC_NAME)}}appendScript(r){return e((function*(){if('string'!=typeof r||''===r)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=r,document.body&&document.body.appendChild(e),new Promise(((r,t)=>{e.addEventListener('load',(()=>{r(true)})),e.addEventListener('error',(()=>{t()}))}))}))()}loadScript(){var r=this;return e((function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);var a=function(){var t=e((function*(){return yield r.appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(r.locale,"&onload=onloadRecaptchaCallback"))}));return function(){return t.apply(this,arguments)}}();return new Promise(((e,o)=>{window.onloadRecaptchaCallback=()=>{r.recaptchaReady(),window.grecaptcha?e(window.grecaptcha):o(new t('Recaptcha is not available'))},a().catch((()=>o(new t('Could not load Recaptcha'))))}))}))()}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}errorHandler(e){switch(a("Recaptcha error:",e),e){case'expired':this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case'closed':this.notify('Вы не завершили прохождение проверки. Попробуйте еще раз.');break;case'timeout':this.notify('Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.');break;default:this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}}detectCaptchaChallengeIsShown(){return new Promise((function(e){var r=document.body;var t=new MutationObserver((function(r){r.forEach((r=>{if(r.addedNodes.length){var a=r.addedNodes[0];if(!a)return;if(a.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){var o=a.firstChild;o&&(t.disconnect(),e(o))}}}))}));t.observe(r,{attributeOldValue:false,attributes:false,characterData:false,characterDataOldValue:false,childList:true,subtree:false})}))}renderWidget(e){return new Promise(((e,t)=>{var a,n,i;var c=document.createElement('div');var l="".concat(o,"_").concat(r());c.id=l,null===(a=document.getElementById(o))||void 0===a||a.appendChild(c);var d=this.getGrecaptchaCallbackNames();var s=NaN;function h(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{c.remove()}),1e3)}this.detectCaptchaChallengeIsShown().then((e=>{if(e.parentElement){var r=new MutationObserver((function(){var a,o;'hidden'!==(null===(a=e.parentElement)||void 0===a?void 0:a.style.visibility)||null!==(o=window.grecaptcha)&&void 0!==o&&o.getResponse(s)||(r.disconnect(),t('closed'),h())}));r.observe(e.parentElement,{attributeFilter:['style'],attributes:true})}})),window[d.resolve]=()=>{var r;var t=null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(s);e(null!=t?t:''),h()},window[d.error]=()=>{t('error'),h()},window[d.expired]=()=>{t('expired'),h()},s=null===(n=window.grecaptcha)||void 0===n?void 0:n.render(l,{callback:d.resolve,'error-callback':d.error,'expired-callback':d.expired,sitekey:this.sitekey,size:'invisible'});var p=null===(i=window.grecaptcha)||void 0===i?void 0:i.execute(s);if(!p)return t(new Error('cannot call method execute from grecaptcha')),void h();p.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),h()}))}))}execute(r){var o=this;return e((function*(){if(o.sitekey){a('Load recaptcha script');try{yield o.loadScript()}catch(r){var e=r instanceof t?r:new t('Could not load captcha with error: '+r.toString());throw o.onErrorChallenge(o.provider,e),e}if(!window.grecaptcha){var n=new t('Recaptcha is not available in window');throw o.onErrorChallenge(o.provider,n),n}try{a('Render Recaptcha widget'),o.onRenderCaptcha(o.provider);var i=yield o.renderWidget(r);return o.onSuccessChallenge(o.provider),i}catch(e){if(o.errorHandler(e),'string'!=typeof e){var c=new t('Could not execute captcha with error: '+e.toString());throw o.onErrorChallenge(o.provider,c),c}if('expired'===e){var l=new t("Challenge or token expired");l.reason='expired',l.capture=false,o.onWarnChallenge(o.provider,l)}if('error'===e){var d=new t("Error during captcha execution");d.reason='error',d.capture=false,o.onErrorChallenge(o.provider,d)}}}}))()}}GoogleCaptcha.RESOLVE_FUNC_NAME='grecaptcha_resolved',GoogleCaptcha.ERROR_FUNC_NAME='grecaptcha_error',GoogleCaptcha.EXPIRED_FUNC_NAME='grecaptcha_expired',GoogleCaptcha.DEBUG=false;export{GoogleCaptcha};
1
+ import e from'./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{NODE_ID as r}from'./constants.mjs';import{generateUUID as t}from'../../utils/uuid.mjs';import{CaptchaError as a}from'../error.mjs';import{log as o}from'../log.mjs';var n=function(){};class GoogleCaptcha{constructor(e){var{sitekey:r,locale:t,notify:a,onRenderCaptcha:o,onSuccessChallenge:i,onWarnChallenge:c,onErrorChallenge:l}=e;this.sitekey=null,this.locale='ru',this.container=null,this.provider='recaptcha',this.notifyHandler=void 0,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onErrorChallenge=void 0,this.onWarnChallenge=void 0,this.sitekey=null!=r?r:null,this.notifyHandler=null!=a?a:n,this.onRenderCaptcha=null!=o?o:n,this.onSuccessChallenge=null!=i?i:n,this.onWarnChallenge=null!=c?c:n,this.onErrorChallenge=null!=l?l:n,t&&(this.locale=t),this.addDomElements(),GoogleCaptcha.DEBUG&&(window.gr=this)}recaptchaReady(){o('Google recaptcha is ready',window.grecaptcha)}addDomElements(){if(!this.container&&!document.getElementById(r)){document.body.insertAdjacentHTML('beforeend',"<div id=\"".concat(r,"\"></div>"));var e=document.getElementById(r);e.style.display='none',this.container=e}}getGrecaptchaCallbackNames(){return{error:"".concat(GoogleCaptcha.ERROR_FUNC_NAME),expired:"".concat(GoogleCaptcha.EXPIRED_FUNC_NAME),resolve:"".concat(GoogleCaptcha.RESOLVE_FUNC_NAME)}}appendScript(r){return e((function*(){if('string'!=typeof r||''===r)throw new TypeError('src script is not defined');var e=document.createElement('script');return e.src=r,document.body&&document.body.appendChild(e),new Promise(((r,t)=>{e.addEventListener('load',(()=>{r(true)})),e.addEventListener('error',(()=>{t()}))}))}))()}loadScript(){var r=this;return e((function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);var t=function(){var t=e((function*(){return yield r.appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(r.locale,"&onload=onloadRecaptchaCallback"))}));return function(){return t.apply(this,arguments)}}();return new Promise(((e,o)=>{window.onloadRecaptchaCallback=()=>{r.recaptchaReady(),window.grecaptcha?e(window.grecaptcha):o(new a('Recaptcha is not available'))},t().catch((()=>o(new a('Could not load Recaptcha'))))}))}))()}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}errorHandler(e){switch(o("Recaptcha error:",e),e){case'expired':this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case'closed':this.notify('Вы не завершили прохождение проверки. Попробуйте еще раз.');break;case'timeout':this.notify('Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.');break;default:this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}}detectCaptchaChallengeIsShown(){return new Promise((function(e){var r=document.body;var t=new MutationObserver((function(r){r.forEach((r=>{if(r.addedNodes.length){var a=r.addedNodes[0];if(!a)return;if(a.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){var o=a.firstChild;o&&(t.disconnect(),e(o))}}}))}));t.observe(r,{attributeOldValue:false,attributes:false,characterData:false,characterDataOldValue:false,childList:true,subtree:false})}))}renderWidget(e){return new Promise(((e,a)=>{var o,n,i;var c=document.createElement('div');var l="".concat(r,"_").concat(t());c.id=l,null===(o=document.getElementById(r))||void 0===o||o.appendChild(c);var d=this.getGrecaptchaCallbackNames();var s=NaN;function h(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{c.remove()}),1e3)}this.detectCaptchaChallengeIsShown().then((e=>{if(e.parentElement){var r=new MutationObserver((function(){var t,o;'hidden'!==(null===(t=e.parentElement)||void 0===t?void 0:t.style.visibility)||null!==(o=window.grecaptcha)&&void 0!==o&&o.getResponse(s)||(r.disconnect(),a('closed'),h())}));r.observe(e.parentElement,{attributeFilter:['style'],attributes:true})}})),window[d.resolve]=()=>{var r;var t=null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(s);e(null!=t?t:''),h()},window[d.error]=()=>{a('error'),h()},window[d.expired]=()=>{a('expired'),h()},s=null===(n=window.grecaptcha)||void 0===n?void 0:n.render(l,{callback:d.resolve,'error-callback':d.error,'expired-callback':d.expired,sitekey:this.sitekey,size:'invisible'});var p=null===(i=window.grecaptcha)||void 0===i?void 0:i.execute(s);if(!p)return a(new Error('cannot call method execute from grecaptcha')),void h();p.catch((e=>{a(e instanceof Error?e:new Error(e.toString())),h()}))}))}execute(r){var t=this;return e((function*(){if(t.sitekey){o('Load recaptcha script');try{yield t.loadScript()}catch(r){var e=r instanceof a?r:new a('Could not load captcha with error: '+r.toString());throw t.onErrorChallenge(t.provider,e),e}if(!window.grecaptcha){var n=new a('Recaptcha is not available in window');throw t.onErrorChallenge(t.provider,n),n}try{o('Render Recaptcha widget'),t.onRenderCaptcha(t.provider);var i=yield t.renderWidget(r);return t.onSuccessChallenge(t.provider),i}catch(e){if(t.errorHandler(e),'string'!=typeof e){var c=new a('Could not execute captcha with error: '+e.toString());throw t.onErrorChallenge(t.provider,c),c}if('expired'===e){var l=new a("Challenge or token expired");l.reason='expired',l.capture=false,t.onWarnChallenge(t.provider,l)}if('error'===e){var d=new a("Error during captcha execution");d.reason='error',d.capture=false,t.onErrorChallenge(t.provider,d)}}}}))()}}GoogleCaptcha.RESOLVE_FUNC_NAME='grecaptcha_resolved',GoogleCaptcha.ERROR_FUNC_NAME='grecaptcha_error',GoogleCaptcha.EXPIRED_FUNC_NAME='grecaptcha_expired',GoogleCaptcha.DEBUG=false;export{GoogleCaptcha};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var t=require('./util.js');var e=require('./method-chooser.js');var n=require('./options.js');var s=new Set;var i=0;var o=function(o,r){var a,h;this.id=i++,s.add(this),this.name=o,this.options=n.fillOptionsWithDefaults(r),this.method=e.chooseMethod(this.options),this._iL=false,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,h=(a=this).method.create(a.name,a.options),t.isPromise(h)?(a._prepP=h,h.then((function(t){a._state=t}))):a._state=h};function r(e,n,s){var i={time:e.method.microSeconds(),type:n,data:s};return(e._prepP?e._prepP:t.PROMISE_RESOLVED_VOID).then((function(){var t=e.method.postMessage(e._state,i);return e._uMP.add(t),t.catch().then((function(){return e._uMP.delete(t)})),t}))}function a(t){return t._addEL.message.length>0||t._addEL.internal.length>0}function h(t,e,n){t._addEL[e].push(n),function(t){if(!t._iL&&a(t)){var e=function(e){t._addEL[e.type].forEach((function(t){e.time>=t.time-1e5&&t.fn(e.data)}))};var n=t.method.microSeconds();t._prepP?t._prepP.then((function(){t._iL=true,t.method.onMessage(t._state,e,n)})):(t._iL=true,t.method.onMessage(t._state,e,n))}}(t)}function u(t,e,n){t._addEL[e]=t._addEL[e].filter((function(t){return t!==n})),function(t){if(t._iL&&!a(t)){t._iL=false;var e=t.method.microSeconds();t.method.onMessage(t._state,null,e)}}(t)}o._pubkey=true,o.prototype={postMessage:function(t){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(t));return r(this,'message',t)},postInternal:function(t){return r(this,'internal',t)},set onmessage(t){var e={time:this.method.microSeconds(),fn:t};u(this,'message',this._onML),t&&'function'==typeof t?(this._onML=e,h(this,'message',e)):this._onML=null},addEventListener:function(t,e){h(this,t,{time:this.method.microSeconds(),fn:e})},removeEventListener:function(t,e){u(this,t,this._addEL[t].find((function(t){return t.fn===e})))},close:function(){var e=this;if(!this.closed){s.delete(this),this.closed=true;var n=this._prepP?this._prepP:t.PROMISE_RESOLVED_VOID;return this._onML=null,this._addEL.message=[],n.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(t){return t()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}},exports.BroadcastChannel=o,exports.OPEN_BROADCAST_CHANNELS=s;
@@ -0,0 +1 @@
1
+ import{PROMISE_RESOLVED_VOID as t,isPromise as e}from'./util.mjs';import{chooseMethod as n}from'./method-chooser.mjs';import{fillOptionsWithDefaults as s}from'./options.mjs';var i=new Set;var o=0;var r=function(t,r){var a,h;this.id=o++,i.add(this),this.name=t,this.options=s(r),this.method=n(this.options),this._iL=false,this._onML=null,this._addEL={message:[],internal:[]},this._uMP=new Set,this._befC=[],this._prepP=null,h=(a=this).method.create(a.name,a.options),e(h)?(a._prepP=h,h.then((function(t){a._state=t}))):a._state=h};function a(e,n,s){var i={time:e.method.microSeconds(),type:n,data:s};return(e._prepP?e._prepP:t).then((function(){var t=e.method.postMessage(e._state,i);return e._uMP.add(t),t.catch().then((function(){return e._uMP.delete(t)})),t}))}function h(t){return t._addEL.message.length>0||t._addEL.internal.length>0}function d(t,e,n){t._addEL[e].push(n),function(t){if(!t._iL&&h(t)){var e=function(e){t._addEL[e.type].forEach((function(t){e.time>=t.time-1e5&&t.fn(e.data)}))};var n=t.method.microSeconds();t._prepP?t._prepP.then((function(){t._iL=true,t.method.onMessage(t._state,e,n)})):(t._iL=true,t.method.onMessage(t._state,e,n))}}(t)}function u(t,e,n){t._addEL[e]=t._addEL[e].filter((function(t){return t!==n})),function(t){if(t._iL&&!h(t)){t._iL=false;var e=t.method.microSeconds();t.method.onMessage(t._state,null,e)}}(t)}r._pubkey=true,r.prototype={postMessage:function(t){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed "+JSON.stringify(t));return a(this,'message',t)},postInternal:function(t){return a(this,'internal',t)},set onmessage(t){var e={time:this.method.microSeconds(),fn:t};u(this,'message',this._onML),t&&'function'==typeof t?(this._onML=e,d(this,'message',e)):this._onML=null},addEventListener:function(t,e){d(this,t,{time:this.method.microSeconds(),fn:e})},removeEventListener:function(t,e){u(this,t,this._addEL[t].find((function(t){return t.fn===e})))},close:function(){var e=this;if(!this.closed){i.delete(this),this.closed=true;var n=this._prepP?this._prepP:t;return this._onML=null,this._addEL.message=[],n.then((function(){return Promise.all(Array.from(e._uMP))})).then((function(){return Promise.all(e._befC.map((function(t){return t()})))})).then((function(){return e.method.close(e._state)}))}},get type(){return this.method.type},get isClosed(){return this.closed}};export{r as BroadcastChannel,i as OPEN_BROADCAST_CHANNELS};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('../../../unload/dist/es/index.js');function t(e,t){return e.broadcastChannel.postInternal({context:'leader',action:t,token:e.token})}exports.beLeader=function(n){n.isLeader=true,n._hasLeader=true;var r=e.add((function(){return n.die()}));n._unl.push(r);var a=function(e){'leader'===e.context&&'apply'===e.action&&t(n,'tell'),'leader'!==e.context||'tell'!==e.action||n._dpLC||(n._dpLC=true,n._dpL(),t(n,'tell'))};return n.broadcastChannel.addEventListener('internal',a),n._lstns.push(a),t(n,'tell')},exports.sendLeaderMessage=t;
@@ -0,0 +1 @@
1
+ import{add as e}from'../../../unload/dist/es/index.mjs';function t(e,t){return e.broadcastChannel.postInternal({context:'leader',action:t,token:e.token})}function n(n){n.isLeader=true,n._hasLeader=true;var r=e((function(){return n.die()}));n._unl.push(r);var a=function(e){'leader'===e.context&&'apply'===e.action&&t(n,'tell'),'leader'!==e.context||'tell'!==e.action||n._dpLC||(n._dpLC=true,n._dpL(),t(n,'tell'))};return n.broadcastChannel.addEventListener('internal',a),n._lstns.push(a),t(n,'tell')}export{n as beLeader,t as sendLeaderMessage};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./util.js');var t=require('./leader-election-util.js');var i=function(t,i){var s=this;this.broadcastChannel=t,t._befC.push((function(){return s.die()})),this._options=i,this.isLeader=false,this.isDead=false,this.token=e.randomToken(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=false,this._wKMC={},this.lN='pubkey-bc||'+t.method.type+'||'+t.name};i.prototype={hasLeader:function(){var e=this;return navigator.locks.query().then((function(t){var i=t.held?t.held.filter((function(t){return t.name===e.lN})):[];return!!(i&&i.length>0)}))},awaitLeadership:function(){var e=this;if(!this._wLMP){this._wKMC.c=new AbortController;var i=new Promise((function(t,i){e._wKMC.res=t,e._wKMC.rej=i}));this._wLMP=new Promise((function(s){navigator.locks.request(e.lN,{signal:e._wKMC.c.signal},(function(){return e._wKMC.c=void 0,t.beLeader(e),s(),i})).catch((function(){}))}))}return this._wLMP},set onduplicate(e){},die:function(){var e=this;return this._lstns.forEach((function(t){return e.broadcastChannel.removeEventListener('internal',t)})),this._lstns=[],this._unl.forEach((function(e){return e.remove()})),this._unl=[],this.isLeader&&(this.isLeader=false),this.isDead=true,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort('LeaderElectionWebLock.die() called'),t.sendLeaderMessage(this,'death')}},exports.LeaderElectionWebLock=i;
@@ -0,0 +1 @@
1
+ import{randomToken as t}from'./util.mjs';import{beLeader as e,sendLeaderMessage as i}from'./leader-election-util.mjs';var n=function(e,i){var n=this;this.broadcastChannel=e,e._befC.push((function(){return n.die()})),this._options=i,this.isLeader=false,this.isDead=false,this.token=t(),this._lstns=[],this._unl=[],this._dpL=function(){},this._dpLC=false,this._wKMC={},this.lN='pubkey-bc||'+e.method.type+'||'+e.name};n.prototype={hasLeader:function(){var t=this;return navigator.locks.query().then((function(e){var i=e.held?e.held.filter((function(e){return e.name===t.lN})):[];return!!(i&&i.length>0)}))},awaitLeadership:function(){var t=this;if(!this._wLMP){this._wKMC.c=new AbortController;var i=new Promise((function(e,i){t._wKMC.res=e,t._wKMC.rej=i}));this._wLMP=new Promise((function(n){navigator.locks.request(t.lN,{signal:t._wKMC.c.signal},(function(){return t._wKMC.c=void 0,e(t),n(),i})).catch((function(){}))}))}return this._wLMP},set onduplicate(t){},die:function(){var t=this;return this._lstns.forEach((function(e){return t.broadcastChannel.removeEventListener('internal',e)})),this._lstns=[],this._unl.forEach((function(t){return t.remove()})),this._unl=[],this.isLeader&&(this.isLeader=false),this.isDead=true,this._wKMC.res&&this._wKMC.res(),this._wKMC.c&&this._wKMC.c.abort('LeaderElectionWebLock.die() called'),i(this,'death')}};export{n as LeaderElectionWebLock};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./util.js');var t=require('./leader-election-util.js');var n=require('./leader-election-web-lock.js');var r=function(t,n){var r=this;this.broadcastChannel=t,this._options=n,this.isLeader=false,this._hasLeader=false,this.isDead=false,this.token=e.randomToken(),this._aplQ=e.PROMISE_RESOLVED_VOID,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=false;var a=function(e){'leader'===e.context&&('death'===e.action&&(r._hasLeader=false),'tell'===e.action&&(r._hasLeader=true))};this.broadcastChannel.addEventListener('internal',a),this._lstns.push(a)};r.prototype={hasLeader:function(){return Promise.resolve(this._hasLeader)},applyOnce:function(n){var r=this;return this.isLeader?e.sleep(0,true):this.isDead?e.sleep(0,false):this._aplQC>1?this._aplQ:(this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then((function(){return function(){if(r.isLeader)return e.PROMISE_RESOLVED_TRUE;var a=false;var s;var i=new Promise((function(e){s=function(){a=true,e()}}));var o=function(e){'leader'===e.context&&e.token!=r.token&&('apply'===e.action&&e.token>r.token&&s(),'tell'===e.action&&(s(),r._hasLeader=true))};r.broadcastChannel.addEventListener('internal',o);var l=n?4*r._options.responseTime:r._options.responseTime;return t.sendLeaderMessage(r,'apply').then((function(){return Promise.race([e.sleep(l),i.then((function(){return Promise.reject(new Error)}))])})).then((function(){return t.sendLeaderMessage(r,'apply')})).then((function(){return Promise.race([e.sleep(l),i.then((function(){return Promise.reject(new Error)}))])})).catch((function(){})).then((function(){return r.broadcastChannel.removeEventListener('internal',o),!a&&t.beLeader(r).then((function(){return true}))}))}()})).then((function(){r._aplQC=r._aplQC-1})),this._aplQ.then((function(){return r.isLeader})))},awaitLeadership:function(){return this._aLP||(this._aLP=(t=this).isLeader?e.PROMISE_RESOLVED_VOID:new Promise((function(n){var r=false;function a(){r||(r=true,t.broadcastChannel.removeEventListener('internal',s),n(true))}t.applyOnce().then((function(){t.isLeader&&a()})),function n(){return e.sleep(t._options.fallbackInterval).then((function(){if(!t.isDead&&!r)return t.isLeader?void a():t.applyOnce(true).then((function(){t.isLeader?a():n()}))}))}();var s=function(e){'leader'===e.context&&'death'===e.action&&(t._hasLeader=false,t.applyOnce().then((function(){t.isLeader&&a()})))};t.broadcastChannel.addEventListener('internal',s),t._lstns.push(s)}))),this._aLP;var t},set onduplicate(e){this._dpL=e},die:function(){var e=this;return this._lstns.forEach((function(t){return e.broadcastChannel.removeEventListener('internal',t)})),this._lstns=[],this._unl.forEach((function(e){return e.remove()})),this._unl=[],this.isLeader&&(this._hasLeader=false,this.isLeader=false),this.isDead=true,t.sendLeaderMessage(this,'death')}},exports.createLeaderElection=function(t,a){if(t._leaderElector)throw new Error('BroadcastChannel already has a leader-elector');a=function(e,t){return e||(e={}),(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}(a,t);var s=e.supportsWebLockAPI()?new n.LeaderElectionWebLock(t,a):new r(t,a);return t._befC.push((function(){return s.die()})),t._leaderElector=s,s};
@@ -0,0 +1 @@
1
+ import{supportsWebLockAPI as e,randomToken as t,PROMISE_RESOLVED_VOID as n,sleep as r,PROMISE_RESOLVED_TRUE as a}from'./util.mjs';import{sendLeaderMessage as i,beLeader as s}from'./leader-election-util.mjs';import{LeaderElectionWebLock as o}from'./leader-election-web-lock.mjs';var h=function(e,r){var a=this;this.broadcastChannel=e,this._options=r,this.isLeader=false,this._hasLeader=false,this.isDead=false,this.token=t(),this._aplQ=n,this._aplQC=0,this._unl=[],this._lstns=[],this._dpL=function(){},this._dpLC=false;var i=function(e){'leader'===e.context&&('death'===e.action&&(a._hasLeader=false),'tell'===e.action&&(a._hasLeader=true))};this.broadcastChannel.addEventListener('internal',i),this._lstns.push(i)};function l(t,n){if(t._leaderElector)throw new Error('BroadcastChannel already has a leader-elector');n=function(e,t){return e||(e={}),(e=JSON.parse(JSON.stringify(e))).fallbackInterval||(e.fallbackInterval=3e3),e.responseTime||(e.responseTime=t.method.averageResponseTime(t.options)),e}(n,t);var r=e()?new o(t,n):new h(t,n);return t._befC.push((function(){return r.die()})),t._leaderElector=r,r}h.prototype={hasLeader:function(){return Promise.resolve(this._hasLeader)},applyOnce:function(e){var t=this;return this.isLeader?r(0,true):this.isDead?r(0,false):this._aplQC>1?this._aplQ:(this._aplQC=this._aplQC+1,this._aplQ=this._aplQ.then((function(){return function(){if(t.isLeader)return a;var n=false;var o;var h=new Promise((function(e){o=function(){n=true,e()}}));var l=function(e){'leader'===e.context&&e.token!=t.token&&('apply'===e.action&&e.token>t.token&&o(),'tell'===e.action&&(o(),t._hasLeader=true))};t.broadcastChannel.addEventListener('internal',l);var u=e?4*t._options.responseTime:t._options.responseTime;return i(t,'apply').then((function(){return Promise.race([r(u),h.then((function(){return Promise.reject(new Error)}))])})).then((function(){return i(t,'apply')})).then((function(){return Promise.race([r(u),h.then((function(){return Promise.reject(new Error)}))])})).catch((function(){})).then((function(){return t.broadcastChannel.removeEventListener('internal',l),!n&&s(t).then((function(){return true}))}))}()})).then((function(){t._aplQC=t._aplQC-1})),this._aplQ.then((function(){return t.isLeader})))},awaitLeadership:function(){return this._aLP||(this._aLP=(e=this).isLeader?n:new Promise((function(t){var n=false;function a(){n||(n=true,e.broadcastChannel.removeEventListener('internal',i),t(true))}e.applyOnce().then((function(){e.isLeader&&a()})),function t(){return r(e._options.fallbackInterval).then((function(){if(!e.isDead&&!n)return e.isLeader?void a():e.applyOnce(true).then((function(){e.isLeader?a():t()}))}))}();var i=function(t){'leader'===t.context&&'death'===t.action&&(e._hasLeader=false,e.applyOnce().then((function(){e.isLeader&&a()})))};e.broadcastChannel.addEventListener('internal',i),e._lstns.push(i)}))),this._aLP;var e},set onduplicate(e){this._dpL=e},die:function(){var e=this;return this._lstns.forEach((function(t){return e.broadcastChannel.removeEventListener('internal',t)})),this._lstns=[],this._unl.forEach((function(e){return e.remove()})),this._unl=[],this.isLeader&&(this._hasLeader=false,this.isLeader=false),this.isDead=true,i(this,'death')}};export{l as createLeaderElection};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./methods/native.js');var t=require('./methods/indexed-db.js');var r=require('./methods/localstorage.js');var o=require('./methods/simulate.js');var n=[e.NativeMethod,t.IndexedDBMethod,r.LocalstorageMethod];exports.chooseMethod=function(e){var t=[].concat(e.methods,n).filter(Boolean);if(e.type){if('simulate'===e.type)return o.SimulateMethod;var r=t.find((function(t){return t.type===e.type}));if(r)return r;throw new Error('method-type '+e.type+' not found')}e.webWorkerSupport||(t=t.filter((function(e){return'idb'!==e.type})));var i=t.find((function(e){return e.canBeUsed()}));if(i)return i;throw new Error("No usable method found in "+JSON.stringify(n.map((function(e){return e.type}))))};
@@ -0,0 +1 @@
1
+ import{NativeMethod as t}from'./methods/native.mjs';import{IndexedDBMethod as r}from'./methods/indexed-db.mjs';import{LocalstorageMethod as e}from'./methods/localstorage.mjs';import{SimulateMethod as o}from'./methods/simulate.mjs';var n=[t,r,e];function i(t){var r=[].concat(t.methods,n).filter(Boolean);if(t.type){if('simulate'===t.type)return o;var e=r.find((function(r){return r.type===t.type}));if(e)return e;throw new Error('method-type '+t.type+' not found')}t.webWorkerSupport||(r=r.filter((function(t){return'idb'!==t.type})));var i=r.find((function(t){return t.canBeUsed()}));if(i)return i;throw new Error("No usable method found in "+JSON.stringify(n.map((function(t){return t.type}))))}export{i as chooseMethod};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('../util.js');var n=require('../../../../oblivious-set/dist/es/index.js');var r=require('../options.js');var t=e.microSeconds;var o='pubkey.broadcast-channel-0-';var s='messages';var i={durability:'relaxed'};function u(){if('undefined'!=typeof indexedDB)return indexedDB;if('undefined'!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return false}function a(e){e.commit&&e.commit()}function c(e){var n=u().open(o+e);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(s,{keyPath:'id',autoIncrement:true})},new Promise((function(e,r){n.onerror=function(e){return r(e)},n.onsuccess=function(){e(n.result)}}))}function d(e,n,r){var t={uuid:n,time:Date.now(),data:r};var o=e.transaction([s],'readwrite',i);return new Promise((function(e,n){o.oncomplete=function(){return e()},o.onerror=function(e){return n(e)},o.objectStore(s).add(t),a(o)}))}function l(e,n){var r=e.transaction(s,'readonly',i);var t=r.objectStore(s);var o=[];var u=IDBKeyRange.bound(n+1,1/0);if(t.getAll){var c=t.getAll(u);return new Promise((function(e,n){c.onerror=function(e){return n(e)},c.onsuccess=function(n){e(n.target.result)}}))}return new Promise((function(e,s){var i=function(){try{return u=IDBKeyRange.bound(n+1,1/0),t.openCursor(u)}catch(e){return t.openCursor()}}();i.onerror=function(e){return s(e)},i.onsuccess=function(t){var s=t.target.result;s?s.value.id<n+1?s.continue(n+1):(o.push(s.value),s.continue()):(a(r),e(o))}}))}function f(e,n){if(e.closed)return Promise.resolve([]);var r=e.db.transaction(s,'readwrite',i).objectStore(s);return Promise.all(n.map((function(e){var n=r.delete(e);return new Promise((function(e){n.onsuccess=function(){return e()}}))})))}function m(e,n){var r=Date.now()-n;var t=e.transaction(s,'readonly',i);var o=t.objectStore(s);var u=[];return new Promise((function(e){o.openCursor().onsuccess=function(n){var o=n.target.result;if(o){var s=o.value;s.time<r?(u.push(s),o.continue()):(a(t),e(u))}else e(u)}}))}function p(e){return m(e.db,e.options.idb.ttl).then((function(n){return f(e,n.map((function(e){return e.id})))}))}function v(t,o){return o=r.fillOptionsWithDefaults(o),c(t).then((function(r){var s={closed:false,lastCursorId:0,channelName:t,options:o,uuid:e.randomToken(),eMIs:new n.ObliviousSet(2*o.idb.ttl),writeBlockPromise:e.PROMISE_RESOLVED_VOID,messagesCallback:null,readQueuePromises:[],db:r};return r.onclose=function(){s.closed=true,o.idb.onclose&&o.idb.onclose()},b(s),s}))}function b(n){n.closed||I(n).then((function(){return e.sleep(n.options.idb.fallbackInterval)})).then((function(){return b(n)}))}function I(n){return n.closed?e.PROMISE_RESOLVED_VOID:n.messagesCallback?l(n.db,n.lastCursorId).then((function(r){var t=r.filter((function(e){return!!e})).map((function(e){return e.id>n.lastCursorId&&(n.lastCursorId=e.id),e})).filter((function(e){return function(e,n){return!(e.uuid===n.uuid||n.eMIs.has(e.id)||e.data.time<n.messagesCallbackTime)}(e,n)})).sort((function(e,n){return e.time-n.time}));return t.forEach((function(e){n.messagesCallback&&(n.eMIs.add(e.id),n.messagesCallback(e.data))})),e.PROMISE_RESOLVED_VOID})):e.PROMISE_RESOLVED_VOID}function g(e){e.closed=true,e.db.close()}function w(n,r){return n.writeBlockPromise=n.writeBlockPromise.then((function(){return d(n.db,n.uuid,r)})).then((function(){0===e.randomInt(0,10)&&p(n)})),n.writeBlockPromise}function x(e,n,r){e.messagesCallbackTime=r,e.messagesCallback=n,I(e)}function D(){return!!u()}function S(e){return 2*e.idb.fallbackInterval}exports.IndexedDBMethod={create:v,close:g,onMessage:x,postMessage:w,canBeUsed:D,type:"idb",averageResponseTime:S,microSeconds:t},exports.TRANSACTION_SETTINGS=i,exports.averageResponseTime=S,exports.canBeUsed=D,exports.cleanOldMessages=p,exports.close=g,exports.commitIndexedDBTransaction=a,exports.create=v,exports.createDatabase=c,exports.getIdb=u,exports.getMessagesHigherThan=l,exports.getOldMessages=m,exports.microSeconds=t,exports.onMessage=x,exports.postMessage=w,exports.removeMessagesById=f,exports.type="idb",exports.writeMessage=d;
@@ -0,0 +1 @@
1
+ import{microSeconds as e,randomToken as n,PROMISE_RESOLVED_VOID as r,sleep as t,randomInt as o}from'../util.mjs';import{ObliviousSet as i}from'../../../../oblivious-set/dist/es/index.mjs';import{fillOptionsWithDefaults as u}from'../options.mjs';var s=e;var a='pubkey.broadcast-channel-0-';var c='messages';var d={durability:'relaxed'};var l='idb';function f(){if('undefined'!=typeof indexedDB)return indexedDB;if('undefined'!=typeof window){if(void 0!==window.mozIndexedDB)return window.mozIndexedDB;if(void 0!==window.webkitIndexedDB)return window.webkitIndexedDB;if(void 0!==window.msIndexedDB)return window.msIndexedDB}return false}function m(e){e.commit&&e.commit()}function v(e){var n=f().open(a+e);return n.onupgradeneeded=function(e){e.target.result.createObjectStore(c,{keyPath:'id',autoIncrement:true})},new Promise((function(e,r){n.onerror=function(e){return r(e)},n.onsuccess=function(){e(n.result)}}))}function b(e,n,r){var t={uuid:n,time:Date.now(),data:r};var o=e.transaction([c],'readwrite',d);return new Promise((function(e,n){o.oncomplete=function(){return e()},o.onerror=function(e){return n(e)},o.objectStore(c).add(t),m(o)}))}function w(e,n){var r=e.transaction(c,'readonly',d);var t=r.objectStore(c);var o=[];var i=IDBKeyRange.bound(n+1,1/0);if(t.getAll){var u=t.getAll(i);return new Promise((function(e,n){u.onerror=function(e){return n(e)},u.onsuccess=function(n){e(n.target.result)}}))}return new Promise((function(e,u){var s=function(){try{return i=IDBKeyRange.bound(n+1,1/0),t.openCursor(i)}catch(e){return t.openCursor()}}();s.onerror=function(e){return u(e)},s.onsuccess=function(t){var i=t.target.result;i?i.value.id<n+1?i.continue(n+1):(o.push(i.value),i.continue()):(m(r),e(o))}}))}function p(e,n){if(e.closed)return Promise.resolve([]);var r=e.db.transaction(c,'readwrite',d).objectStore(c);return Promise.all(n.map((function(e){var n=r.delete(e);return new Promise((function(e){n.onsuccess=function(){return e()}}))})))}function g(e,n){var r=Date.now()-n;var t=e.transaction(c,'readonly',d);var o=t.objectStore(c);var i=[];return new Promise((function(e){o.openCursor().onsuccess=function(n){var o=n.target.result;if(o){var u=o.value;u.time<r?(i.push(u),o.continue()):(m(t),e(i))}else e(i)}}))}function I(e){return g(e.db,e.options.idb.ttl).then((function(n){return p(e,n.map((function(e){return e.id})))}))}function k(e,t){return t=u(t),v(e).then((function(o){var u={closed:false,lastCursorId:0,channelName:e,options:t,uuid:n(),eMIs:new i(2*t.idb.ttl),writeBlockPromise:r,messagesCallback:null,readQueuePromises:[],db:o};return o.onclose=function(){u.closed=true,t.idb.onclose&&t.idb.onclose()},h(u),u}))}function h(e){e.closed||B(e).then((function(){return t(e.options.idb.fallbackInterval)})).then((function(){return h(e)}))}function B(e){return e.closed?r:e.messagesCallback?w(e.db,e.lastCursorId).then((function(n){var t=n.filter((function(e){return!!e})).map((function(n){return n.id>e.lastCursorId&&(e.lastCursorId=n.id),n})).filter((function(n){return function(e,n){return!(e.uuid===n.uuid||n.eMIs.has(e.id)||e.data.time<n.messagesCallbackTime)}(n,e)})).sort((function(e,n){return e.time-n.time}));return t.forEach((function(n){e.messagesCallback&&(e.eMIs.add(n.id),e.messagesCallback(n.data))})),r})):r}function C(e){e.closed=true,e.db.close()}function P(e,n){return e.writeBlockPromise=e.writeBlockPromise.then((function(){return b(e.db,e.uuid,n)})).then((function(){0===o(0,10)&&I(e)})),e.writeBlockPromise}function D(e,n,r){e.messagesCallbackTime=r,e.messagesCallback=n,B(e)}function x(){return!!f()}function y(e){return 2*e.idb.fallbackInterval}var j={create:k,close:C,onMessage:D,postMessage:P,canBeUsed:x,type:"idb",averageResponseTime:y,microSeconds:s};export{j as IndexedDBMethod,d as TRANSACTION_SETTINGS,y as averageResponseTime,x as canBeUsed,I as cleanOldMessages,C as close,m as commitIndexedDBTransaction,k as create,v as createDatabase,f as getIdb,w as getMessagesHigherThan,g as getOldMessages,s as microSeconds,D as onMessage,P as postMessage,p as removeMessagesById,l as type,b as writeMessage};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('../../../../oblivious-set/dist/es/index.js');var t=require('../options.js');var r=require('../util.js');var a=r.microSeconds;var n='pubkey.broadcastChannel-';var o='localstorage';function s(){var e;if('undefined'==typeof window)return null;try{e=window.localStorage,e=window['ie8-eventlistener/storage']||window.localStorage}catch(e){}return e}function i(e){return n+e}function c(e,t){return new Promise((function(a){r.sleep().then((function(){var n=i(e.channelName);var o={token:r.randomToken(),time:Date.now(),data:t,uuid:e.uuid};var c=JSON.stringify(o);s().setItem(n,c);var u=document.createEvent('Event');u.initEvent('storage',true,true),u.key=n,u.newValue=c,window.dispatchEvent(u),a()}))}))}function u(e,t){var r=i(e);var a=function(e){e.key===r&&t(JSON.parse(e.newValue))};return window.addEventListener('storage',a),a}function l(e){window.removeEventListener('storage',e)}function d(a,n){if(n=t.fillOptionsWithDefaults(n),!g())throw new Error('BroadcastChannel: localstorage cannot be used');var o=r.randomToken();var s=new e.ObliviousSet(n.localstorage.removeTimeout);var i={channelName:a,uuid:o,eMIs:s};return i.listener=u(a,(function(e){i.messagesCallback&&e.uuid!==o&&e.token&&!s.has(e.token)&&(e.data.time&&e.data.time<i.messagesCallbackTime||(s.add(e.token),i.messagesCallback(e.data)))})),i}function v(e){l(e.listener)}function m(e,t,r){e.messagesCallbackTime=r,e.messagesCallback=t}function g(){var e=s();if(!e)return false;try{var t='__broadcastchannel_check';e.setItem(t,'works'),e.removeItem(t)}catch(e){return false}return true}function p(){var e=navigator.userAgent.toLowerCase();return e.includes('safari')&&!e.includes('chrome')?240:120}exports.LocalstorageMethod={create:d,close:v,onMessage:m,postMessage:c,canBeUsed:g,type:o,averageResponseTime:p,microSeconds:a},exports.addStorageEventListener=u,exports.averageResponseTime=p,exports.canBeUsed=g,exports.close=v,exports.create=d,exports.getLocalStorage=s,exports.microSeconds=a,exports.onMessage=m,exports.postMessage=c,exports.removeStorageEventListener=l,exports.storageKey=i,exports.type=o;
@@ -0,0 +1 @@
1
+ import{ObliviousSet as e}from'../../../../oblivious-set/dist/es/index.mjs';import{fillOptionsWithDefaults as n}from'../options.mjs';import{microSeconds as t,sleep as a,randomToken as r}from'../util.mjs';var o=t;var s='pubkey.broadcastChannel-';var i='localstorage';function c(){var e;if('undefined'==typeof window)return null;try{e=window.localStorage,e=window['ie8-eventlistener/storage']||window.localStorage}catch(e){}return e}function u(e){return s+e}function l(e,n){return new Promise((function(t){a().then((function(){var a=u(e.channelName);var o={token:r(),time:Date.now(),data:n,uuid:e.uuid};var s=JSON.stringify(o);c().setItem(a,s);var i=document.createEvent('Event');i.initEvent('storage',true,true),i.key=a,i.newValue=s,window.dispatchEvent(i),t()}))}))}function d(e,n){var t=u(e);var a=function(e){e.key===t&&n(JSON.parse(e.newValue))};return window.addEventListener('storage',a),a}function m(e){window.removeEventListener('storage',e)}function v(t,a){if(a=n(a),!g())throw new Error('BroadcastChannel: localstorage cannot be used');var o=r();var s=new e(a.localstorage.removeTimeout);var i={channelName:t,uuid:o,eMIs:s};return i.listener=d(t,(function(e){i.messagesCallback&&e.uuid!==o&&e.token&&!s.has(e.token)&&(e.data.time&&e.data.time<i.messagesCallbackTime||(s.add(e.token),i.messagesCallback(e.data)))})),i}function f(e){m(e.listener)}function w(e,n,t){e.messagesCallbackTime=t,e.messagesCallback=n}function g(){var e=c();if(!e)return false;try{var n='__broadcastchannel_check';e.setItem(n,'works'),e.removeItem(n)}catch(e){return false}return true}function k(){var e=navigator.userAgent.toLowerCase();return e.includes('safari')&&!e.includes('chrome')?240:120}var h={create:v,close:f,onMessage:w,postMessage:l,canBeUsed:g,type:i,averageResponseTime:k,microSeconds:o};export{h as LocalstorageMethod,d as addStorageEventListener,k as averageResponseTime,g as canBeUsed,f as close,v as create,c as getLocalStorage,o as microSeconds,w as onMessage,l as postMessage,m as removeStorageEventListener,u as storageKey,i as type};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('../util.js');var s=e.microSeconds;var t='native';function n(e){var s={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return s.bc.onmessage=function(e){s.messagesCallback&&s.messagesCallback(e.data)},s}function o(e){e.bc.close(),e.subFns=[]}function a(s,t){try{return s.bc.postMessage(t,false),e.PROMISE_RESOLVED_VOID}catch(e){return Promise.reject(e)}}function r(e,s){e.messagesCallback=s}function c(){if('undefined'==typeof window&&'undefined'==typeof self||'function'!=typeof BroadcastChannel)return false;if(BroadcastChannel._pubkey)throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');return true}function i(){return 150}exports.NativeMethod={create:n,close:o,onMessage:r,postMessage:a,canBeUsed:c,type:t,averageResponseTime:i,microSeconds:s},exports.averageResponseTime=i,exports.canBeUsed=c,exports.close=o,exports.create=n,exports.microSeconds=s,exports.onMessage=r,exports.postMessage=a,exports.type=t;
@@ -0,0 +1 @@
1
+ import{microSeconds as e,PROMISE_RESOLVED_VOID as n}from'../util.mjs';var a=e;var s='native';function t(e){var n={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return n.bc.onmessage=function(e){n.messagesCallback&&n.messagesCallback(e.data)},n}function o(e){e.bc.close(),e.subFns=[]}function r(e,a){try{return e.bc.postMessage(a,false),n}catch(e){return Promise.reject(e)}}function c(e,n){e.messagesCallback=n}function i(){if('undefined'==typeof window&&'undefined'==typeof self||'function'!=typeof BroadcastChannel)return false;if(BroadcastChannel._pubkey)throw new Error('BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill');return true}function l(){return 150}var u={create:t,close:o,onMessage:c,postMessage:r,canBeUsed:i,type:s,averageResponseTime:l,microSeconds:a};export{u as NativeMethod,l as averageResponseTime,i as canBeUsed,o as close,t as create,a as microSeconds,c as onMessage,r as postMessage,s as type};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('../util.js').microSeconds;var r='simulate';var t=new Set;function s(e){var r={name:e,messagesCallback:null};return t.add(r),r}function n(e){t.delete(e)}function o(e,r){return new Promise((function(s){return setTimeout((function(){Array.from(t).filter((function(r){return r.name===e.name})).filter((function(r){return r!==e})).filter((function(e){return!!e.messagesCallback})).forEach((function(e){return e.messagesCallback(r)})),s()}),5)}))}function a(e,r){e.messagesCallback=r}function u(){return true}function c(){return 5}exports.SimulateMethod={create:s,close:n,onMessage:a,postMessage:o,canBeUsed:u,type:r,averageResponseTime:c,microSeconds:e},exports.averageResponseTime=c,exports.canBeUsed=u,exports.close=n,exports.create=s,exports.microSeconds=e,exports.onMessage=a,exports.postMessage=o,exports.type=r;
@@ -0,0 +1 @@
1
+ import{microSeconds as e}from'../util.mjs';var n=e;var r='simulate';var t=new Set;function a(e){var n={name:e,messagesCallback:null};return t.add(n),n}function s(e){t.delete(e)}function o(e,n){return new Promise((function(r){return setTimeout((function(){Array.from(t).filter((function(n){return n.name===e.name})).filter((function(n){return n!==e})).filter((function(e){return!!e.messagesCallback})).forEach((function(e){return e.messagesCallback(n)})),r()}),5)}))}function u(e,n){e.messagesCallback=n}function c(){return true}function i(){return 5}var f={create:a,close:s,onMessage:u,postMessage:o,canBeUsed:c,type:r,averageResponseTime:i,microSeconds:n};export{f as SimulateMethod,i as averageResponseTime,c as canBeUsed,s as close,a as create,n as microSeconds,u as onMessage,o as postMessage,r as type};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true}),exports.fillOptionsWithDefaults=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var t=JSON.parse(JSON.stringify(e));return void 0===t.webWorkerSupport&&(t.webWorkerSupport=true),t.idb||(t.idb={}),t.idb.ttl||(t.idb.ttl=45e3),t.idb.fallbackInterval||(t.idb.fallbackInterval=150),e.idb&&'function'==typeof e.idb.onclose&&(t.idb.onclose=e.idb.onclose),t.localstorage||(t.localstorage={}),t.localstorage.removeTimeout||(t.localstorage.removeTimeout=6e4),e.methods&&(t.methods=e.methods),t.node||(t.node={}),t.node.ttl||(t.node.ttl=12e4),t.node.maxParallelWrites||(t.node.maxParallelWrites=2048),void 0===t.node.useFastPath&&(t.node.useFastPath=true),t};
@@ -0,0 +1 @@
1
+ function e(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};var o=JSON.parse(JSON.stringify(e));return void 0===o.webWorkerSupport&&(o.webWorkerSupport=true),o.idb||(o.idb={}),o.idb.ttl||(o.idb.ttl=45e3),o.idb.fallbackInterval||(o.idb.fallbackInterval=150),e.idb&&'function'==typeof e.idb.onclose&&(o.idb.onclose=e.idb.onclose),o.localstorage||(o.localstorage={}),o.localstorage.removeTimeout||(o.localstorage.removeTimeout=6e4),e.methods&&(o.methods=e.methods),o.node||(o.node={}),o.node.ttl||(o.node.ttl=12e4),o.node.maxParallelWrites||(o.node.maxParallelWrites=2048),void 0===o.node.useFastPath&&(o.node.useFastPath=true),o}export{e as fillOptionsWithDefaults};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true}),Promise.resolve(false);var e=Promise.resolve(true);var r=Promise.resolve();var o=0;var t=0;exports.PROMISE_RESOLVED_TRUE=e,exports.PROMISE_RESOLVED_VOID=r,exports.isPromise=function(e){return e&&'function'==typeof e.then},exports.microSeconds=function(){var e=Date.now();return e===o?1e3*e+ ++t:(o=e,t=0,1e3*e)},exports.randomInt=function(e,r){return Math.floor(Math.random()*(r-e+1)+e)},exports.randomToken=function(){return Math.random().toString(36).substring(2)},exports.sleep=function(e,r){return e||(e=0),new Promise((function(o){return setTimeout((function(){return o(r)}),e)}))},exports.supportsWebLockAPI=function(){return'undefined'!=typeof navigator&&void 0!==navigator.locks&&'function'==typeof navigator.locks.request};
@@ -0,0 +1 @@
1
+ function n(n){return n&&'function'==typeof n.then}Promise.resolve(false);var r=Promise.resolve(true);var t=Promise.resolve();function e(n,r){return n||(n=0),new Promise((function(t){return setTimeout((function(){return t(r)}),n)}))}function o(n,r){return Math.floor(Math.random()*(r-n+1)+n)}function u(){return Math.random().toString(36).substring(2)}var i=0;var a=0;function f(){var n=Date.now();return n===i?1e3*n+ ++a:(i=n,a=0,1e3*n)}function s(){return'undefined'!=typeof navigator&&void 0!==navigator.locks&&'function'==typeof navigator.locks.request}export{r as PROMISE_RESOLVED_TRUE,t as PROMISE_RESOLVED_VOID,n as isPromise,f as microSeconds,o as randomInt,u as randomToken,e as sleep,s as supportsWebLockAPI};
@@ -0,0 +1 @@
1
+ 'use strict';function e(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,'default')?e.default:e}Object.defineProperty(exports,'__esModule',{value:true});var t={exports:{}};var s='object'==typeof Reflect?Reflect:null;var r=s&&'function'==typeof s.apply?s.apply:function(e,t,s){return function(){}.apply.call(e,t,s)};var n;n=s&&'function'==typeof s.ownKeys?s.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}t.exports=o,t.exports.once=function(e,t){return new Promise((function(s,r){function n(s){e.removeListener(t,i),r(s)}function i(){'function'==typeof e.removeListener&&e.removeListener('error',n),s([].slice.call(arguments))}b(e,t,i,{once:true}),'error'!==t&&function(e,t){'function'==typeof e.on&&b(e,'error',t,{once:true})}(e,n)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function c(e){if('function'!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,s,r){var n;var i;var o;if(c(s),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit('newListener',t,s.listener?s.listener:s),i=e._events),o=i[t]),void 0===o)o=i[t]=s,++e._eventsCount;else if('function'==typeof o?o=i[t]=r?[s,o]:[o,s]:r?o.unshift(s):o.push(s),(n=h(e))>0&&o.length>n&&!o.warned){o.warned=true;var a=new Error('Possible EventEmitter memory leak detected. '+o.length+' '+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name='MaxListenersExceededWarning',a.emitter=e,a.type=t,a.count=o.length,console&&console.warn&&console.warn(a)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=true,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,s){var r={fired:false,wrapFn:void 0,target:e,type:t,listener:s};var n=l.bind(r);return n.listener=s,r.wrapFn=n,n}function _(e,t,s){var r=e._events;if(void 0===r)return[];var n=r[t];return void 0===n?[]:'function'==typeof n?s?[n.listener||n]:[n]:s?function(e){var t=new Array(e.length);for(var s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(n):f(n,n.length)}function p(e){var t=this._events;if(void 0!==t){var s=t[e];if('function'==typeof s)return 1;if(void 0!==s)return s.length}return 0}function f(e,t){var s=new Array(t);for(var r=0;r<t;++r)s[r]=e[r];return s}function b(e,t,s,r){if('function'==typeof e.on)r.once?e.once(t,s):e.on(t,s);else{if('function'!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function n(i){r.once&&e.removeEventListener(t,n),s(i)}))}}Object.defineProperty(o,'defaultMaxListeners',{enumerable:true,get:function(){return a},set:function(e){if('number'!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+'.');a=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if('number'!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+'.');return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return h(this)},o.prototype.emit=function(e){var t=[];for(var s=1;s<arguments.length;s++)t.push(arguments[s]);var n='error'===e;var i=this._events;if(void 0!==i)n=n&&void 0===i.error;else if(!n)return false;if(n){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error('Unhandled error.'+(o?' ('+o.message+')':''));throw a.context=o,a}var c=i[e];if(void 0===c)return false;if('function'==typeof c)r(c,this,t);else{var h=c.length;var u=f(c,h);for(s=0;s<h;++s)r(u[s],this,t)}return true},o.prototype.on=o.prototype.addListener=function(e,t){return u(this,e,t,false)},o.prototype.prependListener=function(e,t){return u(this,e,t,true)},o.prototype.once=function(e,t){return c(t),this.on(e,d(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,d(this,e,t)),this},o.prototype.removeListener=function(e,t){var s,r,n,i,o;if(c(t),void 0===(r=this._events))return this;if(void 0===(s=r[e]))return this;if(s===t||s.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit('removeListener',e,s.listener||t));else if('function'!=typeof s){for(n=-1,i=s.length-1;i>=0;i--)if(s[i]===t||s[i].listener===t){o=s[i].listener,n=i;break}if(n<0)return this;0===n?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,n),1===s.length&&(r[e]=s[0]),void 0!==r.removeListener&&this.emit('removeListener',e,o||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,s,r;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var n=Object.keys(s);var i;for(r=0;r<n.length;++r)'removeListener'!==(i=n[r])&&this.removeAllListeners(i);return this.removeAllListeners('removeListener'),this._events=Object.create(null),this._eventsCount=0,this}if('function'==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return _(this,e,true)},o.prototype.rawListeners=function(e){return _(this,e,false)},o.listenerCount=function(e,t){return'function'==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};var v=e(t.exports);var g;var m;var S;var y;var C;var T;var x;function w(e){return null!=e&&'function'==typeof e}function k(e,t,s){e>31&&(e=31);var r=function(e,t){return Math.floor(Math.random()*(t-0+1)+0)}(0,Math.min(s,t*Math.pow(2,e)));return Math.min(s,t+r)}function E(e){return Math.min(1e3*e,2147483647)}exports.errorCodes=void 0,(g=exports.errorCodes||(exports.errorCodes={}))[g.timeout=1]="timeout",g[g.transportClosed=2]="transportClosed",g[g.clientDisconnected=3]="clientDisconnected",g[g.clientClosed=4]="clientClosed",g[g.clientConnectToken=5]="clientConnectToken",g[g.clientRefreshToken=6]="clientRefreshToken",g[g.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",g[g.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",g[g.subscriptionRefreshToken=9]="subscriptionRefreshToken",g[g.transportWriteError=10]="transportWriteError",g[g.connectionClosed=11]="connectionClosed",g[g.badConfiguration=12]="badConfiguration",exports.connectingCodes=void 0,(m=exports.connectingCodes||(exports.connectingCodes={}))[m.connectCalled=0]="connectCalled",m[m.transportClosed=1]="transportClosed",m[m.noPing=2]="noPing",m[m.subscribeTimeout=3]="subscribeTimeout",m[m.unsubscribeError=4]="unsubscribeError",exports.disconnectedCodes=void 0,(S=exports.disconnectedCodes||(exports.disconnectedCodes={}))[S.disconnectCalled=0]="disconnectCalled",S[S.unauthorized=1]="unauthorized",S[S.badProtocol=2]="badProtocol",S[S.messageSizeLimit=3]="messageSizeLimit",exports.subscribingCodes=void 0,(y=exports.subscribingCodes||(exports.subscribingCodes={}))[y.subscribeCalled=0]="subscribeCalled",y[y.transportClosed=1]="transportClosed",exports.unsubscribedCodes=void 0,(C=exports.unsubscribedCodes||(exports.unsubscribedCodes={}))[C.unsubscribeCalled=0]="unsubscribeCalled",C[C.unauthorized=1]="unauthorized",C[C.clientClosed=2]="clientClosed",exports.State=void 0,(T=exports.State||(exports.State={})).Disconnected="disconnected",T.Connecting="connecting",T.Connected="connected",exports.SubscriptionState=void 0,(x=exports.SubscriptionState||(exports.SubscriptionState={})).Unsubscribed="unsubscribed",x.Subscribing="subscribing",x.Subscribed="subscribed";class Subscription extends v{constructor(e,t,s){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=exports.SubscriptionState.Unsubscribed,this._centrifuge=e,this._token='',this._getToken=null,this._data=null,this._getData=null,this._recover=false,this._offset=null,this._epoch=null,this._recoverable=false,this._positioned=false,this._joinLeave=false,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=false,this._refreshTimeout=null,this._setOptions(s),this._centrifuge._debugEnabled?(this.on('state',(e=>{this._centrifuge._debug('subscription state',t,e.oldState,'->',e.newState)})),this.on('error',(e=>{this._centrifuge._debug('subscription error',t,e)}))):this.on('error',(function(){Function.prototype()}))}ready(e){return this.state===exports.SubscriptionState.Unsubscribed?Promise.reject({code:exports.errorCodes.subscriptionUnsubscribed,message:this.state}):this.state===exports.SubscriptionState.Subscribed?Promise.resolve():new Promise(((t,s)=>{var r={resolve:t,reject:s};e&&(r.timeout=setTimeout((function(){s({code:exports.errorCodes.timeout,message:'timeout'})}),e)),this._promises[this._nextPromiseId()]=r}))}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(exports.subscribingCodes.subscribeCalled,'subscribe called'))}unsubscribe(){this._setUnsubscribed(exports.unsubscribedCodes.unsubscribeCalled,'unsubscribe called',true)}publish(e){var t=this;return this._methodCall().then((function(){return t._centrifuge.publish(t.channel,e)}))}presence(){var e=this;return this._methodCall().then((function(){return e._centrifuge.presence(e.channel)}))}presenceStats(){var e=this;return this._methodCall().then((function(){return e._centrifuge.presenceStats(e.channel)}))}history(e){var t=this;return this._methodCall().then((function(){return t._centrifuge.history(t.channel,e)}))}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:exports.errorCodes.subscriptionUnsubscribed,message:this.state}):new Promise(((e,t)=>{var s=setTimeout((function(){t({code:exports.errorCodes.timeout,message:'timeout'})}),this._centrifuge._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}}))}_nextPromiseId(){return++this._promiseId}_needRecover(){return true===this._recover}_isUnsubscribed(){return this.state===exports.SubscriptionState.Unsubscribed}_isSubscribing(){return this.state===exports.SubscriptionState.Subscribing}_isSubscribed(){return this.state===exports.SubscriptionState.Subscribed}_setState(e){if(this.state!==e){var t=this.state;return this.state=e,this.emit('state',{newState:e,oldState:t,channel:this.channel}),true}return false}_usesToken(){return''!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout()}_setSubscribed(e){if(this._isSubscribing()){this._clearSubscribingState(),e.recoverable&&(this._recover=true,this._offset=e.offset||0,this._epoch=e.epoch||''),this._setState(exports.SubscriptionState.Subscribed);var t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit('subscribed',t),this._resolvePromises();var s=e.publications;if(s&&s.length>0)for(var r in s)s.hasOwnProperty(r)&&this._handlePublication(s[r]);true===e.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),E(e.ttl)))}}_setSubscribing(e,t){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(exports.SubscriptionState.Subscribing)&&this.emit('subscribing',{channel:this.channel,code:e,reason:t}),this._subscribe())}_subscribe(){if(this._centrifuge._debug('subscribing on',this.channel),!this._centrifuge._transportIsOpen)return this._centrifuge._debug('delay subscribe on',this.channel,'till connected'),null;var e=this;var t={channel:e.channel};return!this._usesToken()||this._token?e._getData?(e._getData(t).then((function(t){e._isSubscribing()&&(e._data=t,e._sendSubscribe(e._token))})),null):e._sendSubscribe(e._token):(this._getSubscriptionToken().then((function(s){e._isSubscribing()&&(s?(e._token=s,e._getData?e._getData(t).then((function(t){e._isSubscribing()&&(e._data=t,e._sendSubscribe(s))})):e._sendSubscribe(s)):e._failUnauthorized())})).catch((function(t){e._isSubscribing()&&(t instanceof UnauthorizedError?e._failUnauthorized():(e.emit('error',{type:'subscribeToken',channel:e.channel,error:{code:exports.errorCodes.subscriptionSubscribeToken,message:void 0!==t?t.toString():''}}),e._scheduleResubscribe()))})),null)}_sendSubscribe(e){if(!this._centrifuge._transportIsOpen)return null;var t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._positioned&&(t.positioned=true),this._recoverable&&(t.recoverable=true),this._joinLeave&&(t.join_leave=true),this._needRecover()){t.recover=true;var s=this._getOffset();s&&(t.offset=s);var r=this._getEpoch();r&&(t.epoch=r)}var n={subscribe:t};return this._inflight=true,this._centrifuge._call(n).then((e=>{this._inflight=false,this._handleSubscribeResponse(e.reply.subscribe),e.next&&e.next()}),(e=>{this._inflight=false,this._handleSubscribeError(e.error),e.next&&e.next()})),n}_handleSubscribeError(e){this._isSubscribing()&&(e.code!==exports.errorCodes.timeout?this._subscribeError(e):this._centrifuge._disconnect(exports.connectingCodes.subscribeTimeout,'subscribe timeout',true))}_handleSubscribeResponse(e){this._isSubscribing()&&this._setSubscribed(e)}_setUnsubscribed(e,t,s){this._isUnsubscribed()||(this._isSubscribed()&&(s&&this._centrifuge._unsubscribe(this),this._clearSubscribedState()),this._isSubscribing()&&(this._inflight&&s&&this._centrifuge._unsubscribe(this),this._clearSubscribingState()),this._setState(exports.SubscriptionState.Unsubscribed)&&this.emit('unsubscribed',{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:exports.errorCodes.subscriptionUnsubscribed,message:this.state}))}_handlePublication(e){var t=this._centrifuge._getPublicationContext(this.channel,e);this.emit('publication',t),e.offset&&(this._offset=e.offset)}_handleJoin(e){var t=this._centrifuge._getJoinLeaveContext(e.info);this.emit('join',{channel:this.channel,info:t})}_handleLeave(e){var t=this._centrifuge._getJoinLeaveContext(e.info);this.emit('leave',{channel:this.channel,info:t})}_resolvePromises(){for(var e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(var t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}_scheduleResubscribe(){var e=this;var t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout((function(){e._isSubscribing()&&e._subscribe()}),t)}_subscribeError(e){this._isSubscribing()&&(e.code<100||109===e.code||true===e.temporary?(109===e.code&&(this._token=''),this._centrifuge.state===exports.State.Connected&&this.emit('error',{channel:this.channel,type:'subscribe',error:e}),this._scheduleResubscribe()):this._setUnsubscribed(e.code,e.message,false))}_getResubscribeDelay(){var e=k(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){e&&(e.since&&(this._offset=e.since.offset,this._epoch=e.since.epoch,this._recover=true),e.data&&(this._data=e.data),e.getData&&(this._getData=e.getData),void 0!==e.minResubscribeDelay&&(this._minResubscribeDelay=e.minResubscribeDelay),void 0!==e.maxResubscribeDelay&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),true===e.positioned&&(this._positioned=true),true===e.recoverable&&(this._recoverable=true),true===e.joinLeave&&(this._joinLeave=true))}_getOffset(){var e=this._offset;return null!==e?e:0}_getEpoch(){var e=this._epoch;return null!==e?e:''}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._centrifuge._debug('get subscription token for channel',this.channel);var e={channel:this.channel};var t=this._getToken;if(null===t)throw this.emit('error',{type:'configuration',channel:this.channel,error:{code:exports.errorCodes.badConfiguration,message:'provide a function to get channel subscription token'}}),new UnauthorizedError('');return t(e)}_refresh(){this._clearRefreshTimeout();var e=this;this._getSubscriptionToken().then((function(t){e._isSubscribed()&&(t?(e._token=t,e._centrifuge._call({sub_refresh:{channel:e.channel,token:t}}).then((t=>{e._refreshResponse(t.reply.sub_refresh),t.next&&t.next()}),(t=>{e._refreshError(t.error),t.next&&t.next()}))):e._failUnauthorized())})).catch((function(t){t instanceof UnauthorizedError?e._failUnauthorized():(e.emit('error',{type:'refreshToken',channel:e.channel,error:{code:exports.errorCodes.subscriptionRefreshToken,message:void 0!==t?t.toString():''}}),e._refreshTimeout=setTimeout((()=>e._refresh()),e._getRefreshRetryDelay()))}))}_refreshResponse(e){this._isSubscribed()&&(this._centrifuge._debug('subscription token refreshed, channel',this.channel),this._clearRefreshTimeout(),true===e.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),E(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||true===e.temporary?(this.emit('error',{type:'refresh',channel:this.channel,error:e}),this._refreshTimeout=setTimeout((()=>this._refresh()),this._getRefreshRetryDelay())):this._setUnsubscribed(e.code,e.message,true))}_getRefreshRetryDelay(){return k(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(exports.unsubscribedCodes.unauthorized,'unauthorized',true)}}class SockjsTransport{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return'sockjs'}subName(){return'sockjs-'+this._transport.transport}emulation(){return false}supported(){return null!==this.options.sockjs}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class WebsocketTransport{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return'websocket'}subName(){return'websocket'}emulation(){return false}supported(){return null!=this.options.websocket}initialize(e,t){var s='';'protobuf'===e&&(s='centrifuge-protobuf'),this._transport=''!==s?new this.options.websocket(this.endpoint,s):new this.options.websocket(this.endpoint),'protobuf'===e&&(this._transport.binaryType='arraybuffer'),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class HttpStreamTransport{constructor(e,t){this.endpoint=e,this.options=t,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol='json'}name(){return'http_stream'}subName(){return'http_stream'}emulation(){return true}_handleErrors(e){if(!e.ok)throw new Error(e.status);return e}_fetchEventTarget(e,t,s){var r=new EventTarget;return(0,e.options.fetch)(t,s).then(e._handleErrors).then((t=>{r.dispatchEvent(new Event('open'));var s='';var n=0;var i=new Uint8Array;var o=t.body.getReader();return new e.options.readableStream({start:t=>function a(){return o.read().then((o=>{var{done:c,value:h}=o;if(c)return r.dispatchEvent(new Event('close')),void t.close();try{if('json'===e._protocol)for(s+=e._utf8decoder.decode(h);n<s.length;)if('\n'===s[n]){var u=s.substring(0,n);r.dispatchEvent(new MessageEvent('message',{data:u})),s=s.substring(n+1),n=0}else++n;else{var l=new Uint8Array(i.length+h.length);for(l.set(i),l.set(h,i.length),i=l;;){var d=e.options.decoder.decodeReply(i);if(!d.ok)break;var _=i.slice(0,d.pos);r.dispatchEvent(new MessageEvent('message',{data:_})),i=i.slice(d.pos)}}}catch(e){return r.dispatchEvent(new Event('error',{detail:e})),r.dispatchEvent(new Event('close')),void t.close()}a()})).catch((function(e){r.dispatchEvent(new Event('error',{detail:e})),r.dispatchEvent(new Event('close')),t.close()}))}()})})).catch((e=>{r.dispatchEvent(new Event('error',{detail:e})),r.dispatchEvent(new Event('close'))})),r}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&'undefined'!=typeof TextDecoder&&'undefined'!=typeof AbortController&&'undefined'!=typeof EventTarget&&'undefined'!=typeof Event&&'undefined'!=typeof MessageEvent&&'undefined'!=typeof Error}initialize(e,t,s){var r;var n;this._protocol=e,this._abortController=new AbortController,'json'===e?(r={Accept:'application/json','Content-Type':'application/json'},n=s):(r={Accept:'application/octet-stream','Content-Type':'application/octet-stream'},n=s);var i=this._fetchEventTarget(this,this.endpoint,{method:'POST',headers:r,body:n,mode:'cors',credentials:'same-origin',cache:'no-cache',signal:this._abortController.signal});i.addEventListener('open',(()=>{t.onOpen()})),i.addEventListener('error',(e=>{this._abortController.abort(),t.onError(e)})),i.addEventListener('close',(()=>{this._abortController.abort(),t.onClose({code:4,reason:'connection closed'})})),i.addEventListener('message',(e=>{t.onMessage(e.data)}))}close(){this._abortController.abort()}send(e,t,s){var r;var n;var i={session:t,node:s,data:e};'json'===this._protocol?(r={'Content-Type':'application/json'},n=JSON.stringify(i)):(r={'Content-Type':'application/octet-stream'},n=this.options.encoder.encodeEmulationRequest(i)),(0,this.options.fetch)(this.options.emulationEndpoint,{method:'POST',headers:r,body:n,mode:'cors',credentials:'same-origin',cache:'no-cache'})}}class SseTransport{constructor(e,t){this.endpoint=e,this.options=t,this._protocol='json',this._transport=null,this._onClose=null}name(){return'sse'}subName(){return'sse'}emulation(){return true}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(e,t,s){var r;(r=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint)).searchParams.append('cf_connect',s);var n=new this.options.eventsource(r.toString(),{});this._transport=n,n.onopen=function(){t.onOpen()},n.onerror=function(e){n.close(),t.onError(e),t.onClose({code:4,reason:'connection closed'})},n.onmessage=function(e){t.onMessage(e.data)},this._onClose=function(){t.onClose({code:4,reason:'connection closed'})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(e,t,s){var r=JSON.stringify({session:t,node:s,data:e});(0,this.options.fetch)(this.options.emulationEndpoint,{method:'POST',headers:{'Content-Type':'application/json'},body:r,mode:'cors',credentials:'same-origin',cache:'no-cache'})}}function P(e,t,s,r){return new(s||(s=Promise))((function(n,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class WebtransportTransport{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol='json'}name(){return'webtransport'}subName(){return'webtransport'}emulation(){return false}supported(){return null!=this.options.webtransport}initialize(e,t){return P(this,void 0,void 0,(function*(){var s;s=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),'protobuf'===e&&s.searchParams.append('cf_protocol','protobuf'),this._protocol=e;var r=new EventTarget;this._transport=new this.options.webtransport(s.toString()),this._transport.closed.then((()=>{t.onClose({code:4,reason:'connection closed'})})).catch((()=>{t.onClose({code:4,reason:'connection closed'})}));try{yield this._transport.ready}catch(e){return void this.close()}var n;try{n=yield this._transport.createBidirectionalStream()}catch(e){return void this.close()}this._stream=n,this._writer=this._stream.writable.getWriter(),r.addEventListener('close',(()=>{t.onClose({code:4,reason:'connection closed'})})),r.addEventListener('message',(e=>{t.onMessage(e.data)})),this._startReading(r),t.onOpen()}))}_startReading(e){return P(this,void 0,void 0,(function*(){var t=this._stream.readable.getReader();var s='';var r=0;var n=new Uint8Array;try{for(;;){var{done:i,value:o}=yield t.read();if(o.length>0)if('json'===this._protocol)for(s+=this._utf8decoder.decode(o);r<s.length;)if('\n'===s[r]){var a=s.substring(0,r);e.dispatchEvent(new MessageEvent('message',{data:a})),s=s.substring(r+1),r=0}else++r;else{var c=new Uint8Array(n.length+o.length);for(c.set(n),c.set(o,n.length),n=c;;){var h=this.options.decoder.decodeReply(n);if(!h.ok)break;var u=n.slice(0,h.pos);e.dispatchEvent(new MessageEvent('message',{data:u})),n=n.slice(h.pos)}}if(i)break}}catch(t){e.dispatchEvent(new Event('close'))}}))}close(){return P(this,void 0,void 0,(function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}}))}send(e){return P(this,void 0,void 0,(function*(){var t;t='json'===this._protocol?(new TextEncoder).encode(e+'\n'):e;try{yield this._writer.write(t)}catch(e){this.close()}}))}}class JsonCodec{name(){return'json'}encodeCommands(e){return e.map((e=>JSON.stringify(e))).join('\n')}decodeReplies(e){return e.trim().split('\n').map((e=>JSON.parse(e)))}}var R={token:'',getToken:null,data:null,getData:null,debug:false,name:'js',version:'',fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:'/emulation',minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class UnauthorizedError extends Error{constructor(e){super(e),this.name=this.constructor.name}}class Centrifuge extends v{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=exports.State.Disconnected,this._transportIsOpen=false,this._endpoint=e,this._emulation=false,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=false,this._transportWasOpen=false,this._transport=null,this._transportId=0,this._deviceWentOffline=false,this._transportClosed=true,this._codec=new JsonCodec,this._reconnecting=false,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session='',this._node='',this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=false,this._refreshRequired=false,this._refreshTimeout=null,this._callbacks={},this._token='',this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=false,this._promises={},this._promiseId=0,this._debugEnabled=false,this._networkEventsSet=false,this._config=Object.assign(Object.assign({},R),t),this._configure(),this._debugEnabled?(this.on('state',(e=>{this._debug('client state',e.oldState,'->',e.newState)})),this.on('error',(e=>{this._debug('client error',e)}))):this.on('error',(function(){Function.prototype()}))}newSubscription(e,t){if(null!==this.getSubscription(e))throw new Error('Subscription to the channel '+e+' already exists');var s=new Subscription(this,e,t);return this._subs[e]=s,s}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==exports.SubscriptionState.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return this.state===exports.State.Disconnected?Promise.reject({code:exports.errorCodes.clientDisconnected,message:'client disconnected'}):this.state===exports.State.Connected?Promise.resolve():new Promise(((t,s)=>{var r={resolve:t,reject:s};e&&(r.timeout=setTimeout((function(){s({code:exports.errorCodes.timeout,message:'timeout'})}),e)),this._promises[this._nextPromiseId()]=r}))}connect(){this._isConnected()?this._debug('connect called when already connected'):this._isConnecting()?this._debug('connect called when already connecting'):(this._debug('connect called'),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(exports.disconnectedCodes.disconnectCalled,'disconnect called',false)}setToken(e){this._token=e}send(e){var t={send:{data:e}};var s=this;return this._methodCall().then((function(){return s._transportSendCommands([t])?Promise.resolve():Promise.reject(s._createErrorObject(exports.errorCodes.transportWriteError,'transport write error'))}))}rpc(e,t){var s={rpc:{method:e,data:t}};var r=this;return this._methodCall().then((function(){return r._callPromise(s,(function(e){return{data:e.rpc.data}}))}))}publish(e,t){var s={publish:{channel:e,data:t}};var r=this;return this._methodCall().then((function(){return r._callPromise(s,(function(){return{}}))}))}history(e,t){var s={history:this._getHistoryRequest(e,t)};var r=this;return this._methodCall().then((function(){return r._callPromise(s,(function(t){var s=t.history;var n=[];if(s.publications)for(var i=0;i<s.publications.length;i++)n.push(r._getPublicationContext(e,s.publications[i]));return{publications:n,epoch:s.epoch||'',offset:s.offset||0}}))}))}presence(e){var t={presence:{channel:e}};var s=this;return this._methodCall().then((function(){return s._callPromise(t,(function(e){var t=e.presence.presence;for(var s in t)if(t.hasOwnProperty(s)){var r=t[s].conn_info;var n=t[s].chan_info;r&&(t[s].connInfo=r),n&&(t[s].chanInfo=n)}return{clients:t}}))}))}presenceStats(e){var t={presence_stats:{channel:e}};var s=this;return this._methodCall().then((function(){return s._callPromise(t,(function(e){var t=e.presence_stats;return{numUsers:t.num_users,numClients:t.num_clients}}))}))}startBatching(){this._batching=true}stopBatching(){var e=this;Promise.resolve().then((function(){Promise.resolve().then((function(){e._batching=false,e._flush()}))}))}_debug(){if(this._debugEnabled){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];(function(e,t){if(globalThis.console){var s=globalThis.console.debug;w(s)&&s.apply(globalThis.console,t)}})(0,t)}}_formatOverride(){}_configure(){if(!('Promise'in globalThis))throw new Error('Promise polyfill required');if(!this._endpoint)throw new Error('endpoint configuration required');if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new JsonCodec,this._formatOverride(),(true===this._config.debug||'undefined'!=typeof localStorage&&localStorage.getItem('centrifuge.debug'))&&(this._debugEnabled=true),this._debug('config',this._config),'string'==typeof this._endpoint);else{if(!('object'==typeof this._endpoint&&this._endpoint instanceof Array))throw new Error('unsupported url configuration type: only string or array of objects are supported');for(var e in this._transports=this._endpoint,this._emulation=true,this._transports)if(this._transports.hasOwnProperty(e)){var t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error('malformed transport configuration');var s=t.transport;if(['websocket','http_stream','sse','sockjs','webtransport'].indexOf(s)<0)throw new Error('unsupported transport name: '+s)}}}_setState(e){if(this.state!==e){this._reconnecting=false;var t=this.state;return this.state=e,this.emit('state',{newState:e,oldState:t}),true}return false}_isDisconnected(){return this.state===exports.State.Disconnected}_isConnecting(){return this.state===exports.State.Connecting}_isConnected(){return this.state===exports.State.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(!this._networkEventsSet){var e=null;null!==this._config.networkEventTarget?e=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(e=globalThis),e&&(e.addEventListener('offline',(()=>{this._debug('offline event triggered'),this.state!==exports.State.Connected&&this.state!==exports.State.Connecting||(this._disconnect(exports.connectingCodes.transportClosed,'transport closed',true),this._deviceWentOffline=true)})),e.addEventListener('online',(()=>{this._debug('online event triggered'),this.state===exports.State.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=false,this._transportClosed=true),this._clearReconnectTimeout(),this._startReconnecting())})),this._networkEventsSet=true)}}_getReconnectDelay(){var e=k(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(var e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){var t=this._callbacks[e];clearTimeout(t.timeout);var s=t.errback;if(!s)continue;s({error:this._createErrorObject(exports.errorCodes.connectionClosed,'connection closed')})}this._callbacks={}}_clearConnectedState(){for(var e in this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout(),this._subs)if(this._subs.hasOwnProperty(e)){var t=this._subs[e];t.state===exports.SubscriptionState.Subscribed&&t._setSubscribing(exports.subscribingCodes.transportClosed,'transport closed')}for(var s in this._serverSubs)this._serverSubs.hasOwnProperty(s)&&this.emit('subscribing',{channel:s})}_handleWriteError(e){for(var t of e){var s=t.id;if(s in this._callbacks){var r=this._callbacks[s];clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],(0,r.errback)({error:this._createErrorObject(exports.errorCodes.transportWriteError,'transport write error')})}}}_transportSendCommands(e){if(!e.length)return true;if(!this._transport)return false;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug('error writing commands',t),this._handleWriteError(e),false}return true}_initializeTransport(){var e;null!==this._config.websocket?e=this._config.websocket:'function'!=typeof globalThis.WebSocket&&'object'!=typeof globalThis.WebSocket||(e=globalThis.WebSocket);var t=null;null!==this._config.sockjs?t=this._config.sockjs:void 0!==globalThis.SockJS&&(t=globalThis.SockJS);var s=null;null!==this._config.eventsource?s=this._config.eventsource:void 0!==globalThis.EventSource&&(s=globalThis.EventSource);var r=null;null!==this._config.fetch?r=this._config.fetch:void 0!==globalThis.fetch&&(r=globalThis.fetch);var n=null;if(null!==this._config.readableStream?n=this._config.readableStream:void 0!==globalThis.ReadableStream&&(n=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=true,this._currentTransportIndex=0);var i=0;for(;;){if(i>=this._transports.length)throw new Error('no supported transport found');var o=this._transports[this._currentTransportIndex];var a=o.transport;var c=o.endpoint;if('websocket'===a){if(this._debug('trying websocket transport'),this._transport=new WebsocketTransport(c,{websocket:e}),!this._transport.supported()){this._debug('websocket transport not available'),this._currentTransportIndex++,i++;continue}}else if('webtransport'===a){if(this._debug('trying webtransport transport'),this._transport=new WebtransportTransport(c,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug('webtransport transport not available'),this._currentTransportIndex++,i++;continue}}else if('http_stream'===a){if(this._debug('trying http_stream transport'),this._transport=new HttpStreamTransport(c,{fetch:r,readableStream:n,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug('http_stream transport not available'),this._currentTransportIndex++,i++;continue}}else if('sse'===a){if(this._debug('trying sse transport'),this._transport=new SseTransport(c,{eventsource:s,fetch:r,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug('sse transport not available'),this._currentTransportIndex++,i++;continue}}else{if('sockjs'!==a)throw new Error('unknown transport '+a);if(this._debug('trying sockjs'),this._transport=new SockjsTransport(c,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug('sockjs transport not available'),this._currentTransportIndex++,i++;continue}}break}}else{if(0===this._endpoint.lastIndexOf('http',0))throw new Error('Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport');if(this._debug('client will use websocket'),this._transport=new WebsocketTransport(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error('WebSocket not available')}var h=this;var u=this._transport;var l=this._nextTransportId();h._debug("id of transport",l);var d=false;var _=[];if(this._transport.emulation()){var p=h._sendConnect(true);_.push(p)}this._setNetworkEvents();var f=this._codec.encodeCommands(_);var b;this._transportClosed=false,b=setTimeout((function(){u.close()}),this._config.timeout),this._transport.initialize(this._codec.name(),{onOpen:function(){if(b&&(clearTimeout(b),b=null),h._transportId!=l)return h._debug('open callback from non-actual transport'),void u.close();d=true,h._debug(u.subName(),'transport open'),u.emulation()||(h._transportIsOpen=true,h._transportWasOpen=true,h.startBatching(),h._sendConnect(false),h._sendSubscribeCommands(),h.stopBatching(),h.emit('__centrifuge_debug:connect_frame_sent',{}))},onError:function(e){h._transportId==l?h._debug('transport level error',e):h._debug('error callback from non-actual transport')},onClose:function(e){if(b&&(clearTimeout(b),b=null),h._transportId==l){h._debug(u.subName(),'transport closed'),h._transportClosed=true,h._transportIsOpen=false;var t='connection closed';var s=true;var r=0;if(e&&'code'in e&&e.code&&(r=e.code),e&&e.reason)try{var n=JSON.parse(e.reason);t=n.reason,s=n.reconnect}catch(n){t=e.reason,(r>=3500&&r<4e3||r>=4500&&r<5e3)&&(s=false)}r<3e3?(1009===r?(r=exports.disconnectedCodes.messageSizeLimit,t='message size limit exceeded',s=false):(r=exports.connectingCodes.transportClosed,t='transport closed'),h._emulation&&!h._transportWasOpen&&(h._currentTransportIndex++,h._currentTransportIndex>=h._transports.length&&(h._triedAllTransports=true,h._currentTransportIndex=0))):h._transportWasOpen=true,h._isConnecting()&&!d&&h.emit('error',{type:'transport',error:{code:exports.errorCodes.transportClosed,message:'transport closed'},transport:u.name()}),h._reconnecting=false,h._disconnect(r,t,s)}else h._debug('close callback from non-actual transport')},onMessage:function(e){h._dataReceived(e)}},f),h.emit('__centrifuge_debug:transport_initialized',{})}_sendConnect(e){var t=this._constructConnectCommand();var s=this;return this._call(t,e).then((e=>{s._connectResponse(e.reply.connect),e.next&&e.next()}),(e=>{s._connectError(e.error),e.next&&e.next()})),t}_startReconnecting(){if(this._debug('start reconnecting'),this._isConnecting())if(this._reconnecting)this._debug('reconnect already in progress, return from reconnect routine');else if(false!==this._transportClosed){this._reconnecting=true;var e=this;this._refreshRequired||''===this._token&&null!==this._config.getToken?this._getToken().then((function(t){e._isConnecting()&&(null!=t&&null!=t?(e._token=t,e._debug('connection token refreshed'),e._config.getData?e._config.getData().then((function(t){e._isConnecting()&&(e._data=t,e._initializeTransport())})):e._initializeTransport()):e._failUnauthorized())})).catch((function(t){if(e._isConnecting())if(t instanceof UnauthorizedError)e._failUnauthorized();else{e.emit('error',{type:'connectToken',error:{code:exports.errorCodes.clientConnectToken,message:void 0!==t?t.toString():''}});var s=e._getReconnectDelay();e._debug('error on connection token refresh, reconnect after '+s+' milliseconds',t),e._reconnecting=false,e._reconnectTimeout=setTimeout((()=>{e._startReconnecting()}),s)}})):this._config.getData?this._config.getData().then((function(t){e._isConnecting()&&(e._data=t,e._initializeTransport())})):this._initializeTransport()}else this._debug('waiting for transport close');else this._debug('stop reconnecting: client not in connecting state')}_connectError(e){this.state===exports.State.Connecting&&(109===e.code&&(this._refreshRequired=true),e.code<100||true===e.temporary||109===e.code?(this.emit('error',{type:'connect',error:e}),this._debug('closing transport due to connect error'),this._disconnect(e.code,e.message,true)):this._disconnect(e.code,e.message,false))}_scheduleReconnect(){if(this._isConnecting()){var e=false;!this._emulation||this._transportWasOpen||this._triedAllTransports||(e=true);var t=this._getReconnectDelay();e&&(t=0),this._debug('reconnect after '+t+' milliseconds'),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout((()=>{this._startReconnecting()}),t)}}_constructConnectCommand(){var e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version);var t={};var s=false;for(var r in this._serverSubs)if(this._serverSubs.hasOwnProperty(r)&&this._serverSubs[r].recoverable){s=true;var n={recover:true};this._serverSubs[r].offset&&(n.offset=this._serverSubs[r].offset),this._serverSubs[r].epoch&&(n.epoch=this._serverSubs[r].epoch),t[r]=n}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){var s={channel:e};return void 0!==t&&(t.since&&(s.since={offset:t.since.offset},t.since.epoch&&(s.since.epoch=t.since.epoch)),void 0!==t.limit&&(s.limit=t.limit),true===t.reverse&&(s.reverse=true)),s}_methodCall(){return this._isConnected()?Promise.resolve():new Promise(((e,t)=>{var s=setTimeout((function(){t({code:exports.errorCodes.timeout,message:'timeout'})}),this._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}}))}_callPromise(e,t){return new Promise(((s,r)=>{this._call(e,false).then((e=>{s(t(e.reply)),e.next&&e.next()}),(e=>{r(e.error),e.next&&e.next()}))}))}_dataReceived(e){this._serverPing>0&&this._waitServerPing();var t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then((()=>{var e;this._dispatchPromise=new Promise((t=>{e=t})),this._dispatchSynchronized(t,e)}))}_dispatchSynchronized(e,t){var s=this;var r=Promise.resolve();var n=function(t){e.hasOwnProperty(t)&&(r=r.then((()=>s._dispatchReply(e[t]))))};for(var i in e)n(i);r=r.then((()=>{t()}))}_dispatchReply(e){var t;var s=new Promise((e=>{t=e}));if(null==e)return this._debug('dispatch: got undefined or null reply'),t(),s;var r=e.id;return r&&r>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),s}_call(e,t){return new Promise(((s,r)=>{e.id=this._nextCommandId(),this._registerCall(e.id,s,r),t||this._addCommand(e)}))}_startConnecting(){this._debug('start connecting'),this._setState(exports.State.Connecting)&&this.emit('connecting',{code:exports.connectingCodes.connectCalled,reason:'connect called'}),this._client=null,this._startReconnecting()}_disconnect(e,t,s){if(!this._isDisconnected()){this._transportIsOpen=false;var r=this.state;this._reconnecting=false;var n={code:e,reason:t};var i=false;if(s?i=this._setState(exports.State.Connecting):(i=this._setState(exports.State.Disconnected),this._rejectPromises({code:exports.errorCodes.clientDisconnected,message:'disconnected'})),this._clearOutgoingRequests(),r===exports.State.Connecting&&this._clearReconnectTimeout(),r===exports.State.Connected&&this._clearConnectedState(),i&&(this._isConnecting()?this.emit('connecting',n):this.emit('disconnected',n)),this._transport){this._debug("closing existing transport");var o=this._transport;this._transport=null,o.close(),this._transportClosed=true,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}}_failUnauthorized(){this._disconnect(exports.disconnectedCodes.unauthorized,'unauthorized',false)}_getToken(){if(this._debug('get connection token'),!this._config.getToken)throw this.emit('error',{type:'configuration',error:{code:exports.errorCodes.badConfiguration,message:'token expired but no getToken function set in the configuration'}}),new UnauthorizedError('');return this._config.getToken({})}_refresh(){var e=this._client;var t=this;this._getToken().then((function(s){e===t._client&&(s?(t._token=s,t._debug('connection token refreshed'),t._isConnected()&&t._call({refresh:{token:t._token}},false).then((e=>{t._refreshResponse(e.reply.refresh),e.next&&e.next()}),(e=>{t._refreshError(e.error),e.next&&e.next()}))):t._failUnauthorized())})).catch((function(e){t._isConnected()&&(e instanceof UnauthorizedError?t._failUnauthorized():(t.emit('error',{type:'refreshToken',error:{code:exports.errorCodes.clientRefreshToken,message:void 0!==e?e.toString():''}}),t._refreshTimeout=setTimeout((()=>t._refresh()),t._getRefreshRetryDelay())))}))}_refreshError(e){e.code<100||true===e.temporary?(this.emit('error',{type:'refresh',error:e}),this._refreshTimeout=setTimeout((()=>this._refresh()),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,false)}_getRefreshRetryDelay(){return k(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout((()=>this._refresh()),E(e.ttl)))}_removeSubscription(e){null!==e&&delete this._subs[e.channel]}_unsubscribe(e){if(this._transportIsOpen){var t=this;this._call({unsubscribe:{channel:e.channel}},false).then((e=>{e.next&&e.next()}),(e=>{e.next&&e.next(),t._disconnect(exports.connectingCodes.unsubscribeError,'unsubscribe error',true)}))}}_getSub(e){return this._subs[e]||null}_isServerSub(e){return void 0!==this._serverSubs[e]}_sendSubscribeCommands(){var e=[];for(var t in this._subs)if(this._subs.hasOwnProperty(t)){var s=this._subs[t];if(true!==s._inflight&&s.state===exports.SubscriptionState.Subscribing){var r=s._subscribe();r&&e.push(r)}}return e}_connectResponse(e){if(this._transportIsOpen=true,this._transportWasOpen=true,this._reconnectAttempts=0,this._refreshRequired=false,!this._isConnected()){this._client=e.client,this._setState(exports.State.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),E(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();var t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit('connected',t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=1e3*e.ping,this._sendPong=true===e.pong,this._waitServerPing()):this._serverPing=0}}_processServerSubs(e){for(var t in e)if(e.hasOwnProperty(t)){var s=e[t];this._serverSubs[t]={offset:s.offset,epoch:s.epoch,recoverable:s.recoverable||false};var r=this._getSubscribeContext(t,s);this.emit('subscribed',r)}for(var n in e)if(e.hasOwnProperty(n)){var i=e[n];if(i.recovered){var o=i.publications;if(o&&o.length>0)for(var a in o)o.hasOwnProperty(a)&&this._handlePublication(n,o[a])}}for(var c in this._serverSubs)this._serverSubs.hasOwnProperty(c)&&(e[c]||(this.emit('unsubscribed',{channel:c}),delete this._serverSubs[c]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout((()=>{this._isConnected()&&this._disconnect(exports.connectingCodes.noPing,'no ping',true)}),this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){var s={channel:e,positioned:false,recoverable:false,wasRecovering:false,recovered:false};t.recovered&&(s.recovered=true),t.positioned&&(s.positioned=true),t.recoverable&&(s.recoverable=true),t.was_recovering&&(s.wasRecovering=true);var r='';'epoch'in t&&(r=t.epoch);var n=0;return'offset'in t&&(n=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:n,epoch:r}),t.data&&(s.data=t.data),s}_handleReply(e,t){var s=e.id;if(s in this._callbacks){var r=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],'error'in(o=e)&&null!==o.error){var n=r.errback;if(!n)return void t();n({error:e.error,next:t})}else{var i=r.callback;if(!i)return;i({reply:e,next:t})}var o}else t()}_handleJoin(e,t){var s=this._getSub(e);if(s)s._handleJoin(t);else if(this._isServerSub(e)){var r={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit('join',r)}}_handleLeave(e,t){var s=this._getSub(e);if(s)s._handleLeave(t);else if(this._isServerSub(e)){var r={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit('leave',r)}}_handleUnsubscribe(e,t){var s=this._getSub(e);s?t.code<2500?s._setUnsubscribed(t.code,t.reason,false):s._setSubscribing(t.code,t.reason):this._isServerSub(e)&&(delete this._serverSubs[e],this.emit('unsubscribed',{channel:e}))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||false},this.emit('subscribed',this._getSubscribeContext(e,t))}_handleDisconnect(e){var t=e.code;var s=true;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=false),this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){var s={channel:e,data:t.data};return t.offset&&(s.offset=t.offset),t.info&&(s.info=this._getJoinLeaveContext(t.info)),t.tags&&(s.tags=t.tags),s}_getJoinLeaveContext(e){var t={client:e.client,user:e.user};return e.conn_info&&(t.connInfo=e.conn_info),e.chan_info&&(t.chanInfo=e.chan_info),t}_handlePublication(e,t){var s=this._getSub(e);if(s)s._handlePublication(t);else if(this._isServerSub(e)){var r=this._getPublicationContext(e,t);this.emit('publication',r),void 0!==t.offset&&(this._serverSubs[e].offset=t.offset)}}_handleMessage(e){this.emit('message',{data:e.data})}_handleServerPing(e){this._sendPong&&this._transportSendCommands([{}]),e()}_handlePush(e,t){var s=e.channel;e.pub?this._handlePublication(s,e.pub):e.message?this._handleMessage(e.message):e.join?this._handleJoin(s,e.join):e.leave?this._handleLeave(s,e.leave):e.unsubscribe?this._handleUnsubscribe(s,e.unsubscribe):e.subscribe?this._handleSubscribe(s,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){var e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){var r={code:e,message:t};return s&&(r.temporary=true),r}_registerCall(e,t,s){this._callbacks[e]={callback:t,errback:s,timeout:null},this._callbacks[e].timeout=setTimeout((()=>{delete this._callbacks[e],w(s)&&s({error:this._createErrorObject(exports.errorCodes.timeout,'timeout')})}),this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(var e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(var t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}Centrifuge.SubscriptionState=exports.SubscriptionState,Centrifuge.State=exports.State,Centrifuge.UnauthorizedError=UnauthorizedError,exports.Centrifuge=Centrifuge,exports.Subscription=Subscription,exports.UnauthorizedError=UnauthorizedError;
@@ -0,0 +1 @@
1
+ function e(e){return e&&e.__esModule&&{}.hasOwnProperty.call(e,'default')?e.default:e}var t={exports:{}};var s='object'==typeof Reflect?Reflect:null;var n=s&&'function'==typeof s.apply?s.apply:function(e,t,s){return function(){}.apply.call(e,t,s)};var r;r=s&&'function'==typeof s.ownKeys?s.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}t.exports=o,t.exports.once=function(e,t){return new Promise((function(s,n){function r(s){e.removeListener(t,i),n(s)}function i(){'function'==typeof e.removeListener&&e.removeListener('error',r),s([].slice.call(arguments))}b(e,t,i,{once:true}),'error'!==t&&function(e,t){'function'==typeof e.on&&b(e,'error',t,{once:true})}(e,r)}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function c(e){if('function'!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,s,n){var r;var i;var o;if(c(s),void 0===(i=e._events)?(i=e._events=Object.create(null),e._eventsCount=0):(void 0!==i.newListener&&(e.emit('newListener',t,s.listener?s.listener:s),i=e._events),o=i[t]),void 0===o)o=i[t]=s,++e._eventsCount;else if('function'==typeof o?o=i[t]=n?[s,o]:[o,s]:n?o.unshift(s):o.push(s),(r=h(e))>0&&o.length>r&&!o.warned){o.warned=true;var a=new Error('Possible EventEmitter memory leak detected. '+o.length+' '+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name='MaxListenersExceededWarning',a.emitter=e,a.type=t,a.count=o.length,console&&console.warn&&console.warn(a)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=true,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _(e,t,s){var n={fired:false,wrapFn:void 0,target:e,type:t,listener:s};var r=l.bind(n);return r.listener=s,n.wrapFn=r,r}function d(e,t,s){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:'function'==typeof r?s?[r.listener||r]:[r]:s?function(e){var t=new Array(e.length);for(var s=0;s<t.length;++s)t[s]=e[s].listener||e[s];return t}(r):p(r,r.length)}function f(e){var t=this._events;if(void 0!==t){var s=t[e];if('function'==typeof s)return 1;if(void 0!==s)return s.length}return 0}function p(e,t){var s=new Array(t);for(var n=0;n<t;++n)s[n]=e[n];return s}function b(e,t,s,n){if('function'==typeof e.on)n.once?e.once(t,s):e.on(t,s);else{if('function'!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function r(i){n.once&&e.removeEventListener(t,r),s(i)}))}}Object.defineProperty(o,'defaultMaxListeners',{enumerable:true,get:function(){return a},set:function(e){if('number'!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+'.');a=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if('number'!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+'.');return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return h(this)},o.prototype.emit=function(e){var t=[];for(var s=1;s<arguments.length;s++)t.push(arguments[s]);var r='error'===e;var i=this._events;if(void 0!==i)r=r&&void 0===i.error;else if(!r)return false;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error('Unhandled error.'+(o?' ('+o.message+')':''));throw a.context=o,a}var c=i[e];if(void 0===c)return false;if('function'==typeof c)n(c,this,t);else{var h=c.length;var u=p(c,h);for(s=0;s<h;++s)n(u[s],this,t)}return true},o.prototype.on=o.prototype.addListener=function(e,t){return u(this,e,t,false)},o.prototype.prependListener=function(e,t){return u(this,e,t,true)},o.prototype.once=function(e,t){return c(t),this.on(e,_(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,_(this,e,t)),this},o.prototype.removeListener=function(e,t){var s,n,r,i,o;if(c(t),void 0===(n=this._events))return this;if(void 0===(s=n[e]))return this;if(s===t||s.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit('removeListener',e,s.listener||t));else if('function'!=typeof s){for(r=-1,i=s.length-1;i>=0;i--)if(s[i]===t||s[i].listener===t){o=s[i].listener,r=i;break}if(r<0)return this;0===r?s.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(s,r),1===s.length&&(n[e]=s[0]),void 0!==n.removeListener&&this.emit('removeListener',e,o||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,s,n;if(void 0===(s=this._events))return this;if(void 0===s.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==s[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete s[e]),this;if(0===arguments.length){var r=Object.keys(s);var i;for(n=0;n<r.length;++n)'removeListener'!==(i=r[n])&&this.removeAllListeners(i);return this.removeAllListeners('removeListener'),this._events=Object.create(null),this._eventsCount=0,this}if('function'==typeof(t=s[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return d(this,e,true)},o.prototype.rawListeners=function(e){return d(this,e,false)},o.listenerCount=function(e,t){return'function'==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},o.prototype.listenerCount=f,o.prototype.eventNames=function(){return this._eventsCount>0?r(this._events):[]};var m=e(t.exports);var v;var g;var y;var T;var S;var w;var C;function k(e){return null!=e&&'function'==typeof e}function E(e,t,s){e>31&&(e=31);var n=function(e,t){return Math.floor(Math.random()*(t-0+1)+0)}(0,Math.min(s,t*Math.pow(2,e)));return Math.min(s,t+n)}function P(e){return Math.min(1e3*e,2147483647)}(function(e){e[e.timeout=1]="timeout",e[e.transportClosed=2]="transportClosed",e[e.clientDisconnected=3]="clientDisconnected",e[e.clientClosed=4]="clientClosed",e[e.clientConnectToken=5]="clientConnectToken",e[e.clientRefreshToken=6]="clientRefreshToken",e[e.subscriptionUnsubscribed=7]="subscriptionUnsubscribed",e[e.subscriptionSubscribeToken=8]="subscriptionSubscribeToken",e[e.subscriptionRefreshToken=9]="subscriptionRefreshToken",e[e.transportWriteError=10]="transportWriteError",e[e.connectionClosed=11]="connectionClosed",e[e.badConfiguration=12]="badConfiguration"})(v||(v={})),function(e){e[e.connectCalled=0]="connectCalled",e[e.transportClosed=1]="transportClosed",e[e.noPing=2]="noPing",e[e.subscribeTimeout=3]="subscribeTimeout",e[e.unsubscribeError=4]="unsubscribeError"}(g||(g={})),function(e){e[e.disconnectCalled=0]="disconnectCalled",e[e.unauthorized=1]="unauthorized",e[e.badProtocol=2]="badProtocol",e[e.messageSizeLimit=3]="messageSizeLimit"}(y||(y={})),function(e){e[e.subscribeCalled=0]="subscribeCalled",e[e.transportClosed=1]="transportClosed"}(T||(T={})),function(e){e[e.unsubscribeCalled=0]="unsubscribeCalled",e[e.unauthorized=1]="unauthorized",e[e.clientClosed=2]="clientClosed"}(S||(S={})),function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected"}(w||(w={})),function(e){e.Unsubscribed="unsubscribed",e.Subscribing="subscribing",e.Subscribed="subscribed"}(C||(C={}));class Subscription extends m{constructor(e,t,s){super(),this._resubscribeTimeout=null,this._refreshTimeout=null,this.channel=t,this.state=C.Unsubscribed,this._centrifuge=e,this._token='',this._getToken=null,this._data=null,this._getData=null,this._recover=false,this._offset=null,this._epoch=null,this._recoverable=false,this._positioned=false,this._joinLeave=false,this._minResubscribeDelay=500,this._maxResubscribeDelay=2e4,this._resubscribeTimeout=null,this._resubscribeAttempts=0,this._promises={},this._promiseId=0,this._inflight=false,this._refreshTimeout=null,this._setOptions(s),this._centrifuge._debugEnabled?(this.on('state',(e=>{this._centrifuge._debug('subscription state',t,e.oldState,'->',e.newState)})),this.on('error',(e=>{this._centrifuge._debug('subscription error',t,e)}))):this.on('error',(function(){Function.prototype()}))}ready(e){return this.state===C.Unsubscribed?Promise.reject({code:v.subscriptionUnsubscribed,message:this.state}):this.state===C.Subscribed?Promise.resolve():new Promise(((t,s)=>{var n={resolve:t,reject:s};e&&(n.timeout=setTimeout((function(){s({code:v.timeout,message:'timeout'})}),e)),this._promises[this._nextPromiseId()]=n}))}subscribe(){this._isSubscribed()||(this._resubscribeAttempts=0,this._setSubscribing(T.subscribeCalled,'subscribe called'))}unsubscribe(){this._setUnsubscribed(S.unsubscribeCalled,'unsubscribe called',true)}publish(e){var t=this;return this._methodCall().then((function(){return t._centrifuge.publish(t.channel,e)}))}presence(){var e=this;return this._methodCall().then((function(){return e._centrifuge.presence(e.channel)}))}presenceStats(){var e=this;return this._methodCall().then((function(){return e._centrifuge.presenceStats(e.channel)}))}history(e){var t=this;return this._methodCall().then((function(){return t._centrifuge.history(t.channel,e)}))}_methodCall(){return this._isSubscribed()?Promise.resolve():this._isUnsubscribed()?Promise.reject({code:v.subscriptionUnsubscribed,message:this.state}):new Promise(((e,t)=>{var s=setTimeout((function(){t({code:v.timeout,message:'timeout'})}),this._centrifuge._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}}))}_nextPromiseId(){return++this._promiseId}_needRecover(){return true===this._recover}_isUnsubscribed(){return this.state===C.Unsubscribed}_isSubscribing(){return this.state===C.Subscribing}_isSubscribed(){return this.state===C.Subscribed}_setState(e){if(this.state!==e){var t=this.state;return this.state=e,this.emit('state',{newState:e,oldState:t,channel:this.channel}),true}return false}_usesToken(){return''!==this._token||null!==this._getToken}_clearSubscribingState(){this._resubscribeAttempts=0,this._clearResubscribeTimeout()}_clearSubscribedState(){this._clearRefreshTimeout()}_setSubscribed(e){if(this._isSubscribing()){this._clearSubscribingState(),e.recoverable&&(this._recover=true,this._offset=e.offset||0,this._epoch=e.epoch||''),this._setState(C.Subscribed);var t=this._centrifuge._getSubscribeContext(this.channel,e);this.emit('subscribed',t),this._resolvePromises();var s=e.publications;if(s&&s.length>0)for(var n in s)s.hasOwnProperty(n)&&this._handlePublication(s[n]);true===e.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),P(e.ttl)))}}_setSubscribing(e,t){this._isSubscribing()||(this._isSubscribed()&&this._clearSubscribedState(),this._setState(C.Subscribing)&&this.emit('subscribing',{channel:this.channel,code:e,reason:t}),this._subscribe())}_subscribe(){if(this._centrifuge._debug('subscribing on',this.channel),!this._centrifuge._transportIsOpen)return this._centrifuge._debug('delay subscribe on',this.channel,'till connected'),null;var e=this;var t={channel:e.channel};return!this._usesToken()||this._token?e._getData?(e._getData(t).then((function(t){e._isSubscribing()&&(e._data=t,e._sendSubscribe(e._token))})),null):e._sendSubscribe(e._token):(this._getSubscriptionToken().then((function(s){e._isSubscribing()&&(s?(e._token=s,e._getData?e._getData(t).then((function(t){e._isSubscribing()&&(e._data=t,e._sendSubscribe(s))})):e._sendSubscribe(s)):e._failUnauthorized())})).catch((function(t){e._isSubscribing()&&(t instanceof UnauthorizedError?e._failUnauthorized():(e.emit('error',{type:'subscribeToken',channel:e.channel,error:{code:v.subscriptionSubscribeToken,message:void 0!==t?t.toString():''}}),e._scheduleResubscribe()))})),null)}_sendSubscribe(e){if(!this._centrifuge._transportIsOpen)return null;var t={channel:this.channel};if(e&&(t.token=e),this._data&&(t.data=this._data),this._positioned&&(t.positioned=true),this._recoverable&&(t.recoverable=true),this._joinLeave&&(t.join_leave=true),this._needRecover()){t.recover=true;var s=this._getOffset();s&&(t.offset=s);var n=this._getEpoch();n&&(t.epoch=n)}var r={subscribe:t};return this._inflight=true,this._centrifuge._call(r).then((e=>{this._inflight=false,this._handleSubscribeResponse(e.reply.subscribe),e.next&&e.next()}),(e=>{this._inflight=false,this._handleSubscribeError(e.error),e.next&&e.next()})),r}_handleSubscribeError(e){this._isSubscribing()&&(e.code!==v.timeout?this._subscribeError(e):this._centrifuge._disconnect(g.subscribeTimeout,'subscribe timeout',true))}_handleSubscribeResponse(e){this._isSubscribing()&&this._setSubscribed(e)}_setUnsubscribed(e,t,s){this._isUnsubscribed()||(this._isSubscribed()&&(s&&this._centrifuge._unsubscribe(this),this._clearSubscribedState()),this._isSubscribing()&&(this._inflight&&s&&this._centrifuge._unsubscribe(this),this._clearSubscribingState()),this._setState(C.Unsubscribed)&&this.emit('unsubscribed',{channel:this.channel,code:e,reason:t}),this._rejectPromises({code:v.subscriptionUnsubscribed,message:this.state}))}_handlePublication(e){var t=this._centrifuge._getPublicationContext(this.channel,e);this.emit('publication',t),e.offset&&(this._offset=e.offset)}_handleJoin(e){var t=this._centrifuge._getJoinLeaveContext(e.info);this.emit('join',{channel:this.channel,info:t})}_handleLeave(e){var t=this._centrifuge._getJoinLeaveContext(e.info);this.emit('leave',{channel:this.channel,info:t})}_resolvePromises(){for(var e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(var t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}_scheduleResubscribe(){var e=this;var t=this._getResubscribeDelay();this._resubscribeTimeout=setTimeout((function(){e._isSubscribing()&&e._subscribe()}),t)}_subscribeError(e){this._isSubscribing()&&(e.code<100||109===e.code||true===e.temporary?(109===e.code&&(this._token=''),this._centrifuge.state===w.Connected&&this.emit('error',{channel:this.channel,type:'subscribe',error:e}),this._scheduleResubscribe()):this._setUnsubscribed(e.code,e.message,false))}_getResubscribeDelay(){var e=E(this._resubscribeAttempts,this._minResubscribeDelay,this._maxResubscribeDelay);return this._resubscribeAttempts++,e}_setOptions(e){e&&(e.since&&(this._offset=e.since.offset,this._epoch=e.since.epoch,this._recover=true),e.data&&(this._data=e.data),e.getData&&(this._getData=e.getData),void 0!==e.minResubscribeDelay&&(this._minResubscribeDelay=e.minResubscribeDelay),void 0!==e.maxResubscribeDelay&&(this._maxResubscribeDelay=e.maxResubscribeDelay),e.token&&(this._token=e.token),e.getToken&&(this._getToken=e.getToken),true===e.positioned&&(this._positioned=true),true===e.recoverable&&(this._recoverable=true),true===e.joinLeave&&(this._joinLeave=true))}_getOffset(){var e=this._offset;return null!==e?e:0}_getEpoch(){var e=this._epoch;return null!==e?e:''}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearResubscribeTimeout(){null!==this._resubscribeTimeout&&(clearTimeout(this._resubscribeTimeout),this._resubscribeTimeout=null)}_getSubscriptionToken(){this._centrifuge._debug('get subscription token for channel',this.channel);var e={channel:this.channel};var t=this._getToken;if(null===t)throw this.emit('error',{type:'configuration',channel:this.channel,error:{code:v.badConfiguration,message:'provide a function to get channel subscription token'}}),new UnauthorizedError('');return t(e)}_refresh(){this._clearRefreshTimeout();var e=this;this._getSubscriptionToken().then((function(t){e._isSubscribed()&&(t?(e._token=t,e._centrifuge._call({sub_refresh:{channel:e.channel,token:t}}).then((t=>{e._refreshResponse(t.reply.sub_refresh),t.next&&t.next()}),(t=>{e._refreshError(t.error),t.next&&t.next()}))):e._failUnauthorized())})).catch((function(t){t instanceof UnauthorizedError?e._failUnauthorized():(e.emit('error',{type:'refreshToken',channel:e.channel,error:{code:v.subscriptionRefreshToken,message:void 0!==t?t.toString():''}}),e._refreshTimeout=setTimeout((()=>e._refresh()),e._getRefreshRetryDelay()))}))}_refreshResponse(e){this._isSubscribed()&&(this._centrifuge._debug('subscription token refreshed, channel',this.channel),this._clearRefreshTimeout(),true===e.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),P(e.ttl))))}_refreshError(e){this._isSubscribed()&&(e.code<100||true===e.temporary?(this.emit('error',{type:'refresh',channel:this.channel,error:e}),this._refreshTimeout=setTimeout((()=>this._refresh()),this._getRefreshRetryDelay())):this._setUnsubscribed(e.code,e.message,true))}_getRefreshRetryDelay(){return E(0,1e4,2e4)}_failUnauthorized(){this._setUnsubscribed(S.unauthorized,'unauthorized',true)}}class SockjsTransport{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return'sockjs'}subName(){return'sockjs-'+this._transport.transport}emulation(){return false}supported(){return null!==this.options.sockjs}initialize(e,t){this._transport=new this.options.sockjs(this.endpoint,null,this.options.sockjsOptions),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class WebsocketTransport{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null}name(){return'websocket'}subName(){return'websocket'}emulation(){return false}supported(){return null!=this.options.websocket}initialize(e,t){var s='';'protobuf'===e&&(s='centrifuge-protobuf'),this._transport=''!==s?new this.options.websocket(this.endpoint,s):new this.options.websocket(this.endpoint),'protobuf'===e&&(this._transport.binaryType='arraybuffer'),this._transport.onopen=()=>{t.onOpen()},this._transport.onerror=e=>{t.onError(e)},this._transport.onclose=e=>{t.onClose(e)},this._transport.onmessage=e=>{t.onMessage(e.data)}}close(){this._transport.close()}send(e){this._transport.send(e)}}class HttpStreamTransport{constructor(e,t){this.endpoint=e,this.options=t,this._abortController=null,this._utf8decoder=new TextDecoder,this._protocol='json'}name(){return'http_stream'}subName(){return'http_stream'}emulation(){return true}_handleErrors(e){if(!e.ok)throw new Error(e.status);return e}_fetchEventTarget(e,t,s){var n=new EventTarget;return(0,e.options.fetch)(t,s).then(e._handleErrors).then((t=>{n.dispatchEvent(new Event('open'));var s='';var r=0;var i=new Uint8Array;var o=t.body.getReader();return new e.options.readableStream({start:t=>function a(){return o.read().then((o=>{var{done:c,value:h}=o;if(c)return n.dispatchEvent(new Event('close')),void t.close();try{if('json'===e._protocol)for(s+=e._utf8decoder.decode(h);r<s.length;)if('\n'===s[r]){var u=s.substring(0,r);n.dispatchEvent(new MessageEvent('message',{data:u})),s=s.substring(r+1),r=0}else++r;else{var l=new Uint8Array(i.length+h.length);for(l.set(i),l.set(h,i.length),i=l;;){var _=e.options.decoder.decodeReply(i);if(!_.ok)break;var d=i.slice(0,_.pos);n.dispatchEvent(new MessageEvent('message',{data:d})),i=i.slice(_.pos)}}}catch(e){return n.dispatchEvent(new Event('error',{detail:e})),n.dispatchEvent(new Event('close')),void t.close()}a()})).catch((function(e){n.dispatchEvent(new Event('error',{detail:e})),n.dispatchEvent(new Event('close')),t.close()}))}()})})).catch((e=>{n.dispatchEvent(new Event('error',{detail:e})),n.dispatchEvent(new Event('close'))})),n}supported(){return null!==this.options.fetch&&null!==this.options.readableStream&&'undefined'!=typeof TextDecoder&&'undefined'!=typeof AbortController&&'undefined'!=typeof EventTarget&&'undefined'!=typeof Event&&'undefined'!=typeof MessageEvent&&'undefined'!=typeof Error}initialize(e,t,s){var n;var r;this._protocol=e,this._abortController=new AbortController,'json'===e?(n={Accept:'application/json','Content-Type':'application/json'},r=s):(n={Accept:'application/octet-stream','Content-Type':'application/octet-stream'},r=s);var i=this._fetchEventTarget(this,this.endpoint,{method:'POST',headers:n,body:r,mode:'cors',credentials:'same-origin',cache:'no-cache',signal:this._abortController.signal});i.addEventListener('open',(()=>{t.onOpen()})),i.addEventListener('error',(e=>{this._abortController.abort(),t.onError(e)})),i.addEventListener('close',(()=>{this._abortController.abort(),t.onClose({code:4,reason:'connection closed'})})),i.addEventListener('message',(e=>{t.onMessage(e.data)}))}close(){this._abortController.abort()}send(e,t,s){var n;var r;var i={session:t,node:s,data:e};'json'===this._protocol?(n={'Content-Type':'application/json'},r=JSON.stringify(i)):(n={'Content-Type':'application/octet-stream'},r=this.options.encoder.encodeEmulationRequest(i)),(0,this.options.fetch)(this.options.emulationEndpoint,{method:'POST',headers:n,body:r,mode:'cors',credentials:'same-origin',cache:'no-cache'})}}class SseTransport{constructor(e,t){this.endpoint=e,this.options=t,this._protocol='json',this._transport=null,this._onClose=null}name(){return'sse'}subName(){return'sse'}emulation(){return true}supported(){return null!==this.options.eventsource&&null!==this.options.fetch}initialize(e,t,s){var n;(n=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint)).searchParams.append('cf_connect',s);var r=new this.options.eventsource(n.toString(),{});this._transport=r,r.onopen=function(){t.onOpen()},r.onerror=function(e){r.close(),t.onError(e),t.onClose({code:4,reason:'connection closed'})},r.onmessage=function(e){t.onMessage(e.data)},this._onClose=function(){t.onClose({code:4,reason:'connection closed'})}}close(){this._transport.close(),null!==this._onClose&&this._onClose()}send(e,t,s){var n=JSON.stringify({session:t,node:s,data:e});(0,this.options.fetch)(this.options.emulationEndpoint,{method:'POST',headers:{'Content-Type':'application/json'},body:n,mode:'cors',credentials:'same-origin',cache:'no-cache'})}}function x(e,t,s,n){return new(s||(s=Promise))((function(r,i){function o(e){try{c(n.next(e))}catch(e){i(e)}}function a(e){try{c(n.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class WebtransportTransport{constructor(e,t){this.endpoint=e,this.options=t,this._transport=null,this._stream=null,this._writer=null,this._utf8decoder=new TextDecoder,this._protocol='json'}name(){return'webtransport'}subName(){return'webtransport'}emulation(){return false}supported(){return null!=this.options.webtransport}initialize(e,t){return x(this,void 0,void 0,(function*(){var s;s=globalThis&&globalThis.document&&globalThis.document.baseURI?new URL(this.endpoint,globalThis.document.baseURI):new URL(this.endpoint),'protobuf'===e&&s.searchParams.append('cf_protocol','protobuf'),this._protocol=e;var n=new EventTarget;this._transport=new this.options.webtransport(s.toString()),this._transport.closed.then((()=>{t.onClose({code:4,reason:'connection closed'})})).catch((()=>{t.onClose({code:4,reason:'connection closed'})}));try{yield this._transport.ready}catch(e){return void this.close()}var r;try{r=yield this._transport.createBidirectionalStream()}catch(e){return void this.close()}this._stream=r,this._writer=this._stream.writable.getWriter(),n.addEventListener('close',(()=>{t.onClose({code:4,reason:'connection closed'})})),n.addEventListener('message',(e=>{t.onMessage(e.data)})),this._startReading(n),t.onOpen()}))}_startReading(e){return x(this,void 0,void 0,(function*(){var t=this._stream.readable.getReader();var s='';var n=0;var r=new Uint8Array;try{for(;;){var{done:i,value:o}=yield t.read();if(o.length>0)if('json'===this._protocol)for(s+=this._utf8decoder.decode(o);n<s.length;)if('\n'===s[n]){var a=s.substring(0,n);e.dispatchEvent(new MessageEvent('message',{data:a})),s=s.substring(n+1),n=0}else++n;else{var c=new Uint8Array(r.length+o.length);for(c.set(r),c.set(o,r.length),r=c;;){var h=this.options.decoder.decodeReply(r);if(!h.ok)break;var u=r.slice(0,h.pos);e.dispatchEvent(new MessageEvent('message',{data:u})),r=r.slice(h.pos)}}if(i)break}}catch(t){e.dispatchEvent(new Event('close'))}}))}close(){return x(this,void 0,void 0,(function*(){try{this._writer&&(yield this._writer.close()),this._transport.close()}catch(e){}}))}send(e){return x(this,void 0,void 0,(function*(){var t;t='json'===this._protocol?(new TextEncoder).encode(e+'\n'):e;try{yield this._writer.write(t)}catch(e){this.close()}}))}}class JsonCodec{name(){return'json'}encodeCommands(e){return e.map((e=>JSON.stringify(e))).join('\n')}decodeReplies(e){return e.trim().split('\n').map((e=>JSON.parse(e)))}}var R={token:'',getToken:null,data:null,getData:null,debug:false,name:'js',version:'',fetch:null,readableStream:null,websocket:null,eventsource:null,sockjs:null,sockjsOptions:{},emulationEndpoint:'/emulation',minReconnectDelay:500,maxReconnectDelay:2e4,timeout:5e3,maxServerPingDelay:1e4,networkEventTarget:null};class UnauthorizedError extends Error{constructor(e){super(e),this.name=this.constructor.name}}class Centrifuge extends m{constructor(e,t){super(),this._reconnectTimeout=null,this._refreshTimeout=null,this._serverPingTimeout=null,this.state=w.Disconnected,this._transportIsOpen=false,this._endpoint=e,this._emulation=false,this._transports=[],this._currentTransportIndex=0,this._triedAllTransports=false,this._transportWasOpen=false,this._transport=null,this._transportId=0,this._deviceWentOffline=false,this._transportClosed=true,this._codec=new JsonCodec,this._reconnecting=false,this._reconnectTimeout=null,this._reconnectAttempts=0,this._client=null,this._session='',this._node='',this._subs={},this._serverSubs={},this._commandId=0,this._commands=[],this._batching=false,this._refreshRequired=false,this._refreshTimeout=null,this._callbacks={},this._token='',this._data=null,this._dispatchPromise=Promise.resolve(),this._serverPing=0,this._serverPingTimeout=null,this._sendPong=false,this._promises={},this._promiseId=0,this._debugEnabled=false,this._networkEventsSet=false,this._config=Object.assign(Object.assign({},R),t),this._configure(),this._debugEnabled?(this.on('state',(e=>{this._debug('client state',e.oldState,'->',e.newState)})),this.on('error',(e=>{this._debug('client error',e)}))):this.on('error',(function(){Function.prototype()}))}newSubscription(e,t){if(null!==this.getSubscription(e))throw new Error('Subscription to the channel '+e+' already exists');var s=new Subscription(this,e,t);return this._subs[e]=s,s}getSubscription(e){return this._getSub(e)}removeSubscription(e){e&&(e.state!==C.Unsubscribed&&e.unsubscribe(),this._removeSubscription(e))}subscriptions(){return this._subs}ready(e){return this.state===w.Disconnected?Promise.reject({code:v.clientDisconnected,message:'client disconnected'}):this.state===w.Connected?Promise.resolve():new Promise(((t,s)=>{var n={resolve:t,reject:s};e&&(n.timeout=setTimeout((function(){s({code:v.timeout,message:'timeout'})}),e)),this._promises[this._nextPromiseId()]=n}))}connect(){this._isConnected()?this._debug('connect called when already connected'):this._isConnecting()?this._debug('connect called when already connecting'):(this._debug('connect called'),this._reconnectAttempts=0,this._startConnecting())}disconnect(){this._disconnect(y.disconnectCalled,'disconnect called',false)}setToken(e){this._token=e}send(e){var t={send:{data:e}};var s=this;return this._methodCall().then((function(){return s._transportSendCommands([t])?Promise.resolve():Promise.reject(s._createErrorObject(v.transportWriteError,'transport write error'))}))}rpc(e,t){var s={rpc:{method:e,data:t}};var n=this;return this._methodCall().then((function(){return n._callPromise(s,(function(e){return{data:e.rpc.data}}))}))}publish(e,t){var s={publish:{channel:e,data:t}};var n=this;return this._methodCall().then((function(){return n._callPromise(s,(function(){return{}}))}))}history(e,t){var s={history:this._getHistoryRequest(e,t)};var n=this;return this._methodCall().then((function(){return n._callPromise(s,(function(t){var s=t.history;var r=[];if(s.publications)for(var i=0;i<s.publications.length;i++)r.push(n._getPublicationContext(e,s.publications[i]));return{publications:r,epoch:s.epoch||'',offset:s.offset||0}}))}))}presence(e){var t={presence:{channel:e}};var s=this;return this._methodCall().then((function(){return s._callPromise(t,(function(e){var t=e.presence.presence;for(var s in t)if(t.hasOwnProperty(s)){var n=t[s].conn_info;var r=t[s].chan_info;n&&(t[s].connInfo=n),r&&(t[s].chanInfo=r)}return{clients:t}}))}))}presenceStats(e){var t={presence_stats:{channel:e}};var s=this;return this._methodCall().then((function(){return s._callPromise(t,(function(e){var t=e.presence_stats;return{numUsers:t.num_users,numClients:t.num_clients}}))}))}startBatching(){this._batching=true}stopBatching(){var e=this;Promise.resolve().then((function(){Promise.resolve().then((function(){e._batching=false,e._flush()}))}))}_debug(){if(this._debugEnabled){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];(function(e,t){if(globalThis.console){var s=globalThis.console.debug;k(s)&&s.apply(globalThis.console,t)}})(0,t)}}_formatOverride(){}_configure(){if(!('Promise'in globalThis))throw new Error('Promise polyfill required');if(!this._endpoint)throw new Error('endpoint configuration required');if(null!==this._config.token&&(this._token=this._config.token),null!==this._config.data&&(this._data=this._config.data),this._codec=new JsonCodec,this._formatOverride(),(true===this._config.debug||'undefined'!=typeof localStorage&&localStorage.getItem('centrifuge.debug'))&&(this._debugEnabled=true),this._debug('config',this._config),'string'==typeof this._endpoint);else{if(!('object'==typeof this._endpoint&&this._endpoint instanceof Array))throw new Error('unsupported url configuration type: only string or array of objects are supported');for(var e in this._transports=this._endpoint,this._emulation=true,this._transports)if(this._transports.hasOwnProperty(e)){var t=this._transports[e];if(!t.endpoint||!t.transport)throw new Error('malformed transport configuration');var s=t.transport;if(['websocket','http_stream','sse','sockjs','webtransport'].indexOf(s)<0)throw new Error('unsupported transport name: '+s)}}}_setState(e){if(this.state!==e){this._reconnecting=false;var t=this.state;return this.state=e,this.emit('state',{newState:e,oldState:t}),true}return false}_isDisconnected(){return this.state===w.Disconnected}_isConnecting(){return this.state===w.Connecting}_isConnected(){return this.state===w.Connected}_nextCommandId(){return++this._commandId}_setNetworkEvents(){if(!this._networkEventsSet){var e=null;null!==this._config.networkEventTarget?e=this._config.networkEventTarget:void 0!==globalThis.addEventListener&&(e=globalThis),e&&(e.addEventListener('offline',(()=>{this._debug('offline event triggered'),this.state!==w.Connected&&this.state!==w.Connecting||(this._disconnect(g.transportClosed,'transport closed',true),this._deviceWentOffline=true)})),e.addEventListener('online',(()=>{this._debug('online event triggered'),this.state===w.Connecting&&(this._deviceWentOffline&&!this._transportClosed&&(this._deviceWentOffline=false,this._transportClosed=true),this._clearReconnectTimeout(),this._startReconnecting())})),this._networkEventsSet=true)}}_getReconnectDelay(){var e=E(this._reconnectAttempts,this._config.minReconnectDelay,this._config.maxReconnectDelay);return this._reconnectAttempts+=1,e}_clearOutgoingRequests(){for(var e in this._callbacks)if(this._callbacks.hasOwnProperty(e)){var t=this._callbacks[e];clearTimeout(t.timeout);var s=t.errback;if(!s)continue;s({error:this._createErrorObject(v.connectionClosed,'connection closed')})}this._callbacks={}}_clearConnectedState(){for(var e in this._client=null,this._clearServerPingTimeout(),this._clearRefreshTimeout(),this._subs)if(this._subs.hasOwnProperty(e)){var t=this._subs[e];t.state===C.Subscribed&&t._setSubscribing(T.transportClosed,'transport closed')}for(var s in this._serverSubs)this._serverSubs.hasOwnProperty(s)&&this.emit('subscribing',{channel:s})}_handleWriteError(e){for(var t of e){var s=t.id;if(s in this._callbacks){var n=this._callbacks[s];clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],(0,n.errback)({error:this._createErrorObject(v.transportWriteError,'transport write error')})}}}_transportSendCommands(e){if(!e.length)return true;if(!this._transport)return false;try{this._transport.send(this._codec.encodeCommands(e),this._session,this._node)}catch(t){return this._debug('error writing commands',t),this._handleWriteError(e),false}return true}_initializeTransport(){var e;null!==this._config.websocket?e=this._config.websocket:'function'!=typeof globalThis.WebSocket&&'object'!=typeof globalThis.WebSocket||(e=globalThis.WebSocket);var t=null;null!==this._config.sockjs?t=this._config.sockjs:void 0!==globalThis.SockJS&&(t=globalThis.SockJS);var s=null;null!==this._config.eventsource?s=this._config.eventsource:void 0!==globalThis.EventSource&&(s=globalThis.EventSource);var n=null;null!==this._config.fetch?n=this._config.fetch:void 0!==globalThis.fetch&&(n=globalThis.fetch);var r=null;if(null!==this._config.readableStream?r=this._config.readableStream:void 0!==globalThis.ReadableStream&&(r=globalThis.ReadableStream),this._emulation){this._currentTransportIndex>=this._transports.length&&(this._triedAllTransports=true,this._currentTransportIndex=0);var i=0;for(;;){if(i>=this._transports.length)throw new Error('no supported transport found');var o=this._transports[this._currentTransportIndex];var a=o.transport;var c=o.endpoint;if('websocket'===a){if(this._debug('trying websocket transport'),this._transport=new WebsocketTransport(c,{websocket:e}),!this._transport.supported()){this._debug('websocket transport not available'),this._currentTransportIndex++,i++;continue}}else if('webtransport'===a){if(this._debug('trying webtransport transport'),this._transport=new WebtransportTransport(c,{webtransport:globalThis.WebTransport,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug('webtransport transport not available'),this._currentTransportIndex++,i++;continue}}else if('http_stream'===a){if(this._debug('trying http_stream transport'),this._transport=new HttpStreamTransport(c,{fetch:n,readableStream:r,emulationEndpoint:this._config.emulationEndpoint,decoder:this._codec,encoder:this._codec}),!this._transport.supported()){this._debug('http_stream transport not available'),this._currentTransportIndex++,i++;continue}}else if('sse'===a){if(this._debug('trying sse transport'),this._transport=new SseTransport(c,{eventsource:s,fetch:n,emulationEndpoint:this._config.emulationEndpoint}),!this._transport.supported()){this._debug('sse transport not available'),this._currentTransportIndex++,i++;continue}}else{if('sockjs'!==a)throw new Error('unknown transport '+a);if(this._debug('trying sockjs'),this._transport=new SockjsTransport(c,{sockjs:t,sockjsOptions:this._config.sockjsOptions}),!this._transport.supported()){this._debug('sockjs transport not available'),this._currentTransportIndex++,i++;continue}}break}}else{if(0===this._endpoint.lastIndexOf('http',0))throw new Error('Provide explicit transport endpoints configuration in case of using HTTP (i.e. using array of TransportEndpoint instead of a single string), or use ws(s):// scheme in an endpoint if you aimed using WebSocket transport');if(this._debug('client will use websocket'),this._transport=new WebsocketTransport(this._endpoint,{websocket:e}),!this._transport.supported())throw new Error('WebSocket not available')}var h=this;var u=this._transport;var l=this._nextTransportId();h._debug("id of transport",l);var _=false;var d=[];if(this._transport.emulation()){var f=h._sendConnect(true);d.push(f)}this._setNetworkEvents();var p=this._codec.encodeCommands(d);var b;this._transportClosed=false,b=setTimeout((function(){u.close()}),this._config.timeout),this._transport.initialize(this._codec.name(),{onOpen:function(){if(b&&(clearTimeout(b),b=null),h._transportId!=l)return h._debug('open callback from non-actual transport'),void u.close();_=true,h._debug(u.subName(),'transport open'),u.emulation()||(h._transportIsOpen=true,h._transportWasOpen=true,h.startBatching(),h._sendConnect(false),h._sendSubscribeCommands(),h.stopBatching(),h.emit('__centrifuge_debug:connect_frame_sent',{}))},onError:function(e){h._transportId==l?h._debug('transport level error',e):h._debug('error callback from non-actual transport')},onClose:function(e){if(b&&(clearTimeout(b),b=null),h._transportId==l){h._debug(u.subName(),'transport closed'),h._transportClosed=true,h._transportIsOpen=false;var t='connection closed';var s=true;var n=0;if(e&&'code'in e&&e.code&&(n=e.code),e&&e.reason)try{var r=JSON.parse(e.reason);t=r.reason,s=r.reconnect}catch(r){t=e.reason,(n>=3500&&n<4e3||n>=4500&&n<5e3)&&(s=false)}n<3e3?(1009===n?(n=y.messageSizeLimit,t='message size limit exceeded',s=false):(n=g.transportClosed,t='transport closed'),h._emulation&&!h._transportWasOpen&&(h._currentTransportIndex++,h._currentTransportIndex>=h._transports.length&&(h._triedAllTransports=true,h._currentTransportIndex=0))):h._transportWasOpen=true,h._isConnecting()&&!_&&h.emit('error',{type:'transport',error:{code:v.transportClosed,message:'transport closed'},transport:u.name()}),h._reconnecting=false,h._disconnect(n,t,s)}else h._debug('close callback from non-actual transport')},onMessage:function(e){h._dataReceived(e)}},p),h.emit('__centrifuge_debug:transport_initialized',{})}_sendConnect(e){var t=this._constructConnectCommand();var s=this;return this._call(t,e).then((e=>{s._connectResponse(e.reply.connect),e.next&&e.next()}),(e=>{s._connectError(e.error),e.next&&e.next()})),t}_startReconnecting(){if(this._debug('start reconnecting'),this._isConnecting())if(this._reconnecting)this._debug('reconnect already in progress, return from reconnect routine');else if(false!==this._transportClosed){this._reconnecting=true;var e=this;this._refreshRequired||''===this._token&&null!==this._config.getToken?this._getToken().then((function(t){e._isConnecting()&&(null!=t&&null!=t?(e._token=t,e._debug('connection token refreshed'),e._config.getData?e._config.getData().then((function(t){e._isConnecting()&&(e._data=t,e._initializeTransport())})):e._initializeTransport()):e._failUnauthorized())})).catch((function(t){if(e._isConnecting())if(t instanceof UnauthorizedError)e._failUnauthorized();else{e.emit('error',{type:'connectToken',error:{code:v.clientConnectToken,message:void 0!==t?t.toString():''}});var s=e._getReconnectDelay();e._debug('error on connection token refresh, reconnect after '+s+' milliseconds',t),e._reconnecting=false,e._reconnectTimeout=setTimeout((()=>{e._startReconnecting()}),s)}})):this._config.getData?this._config.getData().then((function(t){e._isConnecting()&&(e._data=t,e._initializeTransport())})):this._initializeTransport()}else this._debug('waiting for transport close');else this._debug('stop reconnecting: client not in connecting state')}_connectError(e){this.state===w.Connecting&&(109===e.code&&(this._refreshRequired=true),e.code<100||true===e.temporary||109===e.code?(this.emit('error',{type:'connect',error:e}),this._debug('closing transport due to connect error'),this._disconnect(e.code,e.message,true)):this._disconnect(e.code,e.message,false))}_scheduleReconnect(){if(this._isConnecting()){var e=false;!this._emulation||this._transportWasOpen||this._triedAllTransports||(e=true);var t=this._getReconnectDelay();e&&(t=0),this._debug('reconnect after '+t+' milliseconds'),this._clearReconnectTimeout(),this._reconnectTimeout=setTimeout((()=>{this._startReconnecting()}),t)}}_constructConnectCommand(){var e={};this._token&&(e.token=this._token),this._data&&(e.data=this._data),this._config.name&&(e.name=this._config.name),this._config.version&&(e.version=this._config.version);var t={};var s=false;for(var n in this._serverSubs)if(this._serverSubs.hasOwnProperty(n)&&this._serverSubs[n].recoverable){s=true;var r={recover:true};this._serverSubs[n].offset&&(r.offset=this._serverSubs[n].offset),this._serverSubs[n].epoch&&(r.epoch=this._serverSubs[n].epoch),t[n]=r}return s&&(e.subs=t),{connect:e}}_getHistoryRequest(e,t){var s={channel:e};return void 0!==t&&(t.since&&(s.since={offset:t.since.offset},t.since.epoch&&(s.since.epoch=t.since.epoch)),void 0!==t.limit&&(s.limit=t.limit),true===t.reverse&&(s.reverse=true)),s}_methodCall(){return this._isConnected()?Promise.resolve():new Promise(((e,t)=>{var s=setTimeout((function(){t({code:v.timeout,message:'timeout'})}),this._config.timeout);this._promises[this._nextPromiseId()]={timeout:s,resolve:e,reject:t}}))}_callPromise(e,t){return new Promise(((s,n)=>{this._call(e,false).then((e=>{s(t(e.reply)),e.next&&e.next()}),(e=>{n(e.error),e.next&&e.next()}))}))}_dataReceived(e){this._serverPing>0&&this._waitServerPing();var t=this._codec.decodeReplies(e);this._dispatchPromise=this._dispatchPromise.then((()=>{var e;this._dispatchPromise=new Promise((t=>{e=t})),this._dispatchSynchronized(t,e)}))}_dispatchSynchronized(e,t){var s=this;var n=Promise.resolve();var r=function(t){e.hasOwnProperty(t)&&(n=n.then((()=>s._dispatchReply(e[t]))))};for(var i in e)r(i);n=n.then((()=>{t()}))}_dispatchReply(e){var t;var s=new Promise((e=>{t=e}));if(null==e)return this._debug('dispatch: got undefined or null reply'),t(),s;var n=e.id;return n&&n>0?this._handleReply(e,t):e.push?this._handlePush(e.push,t):this._handleServerPing(t),s}_call(e,t){return new Promise(((s,n)=>{e.id=this._nextCommandId(),this._registerCall(e.id,s,n),t||this._addCommand(e)}))}_startConnecting(){this._debug('start connecting'),this._setState(w.Connecting)&&this.emit('connecting',{code:g.connectCalled,reason:'connect called'}),this._client=null,this._startReconnecting()}_disconnect(e,t,s){if(!this._isDisconnected()){this._transportIsOpen=false;var n=this.state;this._reconnecting=false;var r={code:e,reason:t};var i=false;if(s?i=this._setState(w.Connecting):(i=this._setState(w.Disconnected),this._rejectPromises({code:v.clientDisconnected,message:'disconnected'})),this._clearOutgoingRequests(),n===w.Connecting&&this._clearReconnectTimeout(),n===w.Connected&&this._clearConnectedState(),i&&(this._isConnecting()?this.emit('connecting',r):this.emit('disconnected',r)),this._transport){this._debug("closing existing transport");var o=this._transport;this._transport=null,o.close(),this._transportClosed=true,this._nextTransportId()}else this._debug("no transport to close");this._scheduleReconnect()}}_failUnauthorized(){this._disconnect(y.unauthorized,'unauthorized',false)}_getToken(){if(this._debug('get connection token'),!this._config.getToken)throw this.emit('error',{type:'configuration',error:{code:v.badConfiguration,message:'token expired but no getToken function set in the configuration'}}),new UnauthorizedError('');return this._config.getToken({})}_refresh(){var e=this._client;var t=this;this._getToken().then((function(s){e===t._client&&(s?(t._token=s,t._debug('connection token refreshed'),t._isConnected()&&t._call({refresh:{token:t._token}},false).then((e=>{t._refreshResponse(e.reply.refresh),e.next&&e.next()}),(e=>{t._refreshError(e.error),e.next&&e.next()}))):t._failUnauthorized())})).catch((function(e){t._isConnected()&&(e instanceof UnauthorizedError?t._failUnauthorized():(t.emit('error',{type:'refreshToken',error:{code:v.clientRefreshToken,message:void 0!==e?e.toString():''}}),t._refreshTimeout=setTimeout((()=>t._refresh()),t._getRefreshRetryDelay())))}))}_refreshError(e){e.code<100||true===e.temporary?(this.emit('error',{type:'refresh',error:e}),this._refreshTimeout=setTimeout((()=>this._refresh()),this._getRefreshRetryDelay())):this._disconnect(e.code,e.message,false)}_getRefreshRetryDelay(){return E(0,5e3,1e4)}_refreshResponse(e){this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null),e.expires&&(this._client=e.client,this._refreshTimeout=setTimeout((()=>this._refresh()),P(e.ttl)))}_removeSubscription(e){null!==e&&delete this._subs[e.channel]}_unsubscribe(e){if(this._transportIsOpen){var t=this;this._call({unsubscribe:{channel:e.channel}},false).then((e=>{e.next&&e.next()}),(e=>{e.next&&e.next(),t._disconnect(g.unsubscribeError,'unsubscribe error',true)}))}}_getSub(e){return this._subs[e]||null}_isServerSub(e){return void 0!==this._serverSubs[e]}_sendSubscribeCommands(){var e=[];for(var t in this._subs)if(this._subs.hasOwnProperty(t)){var s=this._subs[t];if(true!==s._inflight&&s.state===C.Subscribing){var n=s._subscribe();n&&e.push(n)}}return e}_connectResponse(e){if(this._transportIsOpen=true,this._transportWasOpen=true,this._reconnectAttempts=0,this._refreshRequired=false,!this._isConnected()){this._client=e.client,this._setState(w.Connected),this._refreshTimeout&&clearTimeout(this._refreshTimeout),e.expires&&(this._refreshTimeout=setTimeout((()=>this._refresh()),P(e.ttl))),this._session=e.session,this._node=e.node,this.startBatching(),this._sendSubscribeCommands(),this.stopBatching();var t={client:e.client,transport:this._transport.subName()};e.data&&(t.data=e.data),this.emit('connected',t),this._resolvePromises(),this._processServerSubs(e.subs||{}),e.ping&&e.ping>0?(this._serverPing=1e3*e.ping,this._sendPong=true===e.pong,this._waitServerPing()):this._serverPing=0}}_processServerSubs(e){for(var t in e)if(e.hasOwnProperty(t)){var s=e[t];this._serverSubs[t]={offset:s.offset,epoch:s.epoch,recoverable:s.recoverable||false};var n=this._getSubscribeContext(t,s);this.emit('subscribed',n)}for(var r in e)if(e.hasOwnProperty(r)){var i=e[r];if(i.recovered){var o=i.publications;if(o&&o.length>0)for(var a in o)o.hasOwnProperty(a)&&this._handlePublication(r,o[a])}}for(var c in this._serverSubs)this._serverSubs.hasOwnProperty(c)&&(e[c]||(this.emit('unsubscribed',{channel:c}),delete this._serverSubs[c]))}_clearRefreshTimeout(){null!==this._refreshTimeout&&(clearTimeout(this._refreshTimeout),this._refreshTimeout=null)}_clearReconnectTimeout(){null!==this._reconnectTimeout&&(clearTimeout(this._reconnectTimeout),this._reconnectTimeout=null)}_clearServerPingTimeout(){null!==this._serverPingTimeout&&(clearTimeout(this._serverPingTimeout),this._serverPingTimeout=null)}_waitServerPing(){0!==this._config.maxServerPingDelay&&this._isConnected()&&(this._clearServerPingTimeout(),this._serverPingTimeout=setTimeout((()=>{this._isConnected()&&this._disconnect(g.noPing,'no ping',true)}),this._serverPing+this._config.maxServerPingDelay))}_getSubscribeContext(e,t){var s={channel:e,positioned:false,recoverable:false,wasRecovering:false,recovered:false};t.recovered&&(s.recovered=true),t.positioned&&(s.positioned=true),t.recoverable&&(s.recoverable=true),t.was_recovering&&(s.wasRecovering=true);var n='';'epoch'in t&&(n=t.epoch);var r=0;return'offset'in t&&(r=t.offset),(s.positioned||s.recoverable)&&(s.streamPosition={offset:r,epoch:n}),t.data&&(s.data=t.data),s}_handleReply(e,t){var s=e.id;if(s in this._callbacks){var n=this._callbacks[s];if(clearTimeout(this._callbacks[s].timeout),delete this._callbacks[s],'error'in(o=e)&&null!==o.error){var r=n.errback;if(!r)return void t();r({error:e.error,next:t})}else{var i=n.callback;if(!i)return;i({reply:e,next:t})}var o}else t()}_handleJoin(e,t){var s=this._getSub(e);if(s)s._handleJoin(t);else if(this._isServerSub(e)){var n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit('join',n)}}_handleLeave(e,t){var s=this._getSub(e);if(s)s._handleLeave(t);else if(this._isServerSub(e)){var n={channel:e,info:this._getJoinLeaveContext(t.info)};this.emit('leave',n)}}_handleUnsubscribe(e,t){var s=this._getSub(e);s?t.code<2500?s._setUnsubscribed(t.code,t.reason,false):s._setSubscribing(t.code,t.reason):this._isServerSub(e)&&(delete this._serverSubs[e],this.emit('unsubscribed',{channel:e}))}_handleSubscribe(e,t){this._serverSubs[e]={offset:t.offset,epoch:t.epoch,recoverable:t.recoverable||false},this.emit('subscribed',this._getSubscribeContext(e,t))}_handleDisconnect(e){var t=e.code;var s=true;(t>=3500&&t<4e3||t>=4500&&t<5e3)&&(s=false),this._disconnect(t,e.reason,s)}_getPublicationContext(e,t){var s={channel:e,data:t.data};return t.offset&&(s.offset=t.offset),t.info&&(s.info=this._getJoinLeaveContext(t.info)),t.tags&&(s.tags=t.tags),s}_getJoinLeaveContext(e){var t={client:e.client,user:e.user};return e.conn_info&&(t.connInfo=e.conn_info),e.chan_info&&(t.chanInfo=e.chan_info),t}_handlePublication(e,t){var s=this._getSub(e);if(s)s._handlePublication(t);else if(this._isServerSub(e)){var n=this._getPublicationContext(e,t);this.emit('publication',n),void 0!==t.offset&&(this._serverSubs[e].offset=t.offset)}}_handleMessage(e){this.emit('message',{data:e.data})}_handleServerPing(e){this._sendPong&&this._transportSendCommands([{}]),e()}_handlePush(e,t){var s=e.channel;e.pub?this._handlePublication(s,e.pub):e.message?this._handleMessage(e.message):e.join?this._handleJoin(s,e.join):e.leave?this._handleLeave(s,e.leave):e.unsubscribe?this._handleUnsubscribe(s,e.unsubscribe):e.subscribe?this._handleSubscribe(s,e.subscribe):e.disconnect&&this._handleDisconnect(e.disconnect),t()}_flush(){var e=this._commands.slice(0);this._commands=[],this._transportSendCommands(e)}_createErrorObject(e,t,s){var n={code:e,message:t};return s&&(n.temporary=true),n}_registerCall(e,t,s){this._callbacks[e]={callback:t,errback:s,timeout:null},this._callbacks[e].timeout=setTimeout((()=>{delete this._callbacks[e],k(s)&&s({error:this._createErrorObject(v.timeout,'timeout')})}),this._config.timeout)}_addCommand(e){this._batching?this._commands.push(e):this._transportSendCommands([e])}_nextPromiseId(){return++this._promiseId}_nextTransportId(){return++this._transportId}_resolvePromises(){for(var e in this._promises)this._promises.hasOwnProperty(e)&&(this._promises[e].timeout&&clearTimeout(this._promises[e].timeout),this._promises[e].resolve(),delete this._promises[e])}_rejectPromises(e){for(var t in this._promises)this._promises.hasOwnProperty(t)&&(this._promises[t].timeout&&clearTimeout(this._promises[t].timeout),this._promises[t].reject(e),delete this._promises[t])}}Centrifuge.SubscriptionState=C,Centrifuge.State=w,Centrifuge.UnauthorizedError=UnauthorizedError;export{Centrifuge,w as State,Subscription,C as SubscriptionState,UnauthorizedError,g as connectingCodes,y as disconnectedCodes,v as errorCodes,T as subscribingCodes,S as unsubscribedCodes};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var t=function(){function t(t){this.ttl=t,this.map=new Map,this._to=false}return t.prototype.has=function(t){return this.map.has(t)},t.prototype.add=function(t){var r=this;this.map.set(t,o()),this._to||(this._to=true,setTimeout((function(){r._to=false,e(r)}),0))},t.prototype.clear=function(){this.map.clear()},t}();function e(t){var e=o()-t.ttl;var r=t.map[Symbol.iterator]();for(;;){var i=r.next().value;if(!i)return;if(!(i[1]<e))return;t.map.delete(i[0])}}function o(){return(new Date).getTime()}exports.ObliviousSet=t,exports.now=o,exports.removeTooOldValues=e;
@@ -0,0 +1 @@
1
+ var t=function(){function t(t){this.ttl=t,this.map=new Map,this._to=false}return t.prototype.has=function(t){return this.map.has(t)},t.prototype.add=function(t){var n=this;this.map.set(t,r()),this._to||(this._to=true,setTimeout((function(){n._to=false,e(n)}),0))},t.prototype.clear=function(){this.map.clear()},t}();function e(t){var e=r()-t.ttl;var n=t.map[Symbol.iterator]();for(;;){var o=n.next().value;if(!o)return;if(!(o[1]<e))return;t.map.delete(o[0])}}function r(){return(new Date).getTime()}export{t as ObliviousSet,r as now,e as removeTooOldValues};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true}),exports.addBrowser=function(e){if('function'==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope){var n=self.close.bind(self);self.close=function(){return e(),n()}}else{if('function'!=typeof window.addEventListener)return;window.addEventListener('beforeunload',(function(){e()}),true),window.addEventListener('unload',(function(){e()}),true)}};
@@ -0,0 +1 @@
1
+ function e(e){if('function'==typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope){var n=self.close.bind(self);self.close=function(){return e(),n()}}else{if('function'!=typeof window.addEventListener)return;window.addEventListener('beforeunload',(function(){e()}),true),window.addEventListener('unload',(function(){e()}),true)}}export{e as addBrowser};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./browser.js');var r=require('./node.js');var t='[object process]'==={}.toString.call('undefined'!=typeof process?process:0)?r.addNode:e.addBrowser;var n=new Set;var o=false;function u(){var e=[];return n.forEach((function(r){e.push(r()),n.delete(r)})),Promise.all(e)}exports.add=function(e){if(o||(o=true,t(u)),'function'!=typeof e)throw new Error('Listener is no function');return n.add(e),{remove:function(){return n.delete(e)},run:function(){return n.delete(e),e()}}},exports.runAll=u;
@@ -0,0 +1 @@
1
+ import{addBrowser as e}from'./browser.mjs';import{addNode as r}from'./node.mjs';var n='[object process]'==={}.toString.call('undefined'!=typeof process?process:0)?r:e;var o=new Set;var t=false;function f(e){if(t||(t=true,n(i)),'function'!=typeof e)throw new Error('Listener is no function');return o.add(e),{remove:function(){return o.delete(e)},run:function(){return o.delete(e),e()}}}function i(){var e=[];return o.forEach((function(r){e.push(r()),o.delete(r)})),Promise.all(e)}export{f as add,i as runAll};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true}),exports.addNode=function(e){process.on('exit',(function(){return e()})),process.on('beforeExit',(function(){return e().then((function(){return process.exit()}))})),process.on('SIGINT',(function(){return e().then((function(){return process.exit()}))})),process.on('uncaughtException',(function(n){return e().then((function(){console.trace(n),process.exit(101)}))}))};
@@ -0,0 +1 @@
1
+ function n(n){process.on('exit',(function(){return n()})),process.on('beforeExit',(function(){return n().then((function(){return process.exit()}))})),process.on('SIGINT',(function(){return n().then((function(){return process.exit()}))})),process.on('uncaughtException',(function(e){return n().then((function(){console.trace(e),process.exit(101)}))}))}export{n as addNode};
package/index.d.ts CHANGED
@@ -129,12 +129,10 @@ export interface ResponseError {
129
129
  errorText: string;
130
130
  headers: ApiResponse["headers"];
131
131
  data: ApiResponse["data"];
132
- }
133
- export type ApiErrorExtended = ApiError & {
134
- config: ApiRequestConfig & {
135
- _retry?: boolean;
132
+ originalRequest: ApiRequestConfig & {
133
+ _touched?: boolean;
136
134
  };
137
- };
135
+ }
138
136
  export type ApiRequestConfigExtended = ApiRequestConfig & {
139
137
  camelize?: boolean;
140
138
  withCaptcha?: boolean;
@@ -216,6 +214,64 @@ export declare class CaptchaService implements Captcha {
216
214
  */
217
215
  execute(meta?: ExecuteMeta): Promise<CaptchaAnswer | void>;
218
216
  }
217
+ type TransportName = "websocket" | "http_stream" | "sse" | "sockjs" | "webtransport";
218
+ interface TransportEndpoint {
219
+ /** transport to use */
220
+ transport: TransportName;
221
+ /** endpoint for a selected transport type */
222
+ endpoint: string;
223
+ }
224
+ type SocketServiceConfig = {
225
+ refreshToken: () => Promise<string>;
226
+ token: string;
227
+ logger?: {
228
+ log: (msg: string, ...data: unknown[]) => void;
229
+ debug: (msg: string, ...data: unknown[]) => void;
230
+ error: (msg: string, ...data: unknown[]) => void;
231
+ };
232
+ debug?: boolean;
233
+ transport: Array<TransportEndpoint>;
234
+ };
235
+ /**
236
+ * Service for interacting with WebSocket.
237
+ */
238
+ export declare class SocketService {
239
+ private config;
240
+ private channel;
241
+ private elector;
242
+ private client;
243
+ private connected;
244
+ private logger;
245
+ constructor(config: SocketServiceConfig);
246
+ /**
247
+ * Обновить токен
248
+ * @param {string} token
249
+ */
250
+ setToken(token: string): void;
251
+ /**
252
+ * Создание инстанса центрифуги и соединение с сервером
253
+ */
254
+ private createClient;
255
+ /**
256
+ * Дестрой всех подписок
257
+ */
258
+ private disconnect;
259
+ /**
260
+ * Проверка на существование подписок на канал
261
+ * @param {string} channelName
262
+ * @returns {boolean}
263
+ */
264
+ private subscriptionExists;
265
+ private join;
266
+ /**
267
+ * Подписаться на канал
268
+ */
269
+ subscribe<Message>(channelName: string, handler: (message: Message) => unknown): Promise<void>;
270
+ /**
271
+ * Отписаться от канала
272
+ */
273
+ unsubscribe(channelName: string): void;
274
+ }
219
275
 
220
276
  export {
221
277
  apiServiceInstance as ApiService,
package/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./api/index.js');var r=require('./captcha/index.js');var s=require('./api/plugins/request/index.js');var i=require('./api/plugins/response-success/index.js');var p=require('./captcha/error.js');exports.ApiService=e.ApiService,exports.CaptchaService=r.CaptchaService,exports.RequestPlugin=s.RequestPlugin,exports.ResponseSuccessPlugin=i.ResponseSuccessPlugin,exports.CaptchaError=p.CaptchaError;
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./api/index.js');var r=require('./captcha/index.js');var s=require('./socket/index.js');var i=require('./api/plugins/request/index.js');var c=require('./api/plugins/response-success/index.js');var p=require('./captcha/error.js');exports.ApiService=e.ApiService,exports.CaptchaService=r.CaptchaService,exports.SocketService=s.SocketService,exports.RequestPlugin=i.RequestPlugin,exports.ResponseSuccessPlugin=c.ResponseSuccessPlugin,exports.CaptchaError=p.CaptchaError;
package/index.js.flow CHANGED
@@ -174,18 +174,13 @@ export interface ResponseError {
174
174
  errorText: string;
175
175
  headers: $PropertyType<ApiResponse<>, "headers">;
176
176
  data: $PropertyType<ApiResponse<>, "data">;
177
- }
178
- export type ApiErrorExtended = {|
179
- ...ApiError<>,
180
- ...{|
181
- config: {|
182
- ...ApiRequestConfig,
183
- ...{|
184
- _retry?: boolean,
185
- |},
177
+ originalRequest: {|
178
+ ...ApiRequestConfig,
179
+ ...{|
180
+ _touched?: boolean,
186
181
  |},
187
- |},
188
- |};
182
+ |};
183
+ }
189
184
  export type ApiRequestConfigExtended = {|
190
185
  ...ApiRequestConfig,
191
186
  ...{|
@@ -286,4 +281,57 @@ declare export class CaptchaService implements Captcha {
286
281
  */
287
282
  execute(meta?: ExecuteMeta): Promise<CaptchaAnswer | void>;
288
283
  }
284
+ declare type TransportName =
285
+ | "websocket"
286
+ | "http_stream"
287
+ | "sse"
288
+ | "sockjs"
289
+ | "webtransport";
290
+ declare interface TransportEndpoint {
291
+ /**
292
+ * transport to use
293
+ */
294
+ transport: TransportName;
295
+
296
+ /**
297
+ * endpoint for a selected transport type
298
+ */
299
+ endpoint: string;
300
+ }
301
+ declare type SocketServiceConfig = {|
302
+ refreshToken: () => Promise<string>,
303
+ token: string,
304
+ logger?: {|
305
+ log: (msg: string, ...data: mixed[]) => void,
306
+ debug: (msg: string, ...data: mixed[]) => void,
307
+ error: (msg: string, ...data: mixed[]) => void,
308
+ |},
309
+ debug?: boolean,
310
+ transport: Array<TransportEndpoint>,
311
+ |};
312
+ /**
313
+ * Service for interacting with WebSocket.
314
+ */
315
+ declare export class SocketService {
316
+ constructor(config: SocketServiceConfig): this;
317
+
318
+ /**
319
+ * Обновить токен
320
+ * @param {string} token
321
+ */
322
+ setToken(token: string): void;
323
+
324
+ /**
325
+ * Подписаться на канал
326
+ */
327
+ subscribe<Message>(
328
+ channelName: string,
329
+ handler: (message: Message) => mixed
330
+ ): Promise<void>;
331
+
332
+ /**
333
+ * Отписаться от канала
334
+ */
335
+ unsubscribe(channelName: string): void;
336
+ }
289
337
  declare export { apiServiceInstance as ApiService };
package/index.mjs CHANGED
@@ -1 +1 @@
1
- export{ApiService}from'./api/index.mjs';export{CaptchaService}from'./captcha/index.mjs';export{RequestPlugin}from'./api/plugins/request/index.mjs';export{ResponseSuccessPlugin}from'./api/plugins/response-success/index.mjs';export{CaptchaError}from'./captcha/error.mjs';
1
+ export{ApiService}from'./api/index.mjs';export{CaptchaService}from'./captcha/index.mjs';export{SocketService}from'./socket/index.mjs';export{RequestPlugin}from'./api/plugins/request/index.mjs';export{ResponseSuccessPlugin}from'./api/plugins/response-success/index.mjs';export{CaptchaError}from'./captcha/error.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foxford/services",
3
- "version": "1.2.7",
3
+ "version": "1.3.0",
4
4
  "description": "Foxford services",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",
@@ -150,13 +150,47 @@
150
150
  "dependencies/axios/lib/helpers/spread.mjs",
151
151
  "dependencies/axios/lib/utils.js",
152
152
  "dependencies/axios/lib/utils.mjs",
153
+ "dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.js",
154
+ "dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.mjs",
155
+ "dependencies/broadcast-channel/dist/esbrowser/leader-election-util.js",
156
+ "dependencies/broadcast-channel/dist/esbrowser/leader-election-util.mjs",
157
+ "dependencies/broadcast-channel/dist/esbrowser/leader-election-web-lock.js",
158
+ "dependencies/broadcast-channel/dist/esbrowser/leader-election-web-lock.mjs",
159
+ "dependencies/broadcast-channel/dist/esbrowser/leader-election.js",
160
+ "dependencies/broadcast-channel/dist/esbrowser/leader-election.mjs",
161
+ "dependencies/broadcast-channel/dist/esbrowser/method-chooser.js",
162
+ "dependencies/broadcast-channel/dist/esbrowser/method-chooser.mjs",
163
+ "dependencies/broadcast-channel/dist/esbrowser/methods/indexed-db.js",
164
+ "dependencies/broadcast-channel/dist/esbrowser/methods/indexed-db.mjs",
165
+ "dependencies/broadcast-channel/dist/esbrowser/methods/localstorage.js",
166
+ "dependencies/broadcast-channel/dist/esbrowser/methods/localstorage.mjs",
167
+ "dependencies/broadcast-channel/dist/esbrowser/methods/native.js",
168
+ "dependencies/broadcast-channel/dist/esbrowser/methods/native.mjs",
169
+ "dependencies/broadcast-channel/dist/esbrowser/methods/simulate.js",
170
+ "dependencies/broadcast-channel/dist/esbrowser/methods/simulate.mjs",
171
+ "dependencies/broadcast-channel/dist/esbrowser/options.js",
172
+ "dependencies/broadcast-channel/dist/esbrowser/options.mjs",
173
+ "dependencies/broadcast-channel/dist/esbrowser/util.js",
174
+ "dependencies/broadcast-channel/dist/esbrowser/util.mjs",
175
+ "dependencies/centrifuge/build/index.js",
176
+ "dependencies/centrifuge/build/index.mjs",
153
177
  "dependencies/is-retry-allowed/index.js",
154
178
  "dependencies/is-retry-allowed/index.mjs",
179
+ "dependencies/oblivious-set/dist/es/index.js",
180
+ "dependencies/oblivious-set/dist/es/index.mjs",
181
+ "dependencies/unload/dist/es/browser.js",
182
+ "dependencies/unload/dist/es/browser.mjs",
183
+ "dependencies/unload/dist/es/index.js",
184
+ "dependencies/unload/dist/es/index.mjs",
185
+ "dependencies/unload/dist/es/node.js",
186
+ "dependencies/unload/dist/es/node.mjs",
155
187
  "index.d.ts",
156
188
  "index.js",
157
189
  "index.js.flow",
158
190
  "index.mjs",
159
191
  "packages.json",
192
+ "socket/index.js",
193
+ "socket/index.mjs",
160
194
  "utils/uuid.js",
161
195
  "utils/uuid.mjs"
162
196
  ],
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var t=require('./../dependencies/centrifuge/build/index.js');var n=require('./../dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.js');var i=require('./../dependencies/broadcast-channel/dist/esbrowser/leader-election.js');exports.SocketService=class SocketService{constructor(e){var t;this.config=void 0,this.channel=new n.BroadcastChannel('shared-socket'),this.elector=void 0,this.client=void 0,this.connected=false,this.logger=console,this.config=e,this.logger=null!==(t=null==e?void 0:e.logger)&&void 0!==t?t:this.logger,globalThis.addEventListener('beforeunload',(()=>{this.disconnect()}))}setToken(e){var t;this.config.token=e,null===(t=this.client)||void 0===t||t.setToken(e)}createClient(){var e;if(this.connected||void 0!==this.client)return this.client;this.logger.debug('Try to connect with Centrifuge client');var n=null!==(e=this.config.transport)&&void 0!==e?e:[];var i=(()=>{var e=n.find((e=>'http_stream'===e.transport));if(e)return"".concat(new URL(e.endpoint).origin,"/emulation")})();try{var s,r;return this.client=new t.Centrifuge(null!==(s=this.config.transport)&&void 0!==s?s:[],{debug:null!==(r=this.config.debug)&&void 0!==r&&r,emulationEndpoint:i,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug('Create Centrifuge instance',this.client),this.client.on('disconnected',(e=>{this.connected=false,this.logger.debug('Centrifuge connection is closed and will not be reconnected',e)})),this.client.on('connected',(e=>{this.connected=true,this.logger.debug('Centrifuge is connected with context',e)})),this.client}catch(e){this.logger.error('Failed to create the Centrifuge instance',{reason:e.toString()})}}disconnect(){var e;void 0!==this.client&&(null===(e=this.channel)||void 0===e||e.close(),this.client.disconnect(),this.client=void 0,this.elector=void 0,this.connected=false)}subscriptionExists(e){if(!this.client)return false;var t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;var i=this.createClient();if(i){var s=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug('Create centrifuge subscription',s),s&&(s.on('publication',(e=>{var n;var{data:i}=e;this.logger.debug('Get message from ws: ',i),t(i),null===(n=this.channel)||void 0===n||n.postMessage(i)})),s.subscribe(),i.connect())}}subscribe(t,s){var r=this;return e((function*(){r.subscriptionExists(t)?r.logger.debug('Subscription to the channel is exists. Ignore subscribe.'):(r.logger.debug('Create broadcast channel with name',t),r.channel=new n.BroadcastChannel(t),r.elector=i.createLeaderElection(r.channel),r.logger.debug('Wait leader',r.elector),r.elector.onduplicate=()=>{r.disconnect(),r.subscribe(t,s)},r.elector.awaitLeadership().then((()=>{r.logger.debug('Current tab is leader',r.elector),r.join(t,s)})),r.channel.addEventListener('message',(e=>{r.logger.debug('Get message from broadcast: ',e),s(e)})))}))()}unsubscribe(e){var t;var n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}};
@@ -0,0 +1 @@
1
+ import e from'./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{Centrifuge as t}from'./../dependencies/centrifuge/build/index.mjs';import{BroadcastChannel as n}from'./../dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.mjs';import{createLeaderElection as i}from'./../dependencies/broadcast-channel/dist/esbrowser/leader-election.mjs';class SocketService{constructor(e){var t;this.config=void 0,this.channel=new n('shared-socket'),this.elector=void 0,this.client=void 0,this.connected=false,this.logger=console,this.config=e,this.logger=null!==(t=null==e?void 0:e.logger)&&void 0!==t?t:this.logger,globalThis.addEventListener('beforeunload',(()=>{this.disconnect()}))}setToken(e){var t;this.config.token=e,null===(t=this.client)||void 0===t||t.setToken(e)}createClient(){var e;if(this.connected||void 0!==this.client)return this.client;this.logger.debug('Try to connect with Centrifuge client');var n=null!==(e=this.config.transport)&&void 0!==e?e:[];var i=(()=>{var e=n.find((e=>'http_stream'===e.transport));if(e)return"".concat(new URL(e.endpoint).origin,"/emulation")})();try{var o,s;return this.client=new t(null!==(o=this.config.transport)&&void 0!==o?o:[],{debug:null!==(s=this.config.debug)&&void 0!==s&&s,emulationEndpoint:i,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug('Create Centrifuge instance',this.client),this.client.on('disconnected',(e=>{this.connected=false,this.logger.debug('Centrifuge connection is closed and will not be reconnected',e)})),this.client.on('connected',(e=>{this.connected=true,this.logger.debug('Centrifuge is connected with context',e)})),this.client}catch(e){this.logger.error('Failed to create the Centrifuge instance',{reason:e.toString()})}}disconnect(){var e;void 0!==this.client&&(null===(e=this.channel)||void 0===e||e.close(),this.client.disconnect(),this.client=void 0,this.elector=void 0,this.connected=false)}subscriptionExists(e){if(!this.client)return false;var t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;var i=this.createClient();if(i){var o=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug('Create centrifuge subscription',o),o&&(o.on('publication',(e=>{var n;var{data:i}=e;this.logger.debug('Get message from ws: ',i),t(i),null===(n=this.channel)||void 0===n||n.postMessage(i)})),o.subscribe(),i.connect())}}subscribe(t,o){var s=this;return e((function*(){s.subscriptionExists(t)?s.logger.debug('Subscription to the channel is exists. Ignore subscribe.'):(s.logger.debug('Create broadcast channel with name',t),s.channel=new n(t),s.elector=i(s.channel),s.logger.debug('Wait leader',s.elector),s.elector.onduplicate=()=>{s.disconnect(),s.subscribe(t,o)},s.elector.awaitLeadership().then((()=>{s.logger.debug('Current tab is leader',s.elector),s.join(t,o)})),s.channel.addEventListener('message',(e=>{s.logger.debug('Get message from broadcast: ',e),o(e)})))}))()}unsubscribe(e){var t;var n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}}export{SocketService};