@foxford/services 1.2.2 → 1.2.6

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.
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var t=require('../error.js');var r=require('../log.js');var o=require('./constants.js');var n=require('./style.js');var l=require('./template.js');var i=function(){};class CloudflareTurnstile{constructor(e){var{sitekey:t,locale:r,notify:o,onFatalError:n,onPotentiallyAutomatedError:l,onRenderCaptcha:a,onSuccessChallenge:s,onFailChallenge:c}=e;this.sitekey=null,this.locale='ru',this.provider='cloudflare_turnstile',this.container=null,this.notifyHandler=i,this.onFatalError=i,this.onPotentiallyAutomatedError=i,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onFailChallenge=void 0,this.notifyHandler=null!=o?o:i,this.sitekey=null!=t?t:null,this.onFatalError=null!=n?n:i,this.onPotentiallyAutomatedError=null!=l?l:i,this.onRenderCaptcha=null!=a?a:i,this.onSuccessChallenge=null!=s?s:i,this.onFailChallenge=null!=c?c:i,r&&(this.locale=r),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(o.CONTAINER_NODE_ID)||(document.body.insertAdjacentHTML('beforeend',l),document.body.insertAdjacentHTML('beforeend',"<style>".concat(n,"</style>")),this.container=document.getElementById(o.CONTAINER_NODE_ID))}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 o=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 t.CaptchaError('Cloudflare Turnstile is not available'))},o().catch((()=>n(new t.CaptchaError('Could not load Cloudflare Turnstile'))))}))}))()}turnstileReady(){var e,t;r.log('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,l)=>{var i;var a='';a=null===(i=window.turnstile)||void 0===i?void 0:i.render("#".concat(o.RENDER_NODE_ID),{action:n.normalizeLocation(null==t?void 0:t.location),'after-interactive-callback':()=>{r.log("after-interactive-callback")},'before-interactive-callback':()=>{r.log("before-interactive-callback"),n.show()},callback:t=>{var o;r.log("Challenge Success"),n.hide(),e(t),null===(o=window.turnstile)||void 0===o||o.remove(a)},'error-callback':e=>{var t;CloudflareTurnstile.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))?(l(e),null===(t=window.turnstile)||void 0===t||t.remove(a)):n.onFailChallenge(n.provider,'error',{code:e})},'expired-callback':()=>{var e;n.hide(),l('expired'),null===(e=window.turnstile)||void 0===e||e.remove(a)},language:n.locale,sitekey:n.sitekey,theme:'light','timeout-callback':()=>{var e;n.hide(),l('timeout'),null===(e=window.turnstile)||void 0===e||e.remove(a)},'unsupported-callback':()=>{var e;n.onFailChallenge(n.provider,'error'),l('110500'),null===(e=window.turnstile)||void 0===e||e.remove(a)}})}))}))()}errorHandler(e){r.log("Captcha error with code:",e);var t=[...CloudflareTurnstile.NO_RETRY_ERROR_CODES];if('string'==typeof e){var o=e;switch(true){case o.startsWith('110500'):t=t.filter((e=>!e.startsWith('110500'))),this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.');break;case o.startsWith('110600'):t=t.filter((e=>!e.startsWith('110600'))),this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case o.startsWith('110510'):t=t.filter((e=>!e.startsWith('110510'))),this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку');break;case o.startsWith('200010'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.");break;case o.startsWith('200100'):t=t.filter((e=>!e.startsWith('200100'))),this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.');break;case o.startsWith('300'):case o.startsWith('600'):t=t.filter((e=>!e.startsWith('300')||!e.startsWith('600'))),this.notify('Потвердите еще раз что вы человек')}t.some((e=>o.startsWith(e)))&&this.notify("Что-то пошло не так, код ошибки — ".concat(o,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время."))}else this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}execute(o){var n=this;return e((function*(){if(n.sitekey){if(r.log('Load cloudflare script'),yield n.loadScript(),!window.turnstile)throw new t.CaptchaError('Cloudflare Turnstile is not available in window');try{r.log('Render turnstile widget'),n.onRenderCaptcha(n.provider);var e=yield n.renderWidget(o);return n.onSuccessChallenge(n.provider),e}catch(e){if(n.errorHandler(e),e instanceof Error)throw new t.CaptchaError('Could not execute captcha with error: '+e.toString());throw'string'==typeof e&&(['timeout','expired'].includes(e)?n.onFailChallenge(n.provider,e):n.onFailChallenge(n.provider,'fail',{code:e}),['crashed','undefined_error'].includes(e)||['105','110100','110110','110200'].some((t=>e.startsWith(t)))?null==n||n.onFatalError(e):['300','600'].some((t=>e.startsWith(t)))&&(null==n||n.onPotentiallyAutomatedError(e))),new t.CaptchaError(e)}}}))()}}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('../error.js');var t=require('../log.js');var o=require('./constants.js');var n=require('./style.js');var l=require('./template.js');var i=function(){};class CloudflareTurnstile{constructor(e){var{sitekey:r,locale:t,notify:o,onRenderCaptcha:n,onSuccessChallenge:l,onErrorChallenge:a,onWarnChallenge:s}=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.notifyHandler=null!=o?o:i,this.sitekey=null!=r?r:null,this.onRenderCaptcha=null!=n?n:i,this.onSuccessChallenge=null!=l?l:i,this.onErrorChallenge=null!=a?a:i,this.onWarnChallenge=null!=s?s:i,t&&(this.locale=t),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(o.CONTAINER_NODE_ID)||(document.body.insertAdjacentHTML('beforeend',l),document.body.insertAdjacentHTML('beforeend',"<style>".concat(n,"</style>")),this.container=document.getElementById(o.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 o=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 r.CaptchaError('Cloudflare Turnstile is not available'))},o().catch((()=>n(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 n=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(o.RENDER_NODE_ID),{action:n.normalizeLocation(null==r?void 0:r.location),'after-interactive-callback':()=>{t.log("after-interactive-callback")},'before-interactive-callback':()=>{t.log("before-interactive-callback"),n.show()},callback:r=>{t.log("Challenge Success"),n.hide(),e(r),s()},'error-callback':e=>{l(e),s()},'expired-callback':()=>{n.hide(),l('expired'),s()},language:n.locale,sitekey:n.sitekey,theme:'light','timeout-callback':()=>{n.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 o=e;switch(true){case o.startsWith('110500'):r=r.filter((e=>!e.startsWith('110500'))),this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.');break;case o.startsWith('110600'):r=r.filter((e=>!e.startsWith('110600'))),this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case o.startsWith('110510'):r=r.filter((e=>!e.startsWith('110510'))),this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку');break;case o.startsWith('200010'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.");break;case o.startsWith('200100'):r=r.filter((e=>!e.startsWith('200100'))),this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.');break;case o.startsWith('300'):case o.startsWith('600'):r=r.filter((e=>!e.startsWith('300')||!e.startsWith('600'))),this.notify('Потвердите еще раз что вы человек')}r.some((e=>o.startsWith(e)))&&this.notify("Что-то пошло не так, код ошибки — ".concat(o,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время."))}else this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}execute(o){var n=this;return e((function*(){if(n.sitekey){t.log('Load cloudflare script');try{yield n.loadScript()}catch(t){var e=t instanceof r.CaptchaError?t:new r.CaptchaError('Could not load captcha with error: '+t.toString());throw n.onErrorChallenge(n.provider,e),e}if(!window.turnstile){var l=new r.CaptchaError('Cloudflare Turnstile is not available in window');throw n.onErrorChallenge(n.provider,l),l}try{t.log('Render turnstile widget'),n.onRenderCaptcha(n.provider);var i=yield n.renderWidget(o);return n.onSuccessChallenge(n.provider),i}catch(e){if(n.errorHandler(e),'string'!=typeof e){var a=new r.CaptchaError('Could not execute captcha with error: '+e.toString());throw n.onErrorChallenge(n.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,n.onErrorChallenge(n.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,n.onErrorChallenge(n.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,n.onWarnChallenge(n.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 o,RENDER_NODE_ID as n}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:o,onFatalError:n,onPotentiallyAutomatedError:i,onRenderCaptcha:l,onSuccessChallenge:s,onFailChallenge:d}=e;this.sitekey=null,this.locale='ru',this.provider='cloudflare_turnstile',this.container=null,this.notifyHandler=a,this.onFatalError=a,this.onPotentiallyAutomatedError=a,this.onRenderCaptcha=void 0,this.onSuccessChallenge=void 0,this.onFailChallenge=void 0,this.notifyHandler=null!=o?o:a,this.sitekey=null!=t?t:null,this.onFatalError=null!=n?n:a,this.onPotentiallyAutomatedError=null!=i?i:a,this.onRenderCaptcha=null!=l?l:a,this.onSuccessChallenge=null!=s?s:a,this.onFailChallenge=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(o)||(document.body.insertAdjacentHTML('beforeend',l),document.body.insertAdjacentHTML('beforeend',"<style>".concat(i,"</style>")),this.container=document.getElementById(o))}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 o=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 t('Cloudflare Turnstile is not available'))},o().catch((()=>n(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 o=this;return e((function*(){return new Promise(((e,i)=>{var l;var a='';a=null===(l=window.turnstile)||void 0===l?void 0:l.render("#".concat(n),{action:o.normalizeLocation(null==t?void 0:t.location),'after-interactive-callback':()=>{r("after-interactive-callback")},'before-interactive-callback':()=>{r("before-interactive-callback"),o.show()},callback:t=>{var n;r("Challenge Success"),o.hide(),e(t),null===(n=window.turnstile)||void 0===n||n.remove(a)},'error-callback':e=>{var t;CloudflareTurnstile.NO_RETRY_ERROR_CODES.some((t=>e.startsWith(t)))?(i(e),null===(t=window.turnstile)||void 0===t||t.remove(a)):o.onFailChallenge(o.provider,'error',{code:e})},'expired-callback':()=>{var e;o.hide(),i('expired'),null===(e=window.turnstile)||void 0===e||e.remove(a)},language:o.locale,sitekey:o.sitekey,theme:'light','timeout-callback':()=>{var e;o.hide(),i('timeout'),null===(e=window.turnstile)||void 0===e||e.remove(a)},'unsupported-callback':()=>{var e;o.onFailChallenge(o.provider,'error'),i('110500'),null===(e=window.turnstile)||void 0===e||e.remove(a)}})}))}))()}errorHandler(e){r("Captcha error with code:",e);var t=[...CloudflareTurnstile.NO_RETRY_ERROR_CODES];if('string'==typeof e){var o=e;switch(true){case o.startsWith('110500'):t=t.filter((e=>!e.startsWith('110500'))),this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.');break;case o.startsWith('110600'):t=t.filter((e=>!e.startsWith('110600'))),this.notify('Прошло слишком много времени с момента начала проверки. Попробуйте еще раз.');break;case o.startsWith('110510'):t=t.filter((e=>!e.startsWith('110510'))),this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку');break;case o.startsWith('200010'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку.");break;case o.startsWith('200100'):t=t.filter((e=>!e.startsWith('200100'))),this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.');break;case o.startsWith('300'):case o.startsWith('600'):t=t.filter((e=>!e.startsWith('300')||!e.startsWith('600'))),this.notify('Потвердите еще раз что вы человек')}t.some((e=>o.startsWith(e)))&&this.notify("Что-то пошло не так, код ошибки — ".concat(o,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время."))}else this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}execute(o){var n=this;return e((function*(){if(n.sitekey){if(r('Load cloudflare script'),yield n.loadScript(),!window.turnstile)throw new t('Cloudflare Turnstile is not available in window');try{r('Render turnstile widget'),n.onRenderCaptcha(n.provider);var e=yield n.renderWidget(o);return n.onSuccessChallenge(n.provider),e}catch(e){if(n.errorHandler(e),e instanceof Error)throw new t('Could not execute captcha with error: '+e.toString());throw'string'==typeof e&&(['timeout','expired'].includes(e)?n.onFailChallenge(n.provider,e):n.onFailChallenge(n.provider,'fail',{code:e}),['crashed','undefined_error'].includes(e)||['105','110100','110110','110200'].some((t=>e.startsWith(t)))?null==n||n.onFatalError(e):['300','600'].some((t=>e.startsWith(t)))&&(null==n||n.onPotentiallyAutomatedError(e))),new t(e)}}}))()}}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{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}=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.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,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")},'before-interactive-callback':()=>{r("before-interactive-callback"),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};
package/captcha/error.js CHANGED
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});class CaptchaError extends Error{constructor(r,t){super(r),this.payload={},this.name='CaptchaError',this.message=r,t&&(this.payload=t)}}exports.CaptchaError=CaptchaError;
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});class CaptchaError extends Error{constructor(r){super(r),this.reason=void 0,this.code=void 0,this.capture=true,this.name='CaptchaError',this.message=r}}exports.CaptchaError=CaptchaError;
package/captcha/error.mjs CHANGED
@@ -1 +1 @@
1
- class CaptchaError extends Error{constructor(r,a){super(r),this.payload={},this.name='CaptchaError',this.message=r,a&&(this.payload=a)}}export{CaptchaError};
1
+ class CaptchaError extends Error{constructor(r){super(r),this.reason=void 0,this.code=void 0,this.capture=true,this.name='CaptchaError',this.message=r}}export{CaptchaError};
@@ -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,onFatalError:o,onRenderCaptcha:c,onSuccessChallenge:i,onFailChallenge:l}=e;this.sitekey=null,this.locale='ru',this.container=null,this.provider='recaptcha',this.notifyHandler=n,this.onFatalError=n,this.onRenderCaptcha=n,this.onSuccessChallenge=n,this.onFailChallenge=n,this.sitekey=null!=r?r:null,this.notifyHandler=null!=t?t:n,this.onFatalError=null!=o?o:n,this.onRenderCaptcha=null!=c?c:n,this.onSuccessChallenge=null!=i?i:n,this.onFailChallenge=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'timeout':this.notify('Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.');break;default:this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}}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;window[d.resolve]=()=>{var r;var a=null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(s);e(null!=a?a:''),i.remove()},window[d.error]=()=>{a('error'),i.remove()},window[d.expired]=()=>{a('expired'),i.remove()},this.onRenderCaptcha(this.provider),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 h=null===(c=window.grecaptcha)||void 0===c?void 0:c.execute(s);if(!h)return a(new Error('cannot call method execute from grecaptcha')),void i.remove();h.catch((e=>{a(e instanceof Error?e:new Error(e.toString())),i.remove()}))}))}execute(r){var o=this;return e((function*(){if(o.sitekey){if(t.log('Load recaptcha script'),yield o.loadScript(),!window.grecaptcha)throw new a.CaptchaError('Recaptcha is not available in window');try{t.log('Render Recaptcha widget'),o.onRenderCaptcha(o.provider);var e=yield o.renderWidget(r);return o.onSuccessChallenge(o.provider),e}catch(e){if(o.errorHandler(e),e instanceof Error)throw new a.CaptchaError('Could not execute captcha with error: '+e.toString());throw'string'==typeof e&&('expired'===e&&o.onFailChallenge(o.provider,'expired'),'error'===e&&o.onFailChallenge(o.provider,'fail')),new a.CaptchaError(e)}}}))()}}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('../../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 +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,onFatalError:o,onRenderCaptcha:i,onSuccessChallenge:c,onFailChallenge:l}=e;this.sitekey=null,this.locale='ru',this.container=null,this.provider='recaptcha',this.notifyHandler=n,this.onFatalError=n,this.onRenderCaptcha=n,this.onSuccessChallenge=n,this.onFailChallenge=n,this.sitekey=null!=r?r:null,this.notifyHandler=null!=a?a:n,this.onFatalError=null!=o?o:n,this.onRenderCaptcha=null!=i?i:n,this.onSuccessChallenge=null!=c?c:n,this.onFailChallenge=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'timeout':this.notify('Возможно произшла ошибка с сетевым подключением. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.');break;default:this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.')}}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;window[d.resolve]=()=>{var r;var t=null===(r=window.grecaptcha)||void 0===r?void 0:r.getResponse(s);e(null!=t?t:''),c.remove()},window[d.error]=()=>{t('error'),c.remove()},window[d.expired]=()=>{t('expired'),c.remove()},this.onRenderCaptcha(this.provider),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 h=null===(i=window.grecaptcha)||void 0===i?void 0:i.execute(s);if(!h)return t(new Error('cannot call method execute from grecaptcha')),void c.remove();h.catch((e=>{t(e instanceof Error?e:new Error(e.toString())),c.remove()}))}))}execute(r){var o=this;return e((function*(){if(o.sitekey){if(a('Load recaptcha script'),yield o.loadScript(),!window.grecaptcha)throw new t('Recaptcha is not available in window');try{a('Render Recaptcha widget'),o.onRenderCaptcha(o.provider);var e=yield o.renderWidget(r);return o.onSuccessChallenge(o.provider),e}catch(e){if(o.errorHandler(e),e instanceof Error)throw new t('Could not execute captcha with error: '+e.toString());throw'string'==typeof e&&('expired'===e&&o.onFailChallenge(o.provider,'expired'),'error'===e&&o.onFailChallenge(o.provider,'fail')),new t(e)}}}))()}}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{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};
package/captcha/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var r=require('./cloudflare/index.js');var t=require('./error.js');var a=require('./google/index.js');var i=require('./log.js');exports.CaptchaError=t.CaptchaError,exports.CaptchaService=class CaptchaService{constructor(e){var t,i;switch(this.sitekey=null,this.provider=null,this.locale='en',this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(i=e.provider)&&void 0!==i?i:null,e.locale&&(this.locale=e.locale),e.provider){case'cloudflare_turnstile':this.captcha=new r.CloudflareTurnstile(e);break;case'recaptcha':this.captcha=new a.GoogleCaptcha(e)}}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}execute(r){var a=this;return e((function*(){if(false!==a.isEnabled()&&a.provider&&a.captcha){var e=yield a.captcha.execute(r);if(i.log('Receive answer from captcha provider'),!e)throw new t.CaptchaError("Could't get captcha token from provider "+a.provider);return{captcha_provider:a.provider,captcha_token:e}}}))()}};
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var r=require('./cloudflare/index.js');var t=require('./google/index.js');var a=require('./log.js');exports.CaptchaService=class CaptchaService{constructor(e){var a,i;switch(this.sitekey=null,this.provider=null,this.locale='en',this.captcha=null,this.sitekey=null!==(a=e.sitekey)&&void 0!==a?a:null,this.provider=null!==(i=e.provider)&&void 0!==i?i:null,e.locale&&(this.locale=e.locale),e.provider){case'cloudflare_turnstile':this.captcha=new r.CloudflareTurnstile(e);break;case'recaptcha':this.captcha=new t.GoogleCaptcha(e)}}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}execute(r){var t=this;return e((function*(){if(false!==t.isEnabled()&&t.provider&&t.captcha){var e=yield t.captcha.execute(r);return a.log('Receive answer from captcha provider'),{captcha_provider:t.provider,captcha_token:null!=e?e:''}}}))()}};
package/captcha/index.mjs CHANGED
@@ -1 +1 @@
1
- import e from'./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{CloudflareTurnstile as r}from'./cloudflare/index.mjs';import{CaptchaError as t}from'./error.mjs';export{CaptchaError}from'./error.mjs';import{GoogleCaptcha as o}from'./google/index.mjs';import{log as i}from'./log.mjs';class CaptchaService{constructor(e){var t,i;switch(this.sitekey=null,this.provider=null,this.locale='en',this.captcha=null,this.sitekey=null!==(t=e.sitekey)&&void 0!==t?t:null,this.provider=null!==(i=e.provider)&&void 0!==i?i:null,e.locale&&(this.locale=e.locale),e.provider){case'cloudflare_turnstile':this.captcha=new r(e);break;case'recaptcha':this.captcha=new o(e)}}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}execute(r){var o=this;return e((function*(){if(false!==o.isEnabled()&&o.provider&&o.captcha){var e=yield o.captcha.execute(r);if(i('Receive answer from captcha provider'),!e)throw new t("Could't get captcha token from provider "+o.provider);return{captcha_provider:o.provider,captcha_token:e}}}))()}}export{CaptchaService};
1
+ import e from'./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{CloudflareTurnstile as r}from'./cloudflare/index.mjs';import{GoogleCaptcha as t}from'./google/index.mjs';import{log as i}from'./log.mjs';class CaptchaService{constructor(e){var i,a;switch(this.sitekey=null,this.provider=null,this.locale='en',this.captcha=null,this.sitekey=null!==(i=e.sitekey)&&void 0!==i?i:null,this.provider=null!==(a=e.provider)&&void 0!==a?a:null,e.locale&&(this.locale=e.locale),e.provider){case'cloudflare_turnstile':this.captcha=new r(e);break;case'recaptcha':this.captcha=new t(e)}}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}execute(r){var t=this;return e((function*(){if(false!==t.isEnabled()&&t.provider&&t.captcha){var e=yield t.captcha.execute(r);return i('Receive answer from captcha provider'),{captcha_provider:t.provider,captcha_token:null!=e?e:''}}}))()}}export{CaptchaService};
package/index.d.ts CHANGED
@@ -175,8 +175,10 @@ export declare abstract class ResponseSuccessPlugin implements ResponseSuccessPl
175
175
  }
176
176
  declare const apiServiceInstance: ApiServiceInterface;
177
177
  export declare class CaptchaError extends Error {
178
- payload: {};
179
- constructor(message: string, payload?: object);
178
+ reason?: "error" | "timeout" | "expired";
179
+ code?: string;
180
+ capture?: boolean;
181
+ constructor(message: string);
180
182
  }
181
183
  type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile";
182
184
  type CaptchaAnswer = {
@@ -189,11 +191,10 @@ export type CaptchaConfig = {
189
191
  provider?: CaptchaProviderName;
190
192
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
191
193
  notify?: (...args: any[]) => void;
192
- onFatalError?: (code: string) => void;
193
- onPotentiallyAutomatedError?: (code: string) => void;
194
194
  onRenderCaptcha?: (provider: CaptchaProviderName) => void;
195
195
  onSuccessChallenge?: (provider: CaptchaProviderName) => void;
196
- onFailChallenge?: (provider: CaptchaProviderName, reason: "fail" | "error" | "timeout" | "expired") => void;
196
+ onErrorChallenge?: (provider: CaptchaProviderName, error: CaptchaError) => void;
197
+ onWarnChallenge?: (provider: CaptchaProviderName, error: CaptchaError) => void;
197
198
  };
198
199
  type ExecuteMeta = Record<string, unknown>;
199
200
  export interface Captcha {
package/index.js.flow CHANGED
@@ -243,8 +243,10 @@ declare export class ResponseSuccessPlugin
243
243
  }
244
244
  declare var apiServiceInstance: ApiServiceInterface;
245
245
  declare export class CaptchaError mixins Error {
246
- payload: {||};
247
- constructor(message: string, payload?: { [key: string]: any }): this;
246
+ reason?: "error" | "timeout" | "expired";
247
+ code?: string;
248
+ capture?: boolean;
249
+ constructor(message: string): this;
248
250
  }
249
251
  declare type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile";
250
252
  declare type CaptchaAnswer = {|
@@ -256,13 +258,15 @@ export type CaptchaConfig = {|
256
258
  sitekey?: string,
257
259
  provider?: CaptchaProviderName,
258
260
  notify?: (...args: any[]) => void,
259
- onFatalError?: (code: string) => void,
260
- onPotentiallyAutomatedError?: (code: string) => void,
261
261
  onRenderCaptcha?: (provider: CaptchaProviderName) => void,
262
262
  onSuccessChallenge?: (provider: CaptchaProviderName) => void,
263
- onFailChallenge?: (
263
+ onErrorChallenge?: (
264
264
  provider: CaptchaProviderName,
265
- reason: "fail" | "error" | "timeout" | "expired"
265
+ error: CaptchaError
266
+ ) => void,
267
+ onWarnChallenge?: (
268
+ provider: CaptchaProviderName,
269
+ error: CaptchaError
266
270
  ) => void,
267
271
  |};
268
272
  declare type ExecuteMeta = { [key: string]: mixed };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foxford/services",
3
- "version": "1.2.2",
3
+ "version": "1.2.6",
4
4
  "description": "Foxford services",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",