@foxford/services 1.3.0 → 1.4.0-beta-4f8f0fa6-20250204

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 (152) hide show
  1. package/README.md +30 -96
  2. package/index.d.ts +12 -12
  3. package/index.js +1 -1
  4. package/index.js.flow +24 -13
  5. package/index.mjs +1 -1
  6. package/package.json +40 -182
  7. package/_virtual/_commonjsHelpers.js +0 -1
  8. package/_virtual/_commonjsHelpers.mjs +0 -1
  9. package/_virtual/axios.js +0 -1
  10. package/_virtual/axios.mjs +0 -1
  11. package/_virtual/index.js +0 -1
  12. package/_virtual/index.mjs +0 -1
  13. package/_virtual/index2.js +0 -1
  14. package/_virtual/index2.mjs +0 -1
  15. package/api/index.js +0 -1
  16. package/api/index.mjs +0 -1
  17. package/api/interceptors/request.js +0 -1
  18. package/api/interceptors/request.mjs +0 -1
  19. package/api/interceptors/response.js +0 -1
  20. package/api/interceptors/response.mjs +0 -1
  21. package/api/interceptors/responseFail.js +0 -1
  22. package/api/interceptors/responseFail.mjs +0 -1
  23. package/api/plugins/request/index.js +0 -1
  24. package/api/plugins/request/index.mjs +0 -1
  25. package/api/plugins/response-success/index.js +0 -1
  26. package/api/plugins/response-success/index.mjs +0 -1
  27. package/captcha/cloudflare/constants.js +0 -1
  28. package/captcha/cloudflare/constants.mjs +0 -1
  29. package/captcha/cloudflare/index.js +0 -1
  30. package/captcha/cloudflare/index.mjs +0 -1
  31. package/captcha/cloudflare/style.js +0 -1
  32. package/captcha/cloudflare/style.mjs +0 -1
  33. package/captcha/cloudflare/template.js +0 -1
  34. package/captcha/cloudflare/template.mjs +0 -1
  35. package/captcha/error.js +0 -1
  36. package/captcha/error.mjs +0 -1
  37. package/captcha/google/constants.js +0 -1
  38. package/captcha/google/constants.mjs +0 -1
  39. package/captcha/google/index.js +0 -1
  40. package/captcha/google/index.mjs +0 -1
  41. package/captcha/index.js +0 -1
  42. package/captcha/index.mjs +0 -1
  43. package/captcha/log.js +0 -1
  44. package/captcha/log.mjs +0 -1
  45. package/dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js +0 -1
  46. package/dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs +0 -1
  47. package/dependencies/@babel/runtime/helpers/esm/defineProperty.js +0 -1
  48. package/dependencies/@babel/runtime/helpers/esm/defineProperty.mjs +0 -1
  49. package/dependencies/@babel/runtime/helpers/esm/objectSpread2.js +0 -1
  50. package/dependencies/@babel/runtime/helpers/esm/objectSpread2.mjs +0 -1
  51. package/dependencies/@babel/runtime/helpers/esm/toPrimitive.js +0 -1
  52. package/dependencies/@babel/runtime/helpers/esm/toPrimitive.mjs +0 -1
  53. package/dependencies/@babel/runtime/helpers/esm/toPropertyKey.js +0 -1
  54. package/dependencies/@babel/runtime/helpers/esm/toPropertyKey.mjs +0 -1
  55. package/dependencies/@babel/runtime/helpers/esm/typeof.js +0 -1
  56. package/dependencies/@babel/runtime/helpers/esm/typeof.mjs +0 -1
  57. package/dependencies/axios/index.js +0 -1
  58. package/dependencies/axios/index.mjs +0 -1
  59. package/dependencies/axios/lib/adapters/xhr.js +0 -1
  60. package/dependencies/axios/lib/adapters/xhr.mjs +0 -1
  61. package/dependencies/axios/lib/axios.js +0 -1
  62. package/dependencies/axios/lib/axios.mjs +0 -1
  63. package/dependencies/axios/lib/cancel/Cancel.js +0 -1
  64. package/dependencies/axios/lib/cancel/Cancel.mjs +0 -1
  65. package/dependencies/axios/lib/cancel/CancelToken.js +0 -1
  66. package/dependencies/axios/lib/cancel/CancelToken.mjs +0 -1
  67. package/dependencies/axios/lib/cancel/isCancel.js +0 -1
  68. package/dependencies/axios/lib/cancel/isCancel.mjs +0 -1
  69. package/dependencies/axios/lib/core/Axios.js +0 -1
  70. package/dependencies/axios/lib/core/Axios.mjs +0 -1
  71. package/dependencies/axios/lib/core/InterceptorManager.js +0 -1
  72. package/dependencies/axios/lib/core/InterceptorManager.mjs +0 -1
  73. package/dependencies/axios/lib/core/buildFullPath.js +0 -1
  74. package/dependencies/axios/lib/core/buildFullPath.mjs +0 -1
  75. package/dependencies/axios/lib/core/createError.js +0 -1
  76. package/dependencies/axios/lib/core/createError.mjs +0 -1
  77. package/dependencies/axios/lib/core/dispatchRequest.js +0 -1
  78. package/dependencies/axios/lib/core/dispatchRequest.mjs +0 -1
  79. package/dependencies/axios/lib/core/enhanceError.js +0 -1
  80. package/dependencies/axios/lib/core/enhanceError.mjs +0 -1
  81. package/dependencies/axios/lib/core/mergeConfig.js +0 -1
  82. package/dependencies/axios/lib/core/mergeConfig.mjs +0 -1
  83. package/dependencies/axios/lib/core/settle.js +0 -1
  84. package/dependencies/axios/lib/core/settle.mjs +0 -1
  85. package/dependencies/axios/lib/core/transformData.js +0 -1
  86. package/dependencies/axios/lib/core/transformData.mjs +0 -1
  87. package/dependencies/axios/lib/defaults.js +0 -1
  88. package/dependencies/axios/lib/defaults.mjs +0 -1
  89. package/dependencies/axios/lib/helpers/bind.js +0 -1
  90. package/dependencies/axios/lib/helpers/bind.mjs +0 -1
  91. package/dependencies/axios/lib/helpers/buildURL.js +0 -1
  92. package/dependencies/axios/lib/helpers/buildURL.mjs +0 -1
  93. package/dependencies/axios/lib/helpers/combineURLs.js +0 -1
  94. package/dependencies/axios/lib/helpers/combineURLs.mjs +0 -1
  95. package/dependencies/axios/lib/helpers/cookies.js +0 -1
  96. package/dependencies/axios/lib/helpers/cookies.mjs +0 -1
  97. package/dependencies/axios/lib/helpers/isAbsoluteURL.js +0 -1
  98. package/dependencies/axios/lib/helpers/isAbsoluteURL.mjs +0 -1
  99. package/dependencies/axios/lib/helpers/isAxiosError.js +0 -1
  100. package/dependencies/axios/lib/helpers/isAxiosError.mjs +0 -1
  101. package/dependencies/axios/lib/helpers/isURLSameOrigin.js +0 -1
  102. package/dependencies/axios/lib/helpers/isURLSameOrigin.mjs +0 -1
  103. package/dependencies/axios/lib/helpers/normalizeHeaderName.js +0 -1
  104. package/dependencies/axios/lib/helpers/normalizeHeaderName.mjs +0 -1
  105. package/dependencies/axios/lib/helpers/parseHeaders.js +0 -1
  106. package/dependencies/axios/lib/helpers/parseHeaders.mjs +0 -1
  107. package/dependencies/axios/lib/helpers/spread.js +0 -1
  108. package/dependencies/axios/lib/helpers/spread.mjs +0 -1
  109. package/dependencies/axios/lib/utils.js +0 -1
  110. package/dependencies/axios/lib/utils.mjs +0 -1
  111. package/dependencies/axios-retry/index.js +0 -1
  112. package/dependencies/axios-retry/index.mjs +0 -1
  113. package/dependencies/axios-retry/lib/index.js +0 -1
  114. package/dependencies/axios-retry/lib/index.mjs +0 -1
  115. package/dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.js +0 -1
  116. package/dependencies/broadcast-channel/dist/esbrowser/broadcast-channel.mjs +0 -1
  117. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-util.js +0 -1
  118. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-util.mjs +0 -1
  119. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-web-lock.js +0 -1
  120. package/dependencies/broadcast-channel/dist/esbrowser/leader-election-web-lock.mjs +0 -1
  121. package/dependencies/broadcast-channel/dist/esbrowser/leader-election.js +0 -1
  122. package/dependencies/broadcast-channel/dist/esbrowser/leader-election.mjs +0 -1
  123. package/dependencies/broadcast-channel/dist/esbrowser/method-chooser.js +0 -1
  124. package/dependencies/broadcast-channel/dist/esbrowser/method-chooser.mjs +0 -1
  125. package/dependencies/broadcast-channel/dist/esbrowser/methods/indexed-db.js +0 -1
  126. package/dependencies/broadcast-channel/dist/esbrowser/methods/indexed-db.mjs +0 -1
  127. package/dependencies/broadcast-channel/dist/esbrowser/methods/localstorage.js +0 -1
  128. package/dependencies/broadcast-channel/dist/esbrowser/methods/localstorage.mjs +0 -1
  129. package/dependencies/broadcast-channel/dist/esbrowser/methods/native.js +0 -1
  130. package/dependencies/broadcast-channel/dist/esbrowser/methods/native.mjs +0 -1
  131. package/dependencies/broadcast-channel/dist/esbrowser/methods/simulate.js +0 -1
  132. package/dependencies/broadcast-channel/dist/esbrowser/methods/simulate.mjs +0 -1
  133. package/dependencies/broadcast-channel/dist/esbrowser/options.js +0 -1
  134. package/dependencies/broadcast-channel/dist/esbrowser/options.mjs +0 -1
  135. package/dependencies/broadcast-channel/dist/esbrowser/util.js +0 -1
  136. package/dependencies/broadcast-channel/dist/esbrowser/util.mjs +0 -1
  137. package/dependencies/centrifuge/build/index.js +0 -1
  138. package/dependencies/centrifuge/build/index.mjs +0 -1
  139. package/dependencies/is-retry-allowed/index.js +0 -1
  140. package/dependencies/is-retry-allowed/index.mjs +0 -1
  141. package/dependencies/oblivious-set/dist/es/index.js +0 -1
  142. package/dependencies/oblivious-set/dist/es/index.mjs +0 -1
  143. package/dependencies/unload/dist/es/browser.js +0 -1
  144. package/dependencies/unload/dist/es/browser.mjs +0 -1
  145. package/dependencies/unload/dist/es/index.js +0 -1
  146. package/dependencies/unload/dist/es/index.mjs +0 -1
  147. package/dependencies/unload/dist/es/node.js +0 -1
  148. package/dependencies/unload/dist/es/node.mjs +0 -1
  149. package/socket/index.js +0 -1
  150. package/socket/index.mjs +0 -1
  151. package/utils/uuid.js +0 -1
  152. package/utils/uuid.mjs +0 -1
package/README.md CHANGED
@@ -1,113 +1,47 @@
1
1
  # Сервисы Foxford
2
2
 
3
3
  Библиотека фронтовых сервисов, которые помогут реализовать тот или иной функционал на уровне приложения.
4
- Здесь будут появляться сервисы фокса, которые будут "отвязаны" от других сервисов и функций, не принадлежащих им.
5
4
 
6
5
  ### Captcha Service
7
6
 
8
7
  Сервис для работы с капчей.
9
- В зависимости от данных с бэка используется или Google-капча, или Cloudflare Turnstile
10
8
 
11
- ---
12
-
13
- ## API Service
14
-
15
- ### Для чего?
16
-
17
- Чтобы разные проекты использовали единый HTTP-клиент (Axios) сервис апи был вынесен в пакеты
18
- и опубликован в [npm](https://www.npmjs.com/package/@foxford/services)
19
-
20
- Апи из пакета сервисов представляет собой фабрику, которая принимает параметры и возвращает
21
- инстанс клиента, подробнее описано [здесь](./api/README.md)
22
-
23
- ---
24
-
25
- ### Как обесепечивается единобразное использование HTTP-клиента?
26
-
27
- > Точкой правды, поставщиком HTTP-клиента является `@foxford/foxford-js-sdk (FoxfordService)`
28
- > Все "потребители" должны использовать HTTP-клиент из `FoxfordService`
29
-
30
- `FoxfordService` использует пакет сервисов `@foxford/services` для получения инстанса Api
31
- конфигурирует его и примешивает [Interceptors](https://axios-http.com/docs/interceptors)
32
- и отдает наружу два клиента:
33
-
34
- 1. `FoxfordService.foxApi` - инстанс Api, ориентированный на использование внутренних сервисов Фоксфорда, в нем:
35
-
36
- - Используются `Api Interceptors`
37
- По умолчанию используются два обязательных перехватчика(`camelize` и `referrer`) и один опциональный(`captcha`) в `interceptors.request`, это:
38
- - `camelize` - для преобразования кейса в ответе запроса
39
- - `referrer` - для проброса реферрера в запросе
40
- - `captcha` - опциональный, будет добавлен, если при инициализации `FoxfordService`,
41
- в конфиге будет передан конфиг для капчи. Подробнее [здесь](./api/README.md)
42
- - Используется `axiosRetry` - плагин Api, перехватывающий упавшие запрос и поторяющий его (3 раза)
43
- - Указан `baseURL`
44
-
45
- 2. `FoxfordService.api` - "базовый" инстанс Api, который имеет минимальную конфигурацию и не использует Interceptors и в нем не указан baseUrl
46
- Предназначен для хождения "наружу"
47
-
48
- #### Базовый конфиг Api используемый для `FoxfordService.api`
49
-
50
- ```javascript
51
- {
52
- xsrfCookieName: CSRF_COOKIE_NAME,
53
- xsrfHeaderName: 'X-CSRF-Token',
54
- headers: { 'X-Requested-With': 'XMLHttpRequest' },
55
- }
56
- ```
57
-
58
- #### Конфиг Api используемый для `FoxfordService.foxApi`
59
-
60
- ```javascript
61
- {
62
- xsrfCookieName: CSRF_COOKIE_NAME,
63
- xsrfHeaderName: 'X-CSRF-Token',
64
- headers: { 'X-Requested-With': 'XMLHttpRequest' },
65
- withCredentials: true,
9
+ Представляет из себя фасад для работы с одним из провайдеров (Recaptcha, Cloudflare Turnstile, YandexSmartCaptcha).
10
+
11
+ Все капчи работают в режиме `invisible`.
12
+
13
+ ```js
14
+ type ProviderName = 'recaptcha' | 'cloudflare_turnstile' | 'yandex_smart_captcha'
15
+ type CaptchaConfig = {
16
+ locale?: string
17
+ sitekey?: string
18
+ provider?: ProviderName
19
+ notify?: (...args: any[]) => void // метод для нотификации юзера об ошибке
20
+ onRenderCaptcha?: (provider: ProviderName) => void // событие когда виджет капчи будет срендерен(не обязательно виден)
21
+ onSuccessChallenge?: (provider: ProviderName) => void // событие когда капча успешно решена(токен получен)
22
+ onErrorChallenge?: (provider: ProviderName, error: CaptchaError) => void // событие когда при решение произошла ошибка
23
+ onWarnChallenge?: (provider: ProviderName, error: CaptchaError) => void // событие когда при решении произошла не критичная ошибка
24
+ onBeforeInteractiveChallenge?: (provider: ProviderName) => void // событие когда invisible капча "поднимается" для юзера
25
+ onAfterInteractiveChallenge?: (provider: ProviderName) => void // событие когда открытая invisible капча решается юзером
66
26
  }
67
27
  ```
68
28
 
69
- При необходимости можно расширить или переопределить конфиг для `FoxfordService.foxApi`
70
-
71
- ---
29
+ Пример использования
72
30
 
73
- ### Пример использования апи из `FoxfordService`
31
+ ```js
32
+ import { CaptchaService } from '@foxford/services'
74
33
 
75
- ```javascript
76
- import { Foxford } from '@foxford/foxford-js-sdk'
77
-
78
- const myHost = 'exampleHost'
79
- const FoxfordService = new Foxford({
80
- api: {
81
- config: {
82
- baseURL: myHost,
83
- },
84
- },
85
- host: myHost, // легаси, на работу апи не влияет, есть "на всякий случай",
86
- recaptchaConfig: {
87
- locale: 'ru',
88
- sitekey: 'captchaSecretKey',
89
- },
34
+ const captcha = new CaptchaService({
35
+ locale: 'ru',
36
+ sitekey: 'KEY',
37
+ provider: 'yandex_smart_captcha',
90
38
  })
91
39
 
92
- const getInternalData = () => {
93
- FoxfordService.foxApi.get(`/some-internal-url-protected-with-captcha`).then(({ data }) => data)
94
- }
95
-
96
- const getExternalData = () => {
97
- FoxfordService.api.get(`https://some.external.source`).then(({ data }) => data)
98
- }
99
- ```
100
-
101
- ### Пример использования апи в `stoege`
102
-
103
- ```js static
104
- import { Api, BaseApi } from 'services/api'
105
-
106
- const getInternalData = () => {
107
- Api.get(`/some-internal-url-protected-with-captcha`).then(({ data }) => data)
108
- }
109
-
110
- const getExternalData = () => {
111
- BaseApi.get(`https://some.external.source`).then(({ data }) => data)
40
+ async function submit() {
41
+ const token = await captcha.execute()
42
+ // {
43
+ // captcha_provider: 'yandex_smart_captcha',
44
+ // captcha_token: 'TOKEN',
45
+ // }
112
46
  }
113
47
  ```
package/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  // Generated by dts-bundle-generator v8.0.1
2
2
 
3
- /* eslint-disable @typescript-eslint/no-explicit-any */
4
3
  export interface ApiTransformer {
5
4
  (data: any, headers?: any): any;
6
5
  }
@@ -129,10 +128,12 @@ export interface ResponseError {
129
128
  errorText: string;
130
129
  headers: ApiResponse["headers"];
131
130
  data: ApiResponse["data"];
132
- originalRequest: ApiRequestConfig & {
133
- _touched?: boolean;
134
- };
135
131
  }
132
+ export type ApiErrorExtended = ApiError & {
133
+ config: ApiRequestConfig & {
134
+ _retry?: boolean;
135
+ };
136
+ };
136
137
  export type ApiRequestConfigExtended = ApiRequestConfig & {
137
138
  camelize?: boolean;
138
139
  withCaptcha?: boolean;
@@ -178,8 +179,8 @@ export declare class CaptchaError extends Error {
178
179
  capture?: boolean;
179
180
  constructor(message: string);
180
181
  }
181
- type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile";
182
- type CaptchaAnswer = {
182
+ export type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile" | "yandex_smart_captcha";
183
+ export type CaptchaAnswer = {
183
184
  captcha_token: string;
184
185
  captcha_provider: CaptchaProviderName;
185
186
  };
@@ -187,7 +188,6 @@ export type CaptchaConfig = {
187
188
  locale?: string;
188
189
  sitekey?: string;
189
190
  provider?: CaptchaProviderName;
190
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
191
191
  notify?: (...args: any[]) => void;
192
192
  onRenderCaptcha?: (provider: CaptchaProviderName) => void;
193
193
  onSuccessChallenge?: (provider: CaptchaProviderName) => void;
@@ -196,7 +196,7 @@ export type CaptchaConfig = {
196
196
  onBeforeInteractiveChallenge?: (provider: CaptchaProviderName) => void;
197
197
  onAfterInteractiveChallenge?: (provider: CaptchaProviderName) => void;
198
198
  };
199
- type ExecuteMeta = Record<string, unknown>;
199
+ export type ExecuteMeta = Record<string, unknown>;
200
200
  export interface Captcha {
201
201
  execute(meta?: ExecuteMeta): Promise<CaptchaAnswer | void>;
202
202
  isEnabled(): boolean;
@@ -204,7 +204,6 @@ export interface Captcha {
204
204
  export declare class CaptchaService implements Captcha {
205
205
  private sitekey;
206
206
  private provider;
207
- private locale;
208
207
  private captcha;
209
208
  constructor(config: CaptchaConfig);
210
209
  isEnabled(): boolean;
@@ -214,14 +213,15 @@ export declare class CaptchaService implements Captcha {
214
213
  */
215
214
  execute(meta?: ExecuteMeta): Promise<CaptchaAnswer | void>;
216
215
  }
217
- type TransportName = "websocket" | "http_stream" | "sse" | "sockjs" | "webtransport";
218
- interface TransportEndpoint {
216
+ export type TransportName = "websocket" | "http_stream" | "sse" | "sockjs" | "webtransport";
217
+ /** TransportEndpoint allows configuring transport when using fallback mode */
218
+ export interface TransportEndpoint {
219
219
  /** transport to use */
220
220
  transport: TransportName;
221
221
  /** endpoint for a selected transport type */
222
222
  endpoint: string;
223
223
  }
224
- type SocketServiceConfig = {
224
+ export type SocketServiceConfig = {
225
225
  refreshToken: () => Promise<string>;
226
226
  token: string;
227
227
  logger?: {
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('./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;
1
+ "use strict";var e=require("axios"),t=require("axios-retry"),n=require("broadcast-channel"),r=require("centrifuge");function i(e,t,n,r){return new(n||(n=Promise))((function(i,o){function s(e){try{c(r.next(e))}catch(e){o(e)}}function a(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}function o(e,t,n){return e.headers=Object.assign({"Content-Type":"application/json"},e.headers),window&&window.location&&window.location.pathname&&window.location.origin&&(e.headers=Object.assign(Object.assign({},e.headers),{"X-Referer":window.location.origin+window.location.pathname})),n.length>0?function(e,t,n){return i(this,void 0,void 0,(function*(){for(const r of n)r.isApplicable(e)&&(e=yield r.execute(e,t));return e}))}(e,t,n):e}function s(e,t,n){return n.length>0?function(e,t,n){return i(this,void 0,void 0,(function*(){for(const r of n)r.isApplicable(e)&&(e=yield r.execute(e,t));return e}))}(e,t,n):e}"function"==typeof SuppressedError&&SuppressedError;const a=[422,401];function c(e){const{config:t=null,response:n=null}=e;if(null===t||null===n)return Promise.reject(e);const r=t;a.includes(n.status)&&(r._retry=!0);const i=Object.assign({errorText:e.toString(),headers:n.headers,status:n.status,statusText:n.statusText},"object"==typeof n.data?n.data:{data:n.data});return Promise.reject(i)}const l=new class{createFoxApiInstance({config:n,plugins:r=[]}){const i=e.create(n),a=this.filterPlugins(r,"request"),l=this.filterPlugins(r,"responseSuccess");return i.interceptors.request.use((e=>o(e,i,[...a]))),i.interceptors.response.use((e=>s(e,i,[...l])),c),t(i,{retries:3,retryDelay:t.exponentialDelay}),i}createApiInstance({config:t}){return e.create(t)}createStaticApiInstance(){const t=e;return t.isApiError=e=>"object"==typeof e&&!0===e.isAxiosError,t}filterPlugins(e,t){return e?e.filter((e=>e.pluginType===t)):[]}},d="turnstile-container",h="turnstile-widget";var u=`\n<div id="${d}" class="fox-cf-turnstile">\n <div class="fox-cf-turnstile__overlay"></div>\n <div class="fox-cf-turnstile__content">\n <div class="fox-cf-turnstile__content__text">\n <h3>Надо убедиться, что вы человек</h3>\n <span>Поставьте галочку, нажав на белый квадрат ниже — проверка займёт буквально секунду</span>\n </div>\n <div id="${h}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class p extends Error{constructor(e){super(e),this.capture=!0,this.name="CaptchaError",this.message=e}}function f(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const g=(...e)=>{};class v{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:r,onSuccessChallenge:i,onErrorChallenge:o,onWarnChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.locale="ru",this.provider="cloudflare_turnstile",this.container=null,this.notifyHandler=null!=n?n:g,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=r?r:g,this.onSuccessChallenge=null!=i?i:g,this.onErrorChallenge=null!=o?o:g,this.onWarnChallenge=null!=s?s:g,this.onBeforeInteractiveChallenge=null!=a?a:g,this.onAfterInteractiveChallenge=null!=c?c:g,t&&(this.locale=t),this.addDomElements(),v.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(d)||(document.body.insertAdjacentHTML("beforeend",u),document.body.insertAdjacentHTML("beforeend","<style>\n.fox-cf-turnstile {\n position: fixed;\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100vw;\n height: 100vh;\n z-index: -1;\n}\n.fox-cf-turnstile__noscroll {\n position: fixed; \n top: var(--st, 0);\n inline-size: 100%;\n overflow-y:scroll; \n}\n.fox-cf-turnstile--showing {\n z-index: 9999;\n}\n.fox-cf-turnstile__overlay {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: rgba(246, 247, 251, 0.9);\n opacity: 0;\n transition: all .3s ease;\n transition-delay: .2s;\n z-index: 0;\n}\n.fox-cf-turnstile__content {\n background: white;\n border-radius: 5px;\n max-width: 500px;\n max-height: 50vh;\n position: relative;\n z-index: 1;\n box-shadow: rgba(0, 0, 0, 0.08) 0px 10px 20px 0px;\n height: 1px;\n width: 1px;\n overflow: hidden;\n transition: all .8s ease, opacity 0.3s ease;\n transition-delay: .3s;\n opacity: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n font-size: 1.2rem;\n}\n.fox-cf-turnstile__content__text {\n flex: 1;\n margin-bottom: 20px;\n opacity: 1;\n overflow: hidden;\n transition: opacity 0.3s ease;\n text-align: center;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__overlay, .fox-cf-turnstile--show .fox-cf-turnstile__overlay {\n opacity: 1;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__content, .fox-cf-turnstile--show .fox-cf-turnstile__content {\n width: 100%;\n height: auto;\n min-height: 20vh;\n min-width: 30vw;\n padding: 30px;\n opacity: 1;\n}\n.fox-cf-turnstile__content__text h3 {\n font-size: 1.4rem;\n}\n.fox-cf-turnstile__loader {\n font-size: 10px;\n margin: 50px auto;\n text-indent: -9999em;\n width: 5em;\n height: 5em;\n border-radius: 50%;\n background: #8b1feb;\n background: -moz-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -webkit-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -o-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -ms-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: linear-gradient(to right, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n position: relative;\n -webkit-animation: load3 1.4s infinite linear;\n animation: load3 1.4s infinite linear;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n}\n.fox-cf-turnstile__loader:before {\n width: 50%;\n height: 50%;\n background: #8b1feb;\n border-radius: 100% 0 0 0;\n position: absolute;\n top: 0;\n left: 0;\n content: '';\n}\n.fox-cf-turnstile__loader:after {\n background: white;\n width: 75%;\n height: 75%;\n border-radius: 50%;\n content: '';\n margin: auto;\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n}\n@-webkit-keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n} \n</style>"),this.container=document.getElementById(d))}static appendScript(e){return i(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}show(){var e;null===(e=this.container)||void 0===e||e.classList.add("fox-cf-turnstile--showing"),v.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"),v.bodyScrollUnlock()}loadScript(){return i(this,void 0,void 0,(function*(){if(window.turnstile)return Promise.resolve(window.turnstile);const e=()=>i(this,void 0,void 0,(function*(){return yield v.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return new Promise(((t,n)=>{window.onloadTurnstileCallback=()=>{this.turnstileReady(),window.turnstile?t(window.turnstile):n(new p("Cloudflare Turnstile is not available"))},e().catch((()=>n(new p("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;f("Cloudflare Turnstile is ready",window.turnstile),null===(t=null===(e=this.container)||void 0===e?void 0:e.querySelector(".fox-cf-turnstile__loader"))||void 0===t||t.remove()}static normalizeLocation(e=""){return e.substring(0,31).replace(/\//g,"_")}static bodyScrollLock(){const e=document.body;e.style.setProperty("--st",`-${document.documentElement.scrollTop}px`),e.classList.add("fox-cf-turnstile__noscroll")}static bodyScrollUnlock(){document.body.classList.remove("fox-cf-turnstile__noscroll")}renderWidget(e){return i(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{var r;let i="";function o(){var e;null===(e=window.turnstile)||void 0===e||e.reset(i),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(i)}),500)}i=null===(r=window.turnstile)||void 0===r?void 0:r.render(`#${h}`,{action:v.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{f("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{f("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{f("Challenge Success"),this.hide(),t(e),o()},"error-callback":e=>{n(e),o()},"expired-callback":()=>{this.hide(),n("expired"),o()},language:this.locale,sitekey:this.sitekey,theme:"light","timeout-callback":()=>{this.hide(),n("timeout"),o()},"unsupported-callback":()=>{n("110500"),o()}})}))}))}errorHandler(e){f("Captcha error with code:",e);let t=[...v.NO_RETRY_ERROR_CODES];if("string"!=typeof e)return void this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");const n=e;switch(!0){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(`Что-то пошло не так, код ошибки — ${n}. Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.`)}execute(e){return i(this,void 0,void 0,(function*(){if(this.sitekey){f("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new p("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render turnstile widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new p("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(["110200","110100","110110"].some((t=>e.startsWith(t)))){const t=new p("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(v.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new p("Captcha challenge is failed");t.reason="error",t.capture=!1,t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new p("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:"error",t.capture=!1,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}v.DEBUG=!1,v.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const w="recaptcha-widget";function b(){let e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxx-xxxx-4xxx-yxxx".replace(/[xy]/g,(function(n){let r=16*Math.random();return e>0?(r=(e+r)%16|0,e=Math.floor(e/16)):(r=(t+r)%16|0,t=Math.floor(t/16)),("x"===n?r:3&r|8).toString(16)}))}const m=(...e)=>{};class y{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:r,onSuccessChallenge:i,onWarnChallenge:o,onErrorChallenge:s}){this.sitekey=null,this.locale="ru",this.container=null,this.provider="recaptcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:m,this.onRenderCaptcha=null!=r?r:m,this.onSuccessChallenge=null!=i?i:m,this.onWarnChallenge=null!=o?o:m,this.onErrorChallenge=null!=s?s:m,t&&(this.locale=t),this.addDomElements(),y.DEBUG&&(window.gr=this)}recaptchaReady(){f("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(w))return;document.body.insertAdjacentHTML("beforeend",`<div id="${w}"></div>`);const e=document.getElementById(w);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${y.ERROR_FUNC_NAME}`,expired:`${y.EXPIRED_FUNC_NAME}`,resolve:`${y.RESOLVE_FUNC_NAME}`}}static appendScript(e){return i(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return i(this,void 0,void 0,(function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);const e=()=>i(this,void 0,void 0,(function*(){return yield y.appendScript(`https://www.google.com/recaptcha/api.js?hl=${this.locale}&onload=onloadRecaptchaCallback`)}));return new Promise(((t,n)=>{window.onloadRecaptchaCallback=()=>{this.recaptchaReady(),window.grecaptcha?t(window.grecaptcha):n(new p("Recaptcha is not available"))},e().catch((()=>n(new p("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(f("Recaptcha error:",e),e){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static detectCaptchaChallengeIsShown(){return new Promise((function(e){const t=document.body;const n=new MutationObserver((function(t){t.forEach((t=>{if(t.addedNodes.length){const r=t.addedNodes[0];if(!r)return;if(r.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){const t=r.firstChild;t&&(n.disconnect(),e(t))}}}))}));n.observe(t,{attributeOldValue:!1,attributes:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!1})}))}renderWidget(e){return new Promise(((e,t)=>{var n,r,i;const o=document.createElement("div"),s=`${w}_${b()}`;o.id=s,null===(n=document.getElementById(w))||void 0===n||n.appendChild(o);const a=y.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}y.detectCaptchaChallengeIsShown().then((e=>{if(!e.parentElement)return;const n=new MutationObserver((function(){var r,i;"hidden"!==(null===(r=e.parentElement)||void 0===r?void 0:r.style.visibility)||(null===(i=window.grecaptcha)||void 0===i?void 0:i.getResponse(c))||(n.disconnect(),t("closed"),l())}));n.observe(e.parentElement,{attributeFilter:["style"],attributes:!0})})),window[a.resolve]=()=>{var t;const n=null===(t=window.grecaptcha)||void 0===t?void 0:t.getResponse(c);e(null!=n?n:""),l()},window[a.error]=()=>{t("error"),l()},window[a.expired]=()=>{t("expired"),l()},c=null===(r=window.grecaptcha)||void 0===r?void 0:r.render(s,{callback:a.resolve,"error-callback":a.error,"expired-callback":a.expired,sitekey:this.sitekey,size:"invisible"});const d=null===(i=window.grecaptcha)||void 0===i?void 0:i.execute(c);if(!d)return t(new Error("cannot call method execute from grecaptcha")),void l();d.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),l()}))}))}execute(e){return i(this,void 0,void 0,(function*(){if(this.sitekey){f("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new p("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render Recaptcha widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new p("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new p("Challenge or token expired");e.reason="expired",e.capture=!1,this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new p("Error during captcha execution");e.reason="error",e.capture=!1,this.onErrorChallenge(this.provider,e)}}}}))}}y.RESOLVE_FUNC_NAME="grecaptcha_resolved",y.ERROR_FUNC_NAME="grecaptcha_error",y.EXPIRED_FUNC_NAME="grecaptcha_expired",y.DEBUG=!1;const C="smartcaptcha-container",x=(...e)=>{};class E{constructor({sitekey:e,notify:t,onRenderCaptcha:n,onSuccessChallenge:r,onWarnChallenge:i,onErrorChallenge:o,onBeforeInteractiveChallenge:s,onAfterInteractiveChallenge:a}){this.sitekey=null,this.container=null,this.provider="yandex_smart_captcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=t?t:x,this.onRenderCaptcha=null!=n?n:x,this.onSuccessChallenge=null!=r?r:x,this.onWarnChallenge=null!=i?i:x,this.onErrorChallenge=null!=o?o:x,this.onBeforeInteractiveChallenge=null!=s?s:x,this.onAfterInteractiveChallenge=null!=a?a:x,this.addDomElements()}smartCaptchaReady(){f("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(C))return;document.body.insertAdjacentHTML("beforeend",`<div id="${C}"></div>`);const e=document.getElementById(C);e.style.display="none",this.container=e}static appendScript(e){return i(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return i(this,void 0,void 0,(function*(){if(window.smartCaptcha)return Promise.resolve(window.smartCaptcha);const e=()=>i(this,void 0,void 0,(function*(){return yield E.appendScript("https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadSmartCaptchaCallback")}));return new Promise(((t,n)=>{window.onloadSmartCaptchaCallback=()=>{this.smartCaptchaReady(),window.smartCaptcha?t(window.smartCaptcha):n(new p("SmartCaptcha is not available"))},e().catch((()=>n(new p("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(f("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}renderWidget(e){var t,n,r,i,o,s,a,c;const{promise:l,resolve:d,reject:h}=Promise.withResolvers(),u=document.createElement("div"),f=`${C}_${b()}`;u.id=f,null===(t=document.getElementById(C))||void 0===t||t.appendChild(u),this.onRenderCaptcha(this.provider);const g=window.smartCaptcha.render(f,{callback:e=>{d(e),function(){var e;null===(e=window.smartCaptcha)||void 0===e||e.destroy(g),setTimeout((()=>{u.remove()}),100)}()},hideShield:!0,invisible:!0,sitekey:this.sitekey});return null===(n=window.smartCaptcha)||void 0===n||n.subscribe(g,"challenge-visible",(()=>{this.onBeforeInteractiveChallenge(this.provider)})),null===(r=window.smartCaptcha)||void 0===r||r.subscribe(g,"challenge-hidden",(()=>{this.onAfterInteractiveChallenge(this.provider)})),null===(i=window.smartCaptcha)||void 0===i||i.subscribe(g,"token-expired",(()=>{const e=new p("Token expired");e.reason="expired",h(e)})),null===(o=window.smartCaptcha)||void 0===o||o.subscribe(g,"success",(()=>{this.onSuccessChallenge(this.provider)})),null===(s=window.smartCaptcha)||void 0===s||s.subscribe(g,"network-error",(()=>{const e=new p("Network error");e.reason="timeout",e.capture=!0,h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(g,"javascript-error",(e=>{const t=new p("Javascript error");t.reason="error",t.capture=!0,t.cause=e,h("javascript-error")})),null===(c=window.smartCaptcha)||void 0===c||c.execute(g),l}execute(e){return i(this,void 0,void 0,(function*(){if(this.sitekey){f("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof p?e:new p("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new p("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{f("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(e instanceof p)switch(this.errorHandler(e),e.reason){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз."),this.onWarnChallenge(this.provider,e);break;case"timeout":this.notify("Вероятно у вас проблемы с подключением к сети. Попробуйте еще раз."),this.onErrorChallenge(this.provider,e);break;case"error":this.notify("Произошла непредвиденная ошибка. Мы уже делаем все возможное чтобы устранить её."),this.onErrorChallenge(this.provider,e)}const t=new p("Could not render captcha with error");t.capture=!0,t.cause=e,this.onErrorChallenge(this.provider,t)}}}))}}E.DEBUG=!1;exports.ApiService=l,exports.CaptchaError=p,exports.CaptchaService=class{constructor(e){var t,n;switch(this.sitekey=null,this.provider=null,this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(n=e.provider)&&void 0!==n?n:null,e.provider){case"yandex_smart_captcha":this.captcha=new E(e);break;case"cloudflare_turnstile":this.captcha=new v(e);break;case"recaptcha":this.captcha=new y(e)}}isEnabled(){return"string"==typeof this.sitekey&&""!==this.sitekey}execute(e){return i(this,void 0,void 0,(function*(){if(!1===this.isEnabled())return;if(!this.provider)return;if(!this.captcha)return;const t=yield this.captcha.execute(e);return f("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:null!=t?t:""}}))}},exports.RequestPlugin=class{constructor(){this.pluginType="request"}},exports.ResponseSuccessPlugin=class{constructor(){this.pluginType="responseSuccess"}},exports.SocketService=class{constructor(e){var t;this.channel=new n.BroadcastChannel("shared-socket"),this.elector=void 0,this.client=void 0,this.connected=!1,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,t,n;if(this.connected||void 0!==this.client)return this.client;this.logger.debug("Try to connect with Centrifuge client");const i=null!==(e=this.config.transport)&&void 0!==e?e:[],o=(()=>{const e=i.find((e=>"http_stream"===e.transport));if(e)return`${new URL(e.endpoint).origin}/emulation`})();try{return this.client=new r.Centrifuge(null!==(t=this.config.transport)&&void 0!==t?t:[],{debug:null!==(n=this.config.debug)&&void 0!==n&&n,emulationEndpoint:o,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug("Create Centrifuge instance",this.client),this.client.on("disconnected",(e=>{this.connected=!1,this.logger.debug("Centrifuge connection is closed and will not be reconnected",e)})),this.client.on("connected",(e=>{this.connected=!0,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=!1)}subscriptionExists(e){if(!this.client)return!1;const t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;const r=this.createClient();if(!r)return;const i=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug("Create centrifuge subscription",i),i&&(i.on("publication",(({data:e})=>{var n;this.logger.debug("Get message from ws: ",e),t(e),null===(n=this.channel)||void 0===n||n.postMessage(e)})),i.subscribe(),r.connect())}subscribe(e,t){return i(this,void 0,void 0,(function*(){this.subscriptionExists(e)?this.logger.debug("Subscription to the channel is exists. Ignore subscribe."):(this.logger.debug("Create broadcast channel with name",e),this.channel=new n.BroadcastChannel(e),this.elector=n.createLeaderElection(this.channel),this.logger.debug("Wait leader",this.elector),this.elector.onduplicate=()=>{this.disconnect(),this.subscribe(e,t)},this.elector.awaitLeadership().then((()=>{this.logger.debug("Current tab is leader",this.elector),this.join(e,t)})),this.channel.addEventListener("message",(e=>{this.logger.debug("Get message from broadcast: ",e),t(e)})))}))}unsubscribe(e){var t;const n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}};
package/index.js.flow CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Flowtype definitions for index
2
+ * Flowtype definitions for tmp_index
3
3
  * Generated by Flowgen from a Typescript Definition
4
4
  * Flowgen v1.21.0
5
5
  * @flow
@@ -174,13 +174,18 @@ export interface ResponseError {
174
174
  errorText: string;
175
175
  headers: $PropertyType<ApiResponse<>, "headers">;
176
176
  data: $PropertyType<ApiResponse<>, "data">;
177
- originalRequest: {|
178
- ...ApiRequestConfig,
179
- ...{|
180
- _touched?: boolean,
181
- |},
182
- |};
183
177
  }
178
+ export type ApiErrorExtended = {|
179
+ ...ApiError<>,
180
+ ...{|
181
+ config: {|
182
+ ...ApiRequestConfig,
183
+ ...{|
184
+ _retry?: boolean,
185
+ |},
186
+ |},
187
+ |},
188
+ |};
184
189
  export type ApiRequestConfigExtended = {|
185
190
  ...ApiRequestConfig,
186
191
  ...{|
@@ -243,8 +248,11 @@ declare export class CaptchaError mixins Error {
243
248
  capture?: boolean;
244
249
  constructor(message: string): this;
245
250
  }
246
- declare type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile";
247
- declare type CaptchaAnswer = {|
251
+ export type CaptchaProviderName =
252
+ | "recaptcha"
253
+ | "cloudflare_turnstile"
254
+ | "yandex_smart_captcha";
255
+ export type CaptchaAnswer = {|
248
256
  captcha_token: string,
249
257
  captcha_provider: CaptchaProviderName,
250
258
  |};
@@ -266,7 +274,7 @@ export type CaptchaConfig = {|
266
274
  onBeforeInteractiveChallenge?: (provider: CaptchaProviderName) => void,
267
275
  onAfterInteractiveChallenge?: (provider: CaptchaProviderName) => void,
268
276
  |};
269
- declare type ExecuteMeta = { [key: string]: mixed };
277
+ export type ExecuteMeta = { [key: string]: mixed };
270
278
  export interface Captcha {
271
279
  execute(meta?: ExecuteMeta): Promise<CaptchaAnswer | void>;
272
280
  isEnabled(): boolean;
@@ -281,13 +289,16 @@ declare export class CaptchaService implements Captcha {
281
289
  */
282
290
  execute(meta?: ExecuteMeta): Promise<CaptchaAnswer | void>;
283
291
  }
284
- declare type TransportName =
292
+ export type TransportName =
285
293
  | "websocket"
286
294
  | "http_stream"
287
295
  | "sse"
288
296
  | "sockjs"
289
297
  | "webtransport";
290
- declare interface TransportEndpoint {
298
+ /**
299
+ * TransportEndpoint allows configuring transport when using fallback mode
300
+ */
301
+ export interface TransportEndpoint {
291
302
  /**
292
303
  * transport to use
293
304
  */
@@ -298,7 +309,7 @@ declare interface TransportEndpoint {
298
309
  */
299
310
  endpoint: string;
300
311
  }
301
- declare type SocketServiceConfig = {|
312
+ export type SocketServiceConfig = {|
302
313
  refreshToken: () => Promise<string>,
303
314
  token: string,
304
315
  logger?: {|
package/index.mjs CHANGED
@@ -1 +1 @@
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';
1
+ import e from"axios";import t from"axios-retry";import{BroadcastChannel as n,createLeaderElection as i}from"broadcast-channel";import{Centrifuge as r}from"centrifuge";function o(e,t,n,i){return new(n||(n=Promise))((function(r,o){function s(e){try{c(i.next(e))}catch(e){o(e)}}function a(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((i=i.apply(e,t||[])).next())}))}function s(e,t,n){return e.headers=Object.assign({"Content-Type":"application/json"},e.headers),window&&window.location&&window.location.pathname&&window.location.origin&&(e.headers=Object.assign(Object.assign({},e.headers),{"X-Referer":window.location.origin+window.location.pathname})),n.length>0?function(e,t,n){return o(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}function a(e,t,n){return n.length>0?function(e,t,n){return o(this,void 0,void 0,(function*(){for(const i of n)i.isApplicable(e)&&(e=yield i.execute(e,t));return e}))}(e,t,n):e}"function"==typeof SuppressedError&&SuppressedError;const c=[422,401];function l(e){const{config:t=null,response:n=null}=e;if(null===t||null===n)return Promise.reject(e);const i=t;c.includes(n.status)&&(i._retry=!0);const r=Object.assign({errorText:e.toString(),headers:n.headers,status:n.status,statusText:n.statusText},"object"==typeof n.data?n.data:{data:n.data});return Promise.reject(r)}class d{constructor(){this.pluginType="request"}}class h{constructor(){this.pluginType="responseSuccess"}}const u=new class{createFoxApiInstance({config:n,plugins:i=[]}){const r=e.create(n),o=this.filterPlugins(i,"request"),c=this.filterPlugins(i,"responseSuccess");return r.interceptors.request.use((e=>s(e,r,[...o]))),r.interceptors.response.use((e=>a(e,r,[...c])),l),t(r,{retries:3,retryDelay:t.exponentialDelay}),r}createApiInstance({config:t}){return e.create(t)}createStaticApiInstance(){const t=e;return t.isApiError=e=>"object"==typeof e&&!0===e.isAxiosError,t}filterPlugins(e,t){return e?e.filter((e=>e.pluginType===t)):[]}},p="turnstile-container",f="turnstile-widget";var g=`\n<div id="${p}" class="fox-cf-turnstile">\n <div class="fox-cf-turnstile__overlay"></div>\n <div class="fox-cf-turnstile__content">\n <div class="fox-cf-turnstile__content__text">\n <h3>Надо убедиться, что вы человек</h3>\n <span>Поставьте галочку, нажав на белый квадрат ниже — проверка займёт буквально секунду</span>\n </div>\n <div id="${f}">\n <div class="fox-cf-turnstile__loader"></div>\n </div>\n </div>\n</div>\n`;class v extends Error{constructor(e){super(e),this.capture=!0,this.name="CaptchaError",this.message=e}}function w(...e){const t=["[CaptchaService] ",...e];console.debug.apply(console,t)}const m=(...e)=>{};class b{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onErrorChallenge:o,onWarnChallenge:s,onBeforeInteractiveChallenge:a,onAfterInteractiveChallenge:c}){this.sitekey=null,this.locale="ru",this.provider="cloudflare_turnstile",this.container=null,this.notifyHandler=null!=n?n:m,this.sitekey=null!=e?e:null,this.onRenderCaptcha=null!=i?i:m,this.onSuccessChallenge=null!=r?r:m,this.onErrorChallenge=null!=o?o:m,this.onWarnChallenge=null!=s?s:m,this.onBeforeInteractiveChallenge=null!=a?a:m,this.onAfterInteractiveChallenge=null!=c?c:m,t&&(this.locale=t),this.addDomElements(),b.DEBUG&&(window.cf=this)}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}addDomElements(){this.container||document.getElementById(p)||(document.body.insertAdjacentHTML("beforeend",g),document.body.insertAdjacentHTML("beforeend","<style>\n.fox-cf-turnstile {\n position: fixed;\n top: 0;\n left: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n width: 100vw;\n height: 100vh;\n z-index: -1;\n}\n.fox-cf-turnstile__noscroll {\n position: fixed; \n top: var(--st, 0);\n inline-size: 100%;\n overflow-y:scroll; \n}\n.fox-cf-turnstile--showing {\n z-index: 9999;\n}\n.fox-cf-turnstile__overlay {\n position: absolute;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n background: rgba(246, 247, 251, 0.9);\n opacity: 0;\n transition: all .3s ease;\n transition-delay: .2s;\n z-index: 0;\n}\n.fox-cf-turnstile__content {\n background: white;\n border-radius: 5px;\n max-width: 500px;\n max-height: 50vh;\n position: relative;\n z-index: 1;\n box-shadow: rgba(0, 0, 0, 0.08) 0px 10px 20px 0px;\n height: 1px;\n width: 1px;\n overflow: hidden;\n transition: all .8s ease, opacity 0.3s ease;\n transition-delay: .3s;\n opacity: 0;\n display: flex;\n align-items: center;\n justify-content: center;\n flex-direction: column;\n font-size: 1.2rem;\n}\n.fox-cf-turnstile__content__text {\n flex: 1;\n margin-bottom: 20px;\n opacity: 1;\n overflow: hidden;\n transition: opacity 0.3s ease;\n text-align: center;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__overlay, .fox-cf-turnstile--show .fox-cf-turnstile__overlay {\n opacity: 1;\n}\n.fox-cf-turnstile--showing .fox-cf-turnstile__content, .fox-cf-turnstile--show .fox-cf-turnstile__content {\n width: 100%;\n height: auto;\n min-height: 20vh;\n min-width: 30vw;\n padding: 30px;\n opacity: 1;\n}\n.fox-cf-turnstile__content__text h3 {\n font-size: 1.4rem;\n}\n.fox-cf-turnstile__loader {\n font-size: 10px;\n margin: 50px auto;\n text-indent: -9999em;\n width: 5em;\n height: 5em;\n border-radius: 50%;\n background: #8b1feb;\n background: -moz-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -webkit-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -o-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: -ms-linear-gradient(left, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n background: linear-gradient(to right, #8b1feb 10%, rgba(139,31,235, 0) 42%);\n position: relative;\n -webkit-animation: load3 1.4s infinite linear;\n animation: load3 1.4s infinite linear;\n -webkit-transform: translateZ(0);\n -ms-transform: translateZ(0);\n transform: translateZ(0);\n}\n.fox-cf-turnstile__loader:before {\n width: 50%;\n height: 50%;\n background: #8b1feb;\n border-radius: 100% 0 0 0;\n position: absolute;\n top: 0;\n left: 0;\n content: '';\n}\n.fox-cf-turnstile__loader:after {\n background: white;\n width: 75%;\n height: 75%;\n border-radius: 50%;\n content: '';\n margin: auto;\n position: absolute;\n top: 0;\n left: 0;\n bottom: 0;\n right: 0;\n}\n@-webkit-keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n}\n@keyframes load3 {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg);\n }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg);\n }\n} \n</style>"),this.container=document.getElementById(p))}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}show(){var e;null===(e=this.container)||void 0===e||e.classList.add("fox-cf-turnstile--showing"),b.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"),b.bodyScrollUnlock()}loadScript(){return o(this,void 0,void 0,(function*(){if(window.turnstile)return Promise.resolve(window.turnstile);const e=()=>o(this,void 0,void 0,(function*(){return yield b.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return new Promise(((t,n)=>{window.onloadTurnstileCallback=()=>{this.turnstileReady(),window.turnstile?t(window.turnstile):n(new v("Cloudflare Turnstile is not available"))},e().catch((()=>n(new v("Could not load Cloudflare Turnstile"))))}))}))}turnstileReady(){var e,t;w("Cloudflare Turnstile is ready",window.turnstile),null===(t=null===(e=this.container)||void 0===e?void 0:e.querySelector(".fox-cf-turnstile__loader"))||void 0===t||t.remove()}static normalizeLocation(e=""){return e.substring(0,31).replace(/\//g,"_")}static bodyScrollLock(){const e=document.body;e.style.setProperty("--st",`-${document.documentElement.scrollTop}px`),e.classList.add("fox-cf-turnstile__noscroll")}static bodyScrollUnlock(){document.body.classList.remove("fox-cf-turnstile__noscroll")}renderWidget(e){return o(this,void 0,void 0,(function*(){return new Promise(((t,n)=>{var i;let r="";function o(){var e;null===(e=window.turnstile)||void 0===e||e.reset(r),setTimeout((()=>{var e;null===(e=window.turnstile)||void 0===e||e.remove(r)}),500)}r=null===(i=window.turnstile)||void 0===i?void 0:i.render(`#${f}`,{action:b.normalizeLocation(null==e?void 0:e.location),"after-interactive-callback":()=>{w("after-interactive-callback"),this.onAfterInteractiveChallenge(this.provider)},"before-interactive-callback":()=>{w("before-interactive-callback"),this.onBeforeInteractiveChallenge(this.provider),this.show()},callback:e=>{w("Challenge Success"),this.hide(),t(e),o()},"error-callback":e=>{n(e),o()},"expired-callback":()=>{this.hide(),n("expired"),o()},language:this.locale,sitekey:this.sitekey,theme:"light","timeout-callback":()=>{this.hide(),n("timeout"),o()},"unsupported-callback":()=>{n("110500"),o()}})}))}))}errorHandler(e){w("Captcha error with code:",e);let t=[...b.NO_RETRY_ERROR_CODES];if("string"!=typeof e)return void this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");const n=e;switch(!0){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(`Что-то пошло не так, код ошибки — ${n}. Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.`)}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load cloudflare script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.turnstile){const e=new v("Cloudflare Turnstile is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render turnstile widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new v("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(["110200","110100","110110"].some((t=>e.startsWith(t)))){const t=new v("Invalid sitekey or domain is not allowed");throw t.code=e,this.onErrorChallenge(this.provider,t),t}if(b.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))){const t=new v("Captcha challenge is failed");t.reason="error",t.capture=!1,t.code=e,this.onErrorChallenge(this.provider,t)}else{const t=new v("Captcha challenge has error");t.reason=["timeout","expired"].includes(e)?e:"error",t.capture=!1,t.code=e,this.onWarnChallenge(this.provider,t)}}}}))}}b.DEBUG=!1,b.NO_RETRY_ERROR_CODES=["100","105","106","110100","110110","110200","110420","110430","110500","110510","120","200010","200100"];const y="recaptcha-widget";function C(){let e=(new Date).getTime(),t="undefined"!=typeof performance&&performance.now&&1e3*performance.now()||0;return"xxxx-xxxx-4xxx-yxxx".replace(/[xy]/g,(function(n){let i=16*Math.random();return e>0?(i=(e+i)%16|0,e=Math.floor(e/16)):(i=(t+i)%16|0,t=Math.floor(t/16)),("x"===n?i:3&i|8).toString(16)}))}const x=(...e)=>{};class E{constructor({sitekey:e,locale:t,notify:n,onRenderCaptcha:i,onSuccessChallenge:r,onWarnChallenge:o,onErrorChallenge:s}){this.sitekey=null,this.locale="ru",this.container=null,this.provider="recaptcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=n?n:x,this.onRenderCaptcha=null!=i?i:x,this.onSuccessChallenge=null!=r?r:x,this.onWarnChallenge=null!=o?o:x,this.onErrorChallenge=null!=s?s:x,t&&(this.locale=t),this.addDomElements(),E.DEBUG&&(window.gr=this)}recaptchaReady(){w("Google recaptcha is ready",window.grecaptcha,this)}addDomElements(){if(this.container||document.getElementById(y))return;document.body.insertAdjacentHTML("beforeend",`<div id="${y}"></div>`);const e=document.getElementById(y);e.style.display="none",this.container=e}static getGrecaptchaCallbackNames(){return{error:`${E.ERROR_FUNC_NAME}`,expired:`${E.EXPIRED_FUNC_NAME}`,resolve:`${E.RESOLVE_FUNC_NAME}`}}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return o(this,void 0,void 0,(function*(){if(window.grecaptcha)return Promise.resolve(window.grecaptcha);const e=()=>o(this,void 0,void 0,(function*(){return yield E.appendScript(`https://www.google.com/recaptcha/api.js?hl=${this.locale}&onload=onloadRecaptchaCallback`)}));return new Promise(((t,n)=>{window.onloadRecaptchaCallback=()=>{this.recaptchaReady(),window.grecaptcha?t(window.grecaptcha):n(new v("Recaptcha is not available"))},e().catch((()=>n(new v("Could not load Recaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(w("Recaptcha error:",e),e){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.");break;case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}static detectCaptchaChallengeIsShown(){return new Promise((function(e){const t=document.body;const n=new MutationObserver((function(t){t.forEach((t=>{if(t.addedNodes.length){const i=t.addedNodes[0];if(!i)return;if(i.querySelectorAll('iframe[src^="https://www.google.com/recaptcha"][src*="bframe"]').length){const t=i.firstChild;t&&(n.disconnect(),e(t))}}}))}));n.observe(t,{attributeOldValue:!1,attributes:!1,characterData:!1,characterDataOldValue:!1,childList:!0,subtree:!1})}))}renderWidget(e){return new Promise(((e,t)=>{var n,i,r;const o=document.createElement("div"),s=`${y}_${C()}`;o.id=s,null===(n=document.getElementById(y))||void 0===n||n.appendChild(o);const a=E.getGrecaptchaCallbackNames();let c=NaN;function l(){var e;null===(e=window.grecaptcha)||void 0===e||e.reset(),setTimeout((()=>{o.remove()}),1e3)}E.detectCaptchaChallengeIsShown().then((e=>{if(!e.parentElement)return;const n=new MutationObserver((function(){var i,r;"hidden"!==(null===(i=e.parentElement)||void 0===i?void 0:i.style.visibility)||(null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(c))||(n.disconnect(),t("closed"),l())}));n.observe(e.parentElement,{attributeFilter:["style"],attributes:!0})})),window[a.resolve]=()=>{var t;const n=null===(t=window.grecaptcha)||void 0===t?void 0:t.getResponse(c);e(null!=n?n:""),l()},window[a.error]=()=>{t("error"),l()},window[a.expired]=()=>{t("expired"),l()},c=null===(i=window.grecaptcha)||void 0===i?void 0:i.render(s,{callback:a.resolve,"error-callback":a.error,"expired-callback":a.expired,sitekey:this.sitekey,size:"invisible"});const d=null===(r=window.grecaptcha)||void 0===r?void 0:r.execute(c);if(!d)return t(new Error("cannot call method execute from grecaptcha")),void l();d.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),l()}))}))}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load recaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.grecaptcha){const e=new v("Recaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render Recaptcha widget"),this.onRenderCaptcha(this.provider);const t=yield this.renderWidget(e);return this.onSuccessChallenge(this.provider),t}catch(e){if(this.errorHandler(e),"string"!=typeof e){const t=new v("Could not execute captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if("expired"===e){const e=new v("Challenge or token expired");e.reason="expired",e.capture=!1,this.onWarnChallenge(this.provider,e)}if("error"===e){const e=new v("Error during captcha execution");e.reason="error",e.capture=!1,this.onErrorChallenge(this.provider,e)}}}}))}}E.RESOLVE_FUNC_NAME="grecaptcha_resolved",E.ERROR_FUNC_NAME="grecaptcha_error",E.EXPIRED_FUNC_NAME="grecaptcha_expired",E.DEBUG=!1;const k="smartcaptcha-container",_=(...e)=>{};class S{constructor({sitekey:e,notify:t,onRenderCaptcha:n,onSuccessChallenge:i,onWarnChallenge:r,onErrorChallenge:o,onBeforeInteractiveChallenge:s,onAfterInteractiveChallenge:a}){this.sitekey=null,this.container=null,this.provider="yandex_smart_captcha",this.sitekey=null!=e?e:null,this.notifyHandler=null!=t?t:_,this.onRenderCaptcha=null!=n?n:_,this.onSuccessChallenge=null!=i?i:_,this.onWarnChallenge=null!=r?r:_,this.onErrorChallenge=null!=o?o:_,this.onBeforeInteractiveChallenge=null!=s?s:_,this.onAfterInteractiveChallenge=null!=a?a:_,this.addDomElements()}smartCaptchaReady(){w("Smart captcha is ready",window.smartCaptcha,this)}addDomElements(){if(this.container||document.getElementById(k))return;document.body.insertAdjacentHTML("beforeend",`<div id="${k}"></div>`);const e=document.getElementById(k);e.style.display="none",this.container=e}static appendScript(e){return o(this,void 0,void 0,(function*(){if("string"!=typeof e||""===e)throw new TypeError("src script is not defined");const t=document.createElement("script");return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,n)=>{t.addEventListener("load",(()=>{e(!0)})),t.addEventListener("error",(()=>{n()}))}))}))}loadScript(){return o(this,void 0,void 0,(function*(){if(window.smartCaptcha)return Promise.resolve(window.smartCaptcha);const e=()=>o(this,void 0,void 0,(function*(){return yield S.appendScript("https://smartcaptcha.yandexcloud.net/captcha.js?render=onload&onload=onloadSmartCaptchaCallback")}));return new Promise(((t,n)=>{window.onloadSmartCaptchaCallback=()=>{this.smartCaptchaReady(),window.smartCaptcha?t(window.smartCaptcha):n(new v("SmartCaptcha is not available"))},e().catch((()=>n(new v("Could not load SmartCaptcha"))))}))}))}notify(...e){this.notifyHandler&&this.notifyHandler(...e)}errorHandler(e){switch(w("SmartCaptcha error:",e),e){case"closed":this.notify("Вы не завершили прохождение проверки. Попробуйте еще раз.");break;case"timeout":this.notify("Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.");break;default:this.notify("Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.")}}renderWidget(e){var t,n,i,r,o,s,a,c;const{promise:l,resolve:d,reject:h}=Promise.withResolvers(),u=document.createElement("div"),p=`${k}_${C()}`;u.id=p,null===(t=document.getElementById(k))||void 0===t||t.appendChild(u),this.onRenderCaptcha(this.provider);const f=window.smartCaptcha.render(p,{callback:e=>{d(e),function(){var e;null===(e=window.smartCaptcha)||void 0===e||e.destroy(f),setTimeout((()=>{u.remove()}),100)}()},hideShield:!0,invisible:!0,sitekey:this.sitekey});return null===(n=window.smartCaptcha)||void 0===n||n.subscribe(f,"challenge-visible",(()=>{this.onBeforeInteractiveChallenge(this.provider)})),null===(i=window.smartCaptcha)||void 0===i||i.subscribe(f,"challenge-hidden",(()=>{this.onAfterInteractiveChallenge(this.provider)})),null===(r=window.smartCaptcha)||void 0===r||r.subscribe(f,"token-expired",(()=>{const e=new v("Token expired");e.reason="expired",h(e)})),null===(o=window.smartCaptcha)||void 0===o||o.subscribe(f,"success",(()=>{this.onSuccessChallenge(this.provider)})),null===(s=window.smartCaptcha)||void 0===s||s.subscribe(f,"network-error",(()=>{const e=new v("Network error");e.reason="timeout",e.capture=!0,h(e)})),null===(a=window.smartCaptcha)||void 0===a||a.subscribe(f,"javascript-error",(e=>{const t=new v("Javascript error");t.reason="error",t.capture=!0,t.cause=e,h("javascript-error")})),null===(c=window.smartCaptcha)||void 0===c||c.execute(f),l}execute(e){return o(this,void 0,void 0,(function*(){if(this.sitekey){w("Load smartCaptcha script");try{yield this.loadScript()}catch(e){const t=e instanceof v?e:new v("Could not load captcha with error: "+e.toString());throw this.onErrorChallenge(this.provider,t),t}if(!window.smartCaptcha){const e=new v("SmartCaptcha is not available in window");throw this.onErrorChallenge(this.provider,e),e}try{w("Render SmartCaptcha widget");return yield this.renderWidget(e)}catch(e){if(e instanceof v)switch(this.errorHandler(e),e.reason){case"expired":this.notify("Прошло слишком много времени с момента начала проверки. Попробуйте еще раз."),this.onWarnChallenge(this.provider,e);break;case"timeout":this.notify("Вероятно у вас проблемы с подключением к сети. Попробуйте еще раз."),this.onErrorChallenge(this.provider,e);break;case"error":this.notify("Произошла непредвиденная ошибка. Мы уже делаем все возможное чтобы устранить её."),this.onErrorChallenge(this.provider,e)}const t=new v("Could not render captcha with error");t.capture=!0,t.cause=e,this.onErrorChallenge(this.provider,t)}}}))}}S.DEBUG=!1;class R{constructor(e){var t,n;switch(this.sitekey=null,this.provider=null,this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(n=e.provider)&&void 0!==n?n:null,e.provider){case"yandex_smart_captcha":this.captcha=new S(e);break;case"cloudflare_turnstile":this.captcha=new b(e);break;case"recaptcha":this.captcha=new E(e)}}isEnabled(){return"string"==typeof this.sitekey&&""!==this.sitekey}execute(e){return o(this,void 0,void 0,(function*(){if(!1===this.isEnabled())return;if(!this.provider)return;if(!this.captcha)return;const t=yield this.captcha.execute(e);return w("Receive answer from captcha provider"),{captcha_provider:this.provider,captcha_token:null!=t?t:""}}))}}class T{constructor(e){var t;this.channel=new n("shared-socket"),this.elector=void 0,this.client=void 0,this.connected=!1,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,t,n;if(this.connected||void 0!==this.client)return this.client;this.logger.debug("Try to connect with Centrifuge client");const i=null!==(e=this.config.transport)&&void 0!==e?e:[],o=(()=>{const e=i.find((e=>"http_stream"===e.transport));if(e)return`${new URL(e.endpoint).origin}/emulation`})();try{return this.client=new r(null!==(t=this.config.transport)&&void 0!==t?t:[],{debug:null!==(n=this.config.debug)&&void 0!==n&&n,emulationEndpoint:o,getToken:()=>this.config.refreshToken(),token:this.config.token}),this.logger.debug("Create Centrifuge instance",this.client),this.client.on("disconnected",(e=>{this.connected=!1,this.logger.debug("Centrifuge connection is closed and will not be reconnected",e)})),this.client.on("connected",(e=>{this.connected=!0,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=!1)}subscriptionExists(e){if(!this.client)return!1;const t=this.client.subscriptions();return Boolean(t[e])}join(e,t){var n;const i=this.createClient();if(!i)return;const r=null===(n=this.client)||void 0===n?void 0:n.newSubscription(e);this.logger.debug("Create centrifuge subscription",r),r&&(r.on("publication",(({data:e})=>{var n;this.logger.debug("Get message from ws: ",e),t(e),null===(n=this.channel)||void 0===n||n.postMessage(e)})),r.subscribe(),i.connect())}subscribe(e,t){return o(this,void 0,void 0,(function*(){this.subscriptionExists(e)?this.logger.debug("Subscription to the channel is exists. Ignore subscribe."):(this.logger.debug("Create broadcast channel with name",e),this.channel=new n(e),this.elector=i(this.channel),this.logger.debug("Wait leader",this.elector),this.elector.onduplicate=()=>{this.disconnect(),this.subscribe(e,t)},this.elector.awaitLeadership().then((()=>{this.logger.debug("Current tab is leader",this.elector),this.join(e,t)})),this.channel.addEventListener("message",(e=>{this.logger.debug("Get message from broadcast: ",e),t(e)})))}))}unsubscribe(e){var t;const n=null===(t=this.client)||void 0===t?void 0:t.subscriptions()[e];n&&n.unsubscribe()}}export{u as ApiService,v as CaptchaError,R as CaptchaService,d as RequestPlugin,h as ResponseSuccessPlugin,T as SocketService};