@foxford/services 1.1.0 → 1.2.0-beta-6bf5bf4a-20240109

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,10 @@
3
3
  Библиотека фронтовых сервисов, которые помогут реализовать тот или иной функционал на уровне приложения.
4
4
  Здесь будут появляться сервисы фокса, которые будут "отвязаны" от других сервисов и функций, не принадлежащих им.
5
5
 
6
+ ### Captcha Service
6
7
 
8
+ Сервис для работы с капчей.
9
+ В зависимости от данных с бэке используется или Google-капча, или Cloudflare Turnstile
7
10
 
8
11
  ## Recaptcha Service
9
12
 
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true}),exports.CONTAINER_NODE_ID='turnstile-container',exports.RENDER_NODE_ID='turnstile-widget';
@@ -0,0 +1 @@
1
+ var t='turnstile-container';var r='turnstile-widget';export{t as CONTAINER_NODE_ID,r as RENDER_NODE_ID};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var t=require('../error.js');var r=require('../log.js');var i=require('./constants.js');var n=require('./style.js');var s=require('./template.js');var a=function(){};class CloudflareTurnstile{constructor(e){var{sitekey:t,locale:r,notify:i,onFatalError:n}=e;this.sitekey=null,this.locale='ru',this.container=null,this.notifyHandler=a,this.onFatalError=a,this.transitionSettings={stateClosed:'is-closed',stateClosing:'is-closing',stateOpened:'is-opened',stateOpening:'is-opening',transition:true},this.notifyHandler=null!=i?i:a,this.sitekey=null!=t?t:null,this.onFatalError=null!=n?n:a,r&&(this.locale=r),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(i.CONTAINER_NODE_ID)||(document.body.insertAdjacentHTML('beforeend',s),document.body.insertAdjacentHTML('beforeend',"<style>".concat(n,"</style>")),this.container=document.getElementById(i.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')}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')}loadScript(){var r=this;return e((function*(){if(window.turnstile)return Promise.resolve(window.turnstile);var i=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'))},i().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()}renderWidget(){var t=this;return e((function*(){return new Promise(((e,n)=>{var s;null===(s=window.turnstile)||void 0===s||s.render("#".concat(i.RENDER_NODE_ID),{'after-interactive-callback':()=>{r.log("after-interactive-callback")},'before-interactive-callback':()=>{r.log("before-interactive-callback"),t.show()},callback:i=>{r.log("Challenge Success"),e(i),t.hide()},'error-callback':e=>{t.errorHandler(e)},'expired-callback':()=>{t.hide(),n(new Error('Captcha is expired'))},language:t.locale,sitekey:t.sitekey,theme:'light','timeout-callback':()=>{t.hide(),n(new Error('Captcha is timeout'))},'unsupported-callback':function(){n('110500')}})}))}))()}errorHandler(e){switch(r.log("Captcha error with code:",e),true){case e.startsWith('110500'):this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.'),Promise.reject();break;case e.startsWith('110600'):this.notify('Прошло слишком много времени с момента начала проверки. Обновите страницу и попробуйте ещё раз.');break;case e.startsWith('110510'):this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку'),Promise.reject();break;case e.startsWith('105'):case e.startsWith('106'):case e.startsWith('110100'):case e.startsWith('110110'):case e.startsWith('110200'):case e.startsWith('110420'):case e.startsWith('110430'):case e.startsWith('110500'):this.notify("Что-то пошло не так, код ошибки — ".concat(e,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.")),null==this||this.onFatalError(e),Promise.reject();break;case e.startsWith('200100'):this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.'),Promise.reject();break;case e.startsWith('120'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку."),Promise.reject();break;case e.startsWith('100'):this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.'),Promise.reject()}}execute(){var i=this;return e((function*(){if(i.sitekey){if(r.log('Load cloudflare script'),yield i.loadScript(),!window.turnstile)throw new t.CaptchaError('Cloudflare Turnstile is not available in window');try{return r.log('Render turnstile widget'),yield i.renderWidget()}catch(e){e instanceof Error&&console.warn(e),'string'==typeof e&&i.errorHandler(e)}}}))()}}CloudflareTurnstile.DEBUG=true,exports.CloudflareTurnstile=CloudflareTurnstile;
@@ -0,0 +1 @@
1
+ import t from'./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{CaptchaError as e}from'../error.mjs';import{log as r}from'../log.mjs';import{CONTAINER_NODE_ID as i,RENDER_NODE_ID as n}from'./constants.mjs';import s from'./style.mjs';import o from'./template.mjs';var a=function(){};class CloudflareTurnstile{constructor(t){var{sitekey:e,locale:r,notify:i,onFatalError:n}=t;this.sitekey=null,this.locale='ru',this.container=null,this.notifyHandler=a,this.onFatalError=a,this.transitionSettings={stateClosed:'is-closed',stateClosing:'is-closing',stateOpened:'is-opened',stateOpening:'is-opening',transition:true},this.notifyHandler=null!=i?i:a,this.sitekey=null!=e?e:null,this.onFatalError=null!=n?n:a,r&&(this.locale=r),this.addDomElements(),CloudflareTurnstile.DEBUG&&(window.cf=this)}notify(){this.notifyHandler&&this.notifyHandler(...arguments)}addDomElements(){this.container||document.getElementById(i)||(document.body.insertAdjacentHTML('beforeend',o),document.body.insertAdjacentHTML('beforeend',"<style>".concat(s,"</style>")),this.container=document.getElementById(i))}appendScript(e){return t((function*(){if('string'!=typeof e||''===e)throw new TypeError('src script is not defined');var t=document.createElement('script');return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,r)=>{t.addEventListener('load',(()=>{e(true)})),t.addEventListener('error',(()=>{r()}))}))}))()}show(){var t;null===(t=this.container)||void 0===t||t.classList.add('fox-cf-turnstile--showing')}hide(){var t,e;null===(t=this.container)||void 0===t||t.classList.remove('fox-cf-turnstile--show'),null===(e=this.container)||void 0===e||e.classList.remove('fox-cf-turnstile--showing')}loadScript(){var r=this;return t((function*(){if(window.turnstile)return Promise.resolve(window.turnstile);var i=function(){var e=t((function*(){return yield r.appendScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onloadTurnstileCallback")}));return function(){return e.apply(this,arguments)}}();return new Promise(((t,n)=>{window.onloadTurnstileCallback=()=>{r.turnstileReady(),window.turnstile?t(window.turnstile):n(new e('Cloudflare Turnstile is not available'))},i().catch((()=>n(new e('Could not load Cloudflare Turnstile'))))}))}))()}turnstileReady(){var t,e;r('Cloudflare Turnstile is ready',window.turnstile),null===(t=this.container)||void 0===t||null===(e=t.querySelector('.fox-cf-turnstile__loader'))||void 0===e||e.remove()}renderWidget(){var e=this;return t((function*(){return new Promise(((t,i)=>{var s;null===(s=window.turnstile)||void 0===s||s.render("#".concat(n),{'after-interactive-callback':()=>{r("after-interactive-callback")},'before-interactive-callback':()=>{r("before-interactive-callback"),e.show()},callback:i=>{r("Challenge Success"),t(i),e.hide()},'error-callback':t=>{e.errorHandler(t)},'expired-callback':()=>{e.hide(),i(new Error('Captcha is expired'))},language:e.locale,sitekey:e.sitekey,theme:'light','timeout-callback':()=>{e.hide(),i(new Error('Captcha is timeout'))},'unsupported-callback':function(){i('110500')}})}))}))()}errorHandler(t){switch(r("Captcha error with code:",t),true){case t.startsWith('110500'):this.notify('Ваш браузер устарел. Попробуйте ещё раз, используя другой браузер или устройство.'),Promise.reject();break;case t.startsWith('110600'):this.notify('Прошло слишком много времени с момента начала проверки. Обновите страницу и попробуйте ещё раз.');break;case t.startsWith('110510'):this.notify('Что-то пошло не так — возможно, вы используете технологию подмены User agent. Попробуйте ещё раз или обратитесь в поддержку'),Promise.reject();break;case t.startsWith('105'):case t.startsWith('106'):case t.startsWith('110100'):case t.startsWith('110110'):case t.startsWith('110200'):case t.startsWith('110420'):case t.startsWith('110430'):case t.startsWith('110500'):this.notify("Что-то пошло не так, код ошибки — ".concat(t,". Мы уже знаем о проблеме и скоро всё поправим. Попробуйте ещё раз через некоторое время.")),null==this||this.onFatalError(t),Promise.reject();break;case t.startsWith('200100'):this.notify('Кажется, часы на вашем компьютере показывают неправильное время. Настройте часы и попробуйте ещё раз.'),Promise.reject();break;case t.startsWith('120'):this.notify("Что-то пошло не так. Попробуйте <a href=\"https://yandex.ru/support/common/browsers-settings/cache.html\" target=\"_blank\" rel=\"nofollow noopener\">очистить кеш браузера</a>. Если не помогает, обратитесь в поддержку."),Promise.reject();break;case t.startsWith('100'):this.notify('Что-то пошло не так. Попробуйте ещё раз. Если не помогает, обратитесь в поддержку.'),Promise.reject()}}execute(){var i=this;return t((function*(){if(i.sitekey){if(r('Load cloudflare script'),yield i.loadScript(),!window.turnstile)throw new e('Cloudflare Turnstile is not available in window');try{return r('Render turnstile widget'),yield i.renderWidget()}catch(t){t instanceof Error&&console.warn(t),'string'==typeof t&&i.errorHandler(t)}}}))()}}CloudflareTurnstile.DEBUG=true;export{CloudflareTurnstile};
@@ -0,0 +1 @@
1
+ 'use strict';module.exports="\n.fox-cf-turnstile {\n position: absolute;\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--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";
@@ -0,0 +1 @@
1
+ var n="\n.fox-cf-turnstile {\n position: absolute;\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--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";export{n as default};
@@ -0,0 +1 @@
1
+ 'use strict';var n=require('./constants.js');var s="\n<div id=\"".concat(n.CONTAINER_NODE_ID,"\" 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=\"").concat(n.RENDER_NODE_ID,"\">\n <div class=\"fox-cf-turnstile__loader\"></div>\n </div>\n </div>\n</div>\n");module.exports=s;
@@ -0,0 +1 @@
1
+ import{CONTAINER_NODE_ID as n,RENDER_NODE_ID as t}from'./constants.mjs';var s="\n<div id=\"".concat(n,"\" 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=\"").concat(t,"\">\n <div class=\"fox-cf-turnstile__loader\"></div>\n </div>\n </div>\n</div>\n");export{s as default};
@@ -0,0 +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;
@@ -0,0 +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};
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../../dependencies/@babel/runtime/helpers/esm/objectSpread2.js');var a=require('./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var t=require('../../utils/uuid.js');var r=require('../error.js');var c=require('../log.js');class GoogleCaptcha{constructor(e){var{sitekey:a,locale:t}=e;this.sitekey=null,this.locale='en',this.widgets=[],this.captcha=void 0,this.sitekey=null!=a?a:null,t&&(this.locale=t)}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}__recaptchaReady(){this.captcha=window.grecaptcha}__destroyWidgetByUuid(e){if('string'==typeof e&&this.widgets.find((a=>a.uuid===e))){var a=this.__getGrecaptchaCallbackNames(e);window[a.resolve]&&delete window[a.resolve],window[a.reject]&&delete window[a.reject],window[a.expired]&&delete window[a.expired];var t=document.getElementById(e);t&&t.remove()}}__getGrecaptchaCallbackNames(e){return{expired:"".concat(GoogleCaptcha.EXPIRED_FUNC_NAME,"-").concat(e),reject:"".concat(GoogleCaptcha.REJECT_FUNC_NAME,"-").concat(e),resolve:"".concat(GoogleCaptcha.RESOLVE_FUNC_NAME,"-").concat(e)}}__appendScript(e){var t=this;return a((function*(){if(t.captcha)return Promise.resolve(t.captcha);if('string'!=typeof e||''===e)throw new TypeError('src script is not defined');var a=document.createElement('script');return a.src=e,document.body&&document.body.appendChild(a),new Promise(((e,t)=>{a.addEventListener('load',(()=>{e(true)})),a.addEventListener('error',(()=>{t()}))}))}))()}_loadScript(){var e=this;return a((function*(){if(e.captcha)return Promise.resolve(e.captcha);var t=function(){var t=a((function*(){return yield e.__appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(e.locale,"&onload=__recaptchaReady__"))}));return function(){return t.apply(this,arguments)}}();return new Promise(((a,c)=>{window.__recaptchaReady__=()=>{e.__recaptchaReady(),e.captcha?a(e.captcha):c(new r.CaptchaError('Recaptcha is not available'))},t().catch((()=>c(new r.CaptchaError('Could not load recaptcha scripts'))))}))}))()}__renderRecaptcha(a,t){var r,o;var i=document.createElement('div');return i.style.display='none',i.id=a,document.body&&document.body.appendChild(i),c.log("Render recaptcha widget",this.captcha),{id:null!==(r=null===(o=this.captcha)||void 0===o?void 0:o.render(a,e(e({},t),{},{sitekey:this.sitekey,size:'invisible'})))&&void 0!==r?r:NaN,uuid:a}}__executeRecaptchaWidget(e,t){var c=this;return a((function*(){var a=c.__getGrecaptchaCallbackNames(t);return new Promise(((o,i)=>{var n;window[a.resolve]=()=>{var a;var r=null===(a=c.captcha)||void 0===a?void 0:a.getResponse(e);o({id:e,token:r,uuid:t})},window[a.reject]=()=>{i(new r.CaptchaError('recaptcha is rejected'))},window[a.expired]=()=>{i(new r.CaptchaError('recaptcha is expired'))};var d=null===(n=c.captcha)||void 0===n?void 0:n.execute(e);d?d.catch((e=>{e instanceof Error?i(new r.CaptchaError(e.message)):'string'==typeof e&&i(new r.CaptchaError(e))})):i(new r.CaptchaError('cannot call method execute from grecaptcha'))}))}))()}__createGoogleCaptchaTransaction(){var e=this;return a((function*(){var a=t.generateUUID();var c=e.__getGrecaptchaCallbackNames(a);window[c.resolve]=function(){return null},window[c.reject]=function(){return null},window[c.expired]=function(){return null};var{id:o}=e.__renderRecaptcha(a,{callback:c.resolve,'error-callback':c.reject,'expired-callback':c.expired});if(isNaN(o))throw e.__destroyWidgetByUuid(a),new r.CaptchaError('Recaptcha is not available');try{return yield e.__executeRecaptchaWidget(o,a)}catch(e){if(e instanceof r.CaptchaError)throw new r.CaptchaError('Cannot execute recaptcha with reason: '+e.message,{id:o,uuid:a});throw e}finally{e.__destroyWidgetByUuid(a)}}))()}execute(){var e=this;return a((function*(){if(false!==e.isEnabled()){try{if(yield e._loadScript(),!window.grecaptcha)throw new r.CaptchaError('grecaptcha is not available in window')}catch(e){if(e instanceof r.CaptchaError)throw new r.CaptchaError('grecaptcha is not available: '+e.message);throw e}var a=yield e.__createGoogleCaptchaTransaction();if(e.widgets.push(a),'string'==typeof a.token&&''!==a.token)return a.token}}))()}}GoogleCaptcha.RESOLVE_FUNC_NAME='recaptcha__GoogleRecaptchaResolved',GoogleCaptcha.REJECT_FUNC_NAME='recaptcha__GoogleRecaptchaRejected',GoogleCaptcha.EXPIRED_FUNC_NAME='recaptcha__GoogleRecaptchaExpired',exports.GoogleCaptcha=GoogleCaptcha;
@@ -0,0 +1 @@
1
+ import e from'./../../dependencies/@babel/runtime/helpers/esm/objectSpread2.mjs';import t from'./../../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{generateUUID as a}from'../../utils/uuid.mjs';import{CaptchaError as r}from'../error.mjs';import{log as c}from'../log.mjs';class GoogleCaptcha{constructor(e){var{sitekey:t,locale:a}=e;this.sitekey=null,this.locale='en',this.widgets=[],this.captcha=void 0,this.sitekey=null!=t?t:null,a&&(this.locale=a)}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}__recaptchaReady(){this.captcha=window.grecaptcha}__destroyWidgetByUuid(e){if('string'==typeof e&&this.widgets.find((t=>t.uuid===e))){var t=this.__getGrecaptchaCallbackNames(e);window[t.resolve]&&delete window[t.resolve],window[t.reject]&&delete window[t.reject],window[t.expired]&&delete window[t.expired];var a=document.getElementById(e);a&&a.remove()}}__getGrecaptchaCallbackNames(e){return{expired:"".concat(GoogleCaptcha.EXPIRED_FUNC_NAME,"-").concat(e),reject:"".concat(GoogleCaptcha.REJECT_FUNC_NAME,"-").concat(e),resolve:"".concat(GoogleCaptcha.RESOLVE_FUNC_NAME,"-").concat(e)}}__appendScript(e){var a=this;return t((function*(){if(a.captcha)return Promise.resolve(a.captcha);if('string'!=typeof e||''===e)throw new TypeError('src script is not defined');var t=document.createElement('script');return t.src=e,document.body&&document.body.appendChild(t),new Promise(((e,a)=>{t.addEventListener('load',(()=>{e(true)})),t.addEventListener('error',(()=>{a()}))}))}))()}_loadScript(){var e=this;return t((function*(){if(e.captcha)return Promise.resolve(e.captcha);var a=function(){var a=t((function*(){return yield e.__appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(e.locale,"&onload=__recaptchaReady__"))}));return function(){return a.apply(this,arguments)}}();return new Promise(((t,c)=>{window.__recaptchaReady__=()=>{e.__recaptchaReady(),e.captcha?t(e.captcha):c(new r('Recaptcha is not available'))},a().catch((()=>c(new r('Could not load recaptcha scripts'))))}))}))()}__renderRecaptcha(t,a){var r,o;var i=document.createElement('div');return i.style.display='none',i.id=t,document.body&&document.body.appendChild(i),c("Render recaptcha widget",this.captcha),{id:null!==(r=null===(o=this.captcha)||void 0===o?void 0:o.render(t,e(e({},a),{},{sitekey:this.sitekey,size:'invisible'})))&&void 0!==r?r:NaN,uuid:t}}__executeRecaptchaWidget(e,a){var c=this;return t((function*(){var t=c.__getGrecaptchaCallbackNames(a);return new Promise(((o,i)=>{var n;window[t.resolve]=()=>{var t;var r=null===(t=c.captcha)||void 0===t?void 0:t.getResponse(e);o({id:e,token:r,uuid:a})},window[t.reject]=()=>{i(new r('recaptcha is rejected'))},window[t.expired]=()=>{i(new r('recaptcha is expired'))};var d=null===(n=c.captcha)||void 0===n?void 0:n.execute(e);d?d.catch((e=>{e instanceof Error?i(new r(e.message)):'string'==typeof e&&i(new r(e))})):i(new r('cannot call method execute from grecaptcha'))}))}))()}__createGoogleCaptchaTransaction(){var e=this;return t((function*(){var t=a();var c=e.__getGrecaptchaCallbackNames(t);window[c.resolve]=function(){return null},window[c.reject]=function(){return null},window[c.expired]=function(){return null};var{id:o}=e.__renderRecaptcha(t,{callback:c.resolve,'error-callback':c.reject,'expired-callback':c.expired});if(isNaN(o))throw e.__destroyWidgetByUuid(t),new r('Recaptcha is not available');try{return yield e.__executeRecaptchaWidget(o,t)}catch(e){if(e instanceof r)throw new r('Cannot execute recaptcha with reason: '+e.message,{id:o,uuid:t});throw e}finally{e.__destroyWidgetByUuid(t)}}))()}execute(){var e=this;return t((function*(){if(false!==e.isEnabled()){try{if(yield e._loadScript(),!window.grecaptcha)throw new r('grecaptcha is not available in window')}catch(e){if(e instanceof r)throw new r('grecaptcha is not available: '+e.message);throw e}var t=yield e.__createGoogleCaptchaTransaction();if(e.widgets.push(t),'string'==typeof t.token&&''!==t.token)return t.token}}))()}}GoogleCaptcha.RESOLVE_FUNC_NAME='recaptcha__GoogleRecaptchaResolved',GoogleCaptcha.REJECT_FUNC_NAME='recaptcha__GoogleRecaptchaRejected',GoogleCaptcha.EXPIRED_FUNC_NAME='recaptcha__GoogleRecaptchaExpired';export{GoogleCaptcha};
@@ -0,0 +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{sitekey:t,locale:i,provider:o,notify:c}=e;switch(this.sitekey=null,this.provider=null,this.locale='en',this.captcha=null,this.sitekey=null!=t?t:null,this.provider=null!=o?o:null,i&&(this.locale=i),o){case'cloudflare_turnstile':this.captcha=new r.CloudflareTurnstile({locale:i,notify:c,sitekey:t});break;case'recaptcha':this.captcha=new a.GoogleCaptcha({locale:i,notify:c,sitekey:t})}}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}execute(){var r=this;return e((function*(){if(false!==r.isEnabled()&&r.provider&&r.captcha){var e=yield r.captcha.execute();if(i.log('Receive answer from captcha provider'),!e)throw new t.CaptchaError("Could't get captcha token from provider "+r.provider);return{captcha_provider:r.provider,captcha_token:e}}}))()}};
@@ -0,0 +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{sitekey:t,locale:i,provider:a,notify:c}=e;switch(this.sitekey=null,this.provider=null,this.locale='en',this.captcha=null,this.sitekey=null!=t?t:null,this.provider=null!=a?a:null,i&&(this.locale=i),a){case'cloudflare_turnstile':this.captcha=new r({locale:i,notify:c,sitekey:t});break;case'recaptcha':this.captcha=new o({locale:i,notify:c,sitekey:t})}}isEnabled(){return'string'==typeof this.sitekey&&''!==this.sitekey}execute(){var r=this;return e((function*(){if(false!==r.isEnabled()&&r.provider&&r.captcha){var e=yield r.captcha.execute();if(i('Receive answer from captcha provider'),!e)throw new t("Could't get captcha token from provider "+r.provider);return{captcha_provider:r.provider,captcha_token:e}}}))()}}export{CaptchaService};
package/captcha/log.js ADDED
@@ -0,0 +1 @@
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true}),exports.log=function(){for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];var t=["[CaptchaService] ",...r];console.debug.apply(console,t)};
@@ -0,0 +1 @@
1
+ function e(){for(var e=arguments.length,o=new Array(e),r=0;r<e;r++)o[r]=arguments[r];var a=["[CaptchaService] ",...o];console.debug.apply(console,a)}export{e as log};
package/index.d.ts CHANGED
@@ -174,51 +174,38 @@ export declare abstract class ResponseSuccessPlugin implements ResponseSuccessPl
174
174
  abstract isApplicable(response: ApiResponse): boolean;
175
175
  }
176
176
  declare const apiServiceInstance: ApiServiceInterface;
177
- type RecaptchaAnswer = string;
178
- export type RecaptchaConfig = {
177
+ type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile";
178
+ type CaptchaAnswer = {
179
+ captcha_token: string;
180
+ captcha_provider: CaptchaProviderName;
181
+ };
182
+ export type CaptchaConfig = {
179
183
  locale?: string;
180
184
  sitekey?: string;
185
+ provider?: CaptchaProviderName;
186
+ notify?: (...args: any[]) => void;
187
+ onFatalError?: (code: string) => void;
181
188
  };
182
- export interface RecaptchaServiceInterface {
183
- execute(): Promise<RecaptchaAnswer | void>;
189
+ export interface Captcha {
190
+ execute(): Promise<CaptchaAnswer | void>;
184
191
  isEnabled(): boolean;
185
192
  }
186
- export declare class RecaptchaService implements RecaptchaServiceInterface {
187
- private _sitekey;
188
- private _locale;
189
- private _widgets;
190
- private _captcha;
191
- private static RESOLVE_FUNC_NAME;
192
- private static REJECT_FUNC_NAME;
193
- private static EXPIRED_FUNC_NAME;
194
- constructor({ sitekey, locale }: RecaptchaConfig);
193
+ export declare class CaptchaError extends Error {
194
+ payload: {};
195
+ constructor(message: string, payload?: object);
196
+ }
197
+ export declare class CaptchaService implements Captcha {
198
+ private sitekey;
199
+ private provider;
200
+ private locale;
201
+ private captcha;
202
+ constructor({ sitekey, locale, provider, notify }: CaptchaConfig);
195
203
  isEnabled(): boolean;
196
- private __recaptchaReady;
197
- private __destroyWidgetByUuid;
198
- private __getGrecaptchaCallbackNames;
199
- private __appendScript;
200
- /**
201
- * Load recaptcha script
202
- */
203
- private _loadScript;
204
- /**
205
- * Render recaptcha widget
206
- * @param {string} uuid
207
- * @param {object} params
208
- * @returns {{id: number, uuid: string}}
209
- */
210
- private __renderRecaptcha;
211
- private __executeRecaptchaWidget;
212
- /**
213
- *
214
- * @returns возвращает результат транзакции
215
- */
216
- private __createGoogleCaptchaTransaction;
217
204
  /**
218
205
  * Получаем токен рекапчи
219
- * @returns {Promise<RecaptchaAnswer | void>} <token>
206
+ * @returns {Promise<CaptchaAnswer | void>} <token>
220
207
  */
221
- execute(): Promise<RecaptchaAnswer | void>;
208
+ execute(): Promise<CaptchaAnswer | void>;
222
209
  }
223
210
 
224
211
  export {
package/index.js CHANGED
@@ -1 +1 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./api/index.js');var s=require('./recaptcha/index.js');var r=require('./api/plugins/request/index.js');var i=require('./api/plugins/response-success/index.js');exports.ApiService=e.ApiService,exports.RecaptchaService=s.RecaptchaService,exports.RequestPlugin=r.RequestPlugin,exports.ResponseSuccessPlugin=i.ResponseSuccessPlugin;
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./api/index.js');var r=require('./captcha/index.js');var s=require('./api/plugins/request/index.js');var i=require('./api/plugins/response-success/index.js');var p=require('./captcha/error.js');exports.ApiService=e.ApiService,exports.CaptchaService=r.CaptchaService,exports.RequestPlugin=s.RequestPlugin,exports.ResponseSuccessPlugin=i.ResponseSuccessPlugin,exports.CaptchaError=p.CaptchaError;
package/index.js.flow CHANGED
@@ -242,23 +242,34 @@ declare export class ResponseSuccessPlugin
242
242
  isApplicable(response: ApiResponse<>): boolean;
243
243
  }
244
244
  declare var apiServiceInstance: ApiServiceInterface;
245
- declare type RecaptchaAnswer = string;
246
- export type RecaptchaConfig = {|
245
+ declare type CaptchaProviderName = "recaptcha" | "cloudflare_turnstile";
246
+ declare type CaptchaAnswer = {|
247
+ captcha_token: string,
248
+ captcha_provider: CaptchaProviderName,
249
+ |};
250
+ export type CaptchaConfig = {|
247
251
  locale?: string,
248
252
  sitekey?: string,
253
+ provider?: CaptchaProviderName,
254
+ notify?: (...args: any[]) => void,
255
+ onFatalError?: (code: string) => void,
249
256
  |};
250
- export interface RecaptchaServiceInterface {
251
- execute(): Promise<RecaptchaAnswer | void>;
257
+ export interface Captcha {
258
+ execute(): Promise<CaptchaAnswer | void>;
252
259
  isEnabled(): boolean;
253
260
  }
254
- declare export class RecaptchaService implements RecaptchaServiceInterface {
255
- constructor(x: RecaptchaConfig): this;
261
+ declare export class CaptchaError mixins Error {
262
+ payload: {||};
263
+ constructor(message: string, payload?: { [key: string]: any }): this;
264
+ }
265
+ declare export class CaptchaService implements Captcha {
266
+ constructor(x: CaptchaConfig): this;
256
267
  isEnabled(): boolean;
257
268
 
258
269
  /**
259
270
  * Получаем токен рекапчи
260
- * @returns {Promise<RecaptchaAnswer | void>} <token>
271
+ * @returns {Promise<CaptchaAnswer | void>} <token>
261
272
  */
262
- execute(): Promise<RecaptchaAnswer | void>;
273
+ execute(): Promise<CaptchaAnswer | void>;
263
274
  }
264
275
  declare export { apiServiceInstance as ApiService };
package/index.mjs CHANGED
@@ -1 +1 @@
1
- export{ApiService}from'./api/index.mjs';export{RecaptchaService}from'./recaptcha/index.mjs';export{RequestPlugin}from'./api/plugins/request/index.mjs';export{ResponseSuccessPlugin}from'./api/plugins/response-success/index.mjs';
1
+ export{ApiService}from'./api/index.mjs';export{CaptchaService}from'./captcha/index.mjs';export{RequestPlugin}from'./api/plugins/request/index.mjs';export{ResponseSuccessPlugin}from'./api/plugins/response-success/index.mjs';export{CaptchaError}from'./captcha/error.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foxford/services",
3
- "version": "1.1.0",
3
+ "version": "1.2.0-beta-6bf5bf4a-20240109",
4
4
  "description": "Foxford services",
5
5
  "main": "index.js",
6
6
  "module": "index.mjs",
@@ -62,6 +62,22 @@
62
62
  "api/plugins/request/index.mjs",
63
63
  "api/plugins/response-success/index.js",
64
64
  "api/plugins/response-success/index.mjs",
65
+ "captcha/cloudflare/constants.js",
66
+ "captcha/cloudflare/constants.mjs",
67
+ "captcha/cloudflare/index.js",
68
+ "captcha/cloudflare/index.mjs",
69
+ "captcha/cloudflare/style.js",
70
+ "captcha/cloudflare/style.mjs",
71
+ "captcha/cloudflare/template.js",
72
+ "captcha/cloudflare/template.mjs",
73
+ "captcha/error.js",
74
+ "captcha/error.mjs",
75
+ "captcha/google/index.js",
76
+ "captcha/google/index.mjs",
77
+ "captcha/index.js",
78
+ "captcha/index.mjs",
79
+ "captcha/log.js",
80
+ "captcha/log.mjs",
65
81
  "dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js",
66
82
  "dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs",
67
83
  "dependencies/@babel/runtime/helpers/esm/defineProperty.js",
@@ -139,11 +155,10 @@
139
155
  "index.js.flow",
140
156
  "index.mjs",
141
157
  "packages.json",
142
- "recaptcha/index.js",
143
- "recaptcha/index.mjs",
144
158
  "utils/uuid.js",
145
159
  "utils/uuid.mjs"
146
160
  ],
147
161
  "scripts": {},
148
162
  "peerDependencies": {}
149
163
  }
164
+
@@ -1 +0,0 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var e=require('./../dependencies/@babel/runtime/helpers/esm/objectSpread2.js');var a=require('./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.js');var t=require('../utils/uuid.js');class CaptchaError extends Error{constructor(e,a){super(e),this.payload={},this.name='CaptchaError',this.message=e,a&&(this.payload=a)}}class RecaptchaService{constructor(e){var{sitekey:a,locale:t}=e;this._sitekey=null,this._locale='en',this._widgets=[],this._captcha=void 0,this._sitekey=null!=a?a:null,t&&(this._locale=t)}isEnabled(){return'string'==typeof this._sitekey&&''!==this._sitekey}__recaptchaReady(){this._captcha=window.grecaptcha}__destroyWidgetByUuid(e){if('string'==typeof e&&this._widgets.find((a=>a.uuid===e))){var a=this.__getGrecaptchaCallbackNames(e);window[a.resolve]&&delete window[a.resolve],window[a.reject]&&delete window[a.reject],window[a.expired]&&delete window[a.expired];var t=document.getElementById(e);t&&t.remove()}}__getGrecaptchaCallbackNames(e){return{expired:"".concat(RecaptchaService.EXPIRED_FUNC_NAME,"-").concat(e),reject:"".concat(RecaptchaService.REJECT_FUNC_NAME,"-").concat(e),resolve:"".concat(RecaptchaService.RESOLVE_FUNC_NAME,"-").concat(e)}}__appendScript(e){var t=this;return a((function*(){if(t._captcha)return Promise.resolve(t._captcha);if('string'!=typeof e||''===e)throw new TypeError('src script is not defined');var a=document.createElement('script');return a.src=e,document.body&&document.body.appendChild(a),new Promise(((e,t)=>{a.addEventListener('load',(()=>{e(true)})),a.addEventListener('error',(()=>{t()}))}))}))()}_loadScript(){var e=this;return a((function*(){if(e._captcha)return Promise.resolve(e._captcha);var t=function(){var t=a((function*(){return yield e.__appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(e._locale,"&onload=__recaptchaReady__"))}));return function(){return t.apply(this,arguments)}}();return new Promise(((a,r)=>{window.__recaptchaReady__=()=>{e.__recaptchaReady(),e._captcha?a(e._captcha):r(new CaptchaError('Captcha is not available'))},t().catch((()=>r(new CaptchaError('Could not load recaptcha scripts'))))}))}))()}__renderRecaptcha(a,t){var r,c;var i=document.createElement('div');return i.style.display='none',i.id=a,document.body&&document.body.appendChild(i),console.debug("Render recaptcha widget",this._captcha),{id:null!==(r=null===(c=this._captcha)||void 0===c?void 0:c.render(a,e(e({},t),{},{sitekey:this._sitekey,size:'invisible'})))&&void 0!==r?r:NaN,uuid:a}}__executeRecaptchaWidget(e,t){var r=this;return a((function*(){var a=r.__getGrecaptchaCallbackNames(t);return new Promise(((c,i)=>{var n;window[a.resolve]=()=>{var a;var i=null===(a=r._captcha)||void 0===a?void 0:a.getResponse(e);c({id:e,token:i,uuid:t})},window[a.reject]=()=>{i(new CaptchaError('recaptcha is rejected'))},window[a.expired]=()=>{i(new CaptchaError('recaptcha is expired'))};var o=null===(n=r._captcha)||void 0===n?void 0:n.execute(e);o?o.catch((e=>{e instanceof Error?i(new CaptchaError(e.message)):'string'==typeof e&&i(new CaptchaError(e))})):i(new CaptchaError('cannot call method execute from grecaptcha'))}))}))()}__createGoogleCaptchaTransaction(){var e=this;return a((function*(){var a=t.generateUUID();var r=e.__getGrecaptchaCallbackNames(a);window[r.resolve]=function(){return null},window[r.reject]=function(){return null},window[r.expired]=function(){return null};var{id:c}=e.__renderRecaptcha(a,{callback:r.resolve,'error-callback':r.reject,'expired-callback':r.expired});if(isNaN(c))throw e.__destroyWidgetByUuid(a),new CaptchaError('Recaptcha is not available');try{return yield e.__executeRecaptchaWidget(c,a)}catch(e){if(e instanceof CaptchaError)throw new CaptchaError('Cannot execute recaptcha with reason: '+e.message,{id:c,uuid:a});throw e}finally{e.__destroyWidgetByUuid(a)}}))()}execute(){var e=this;return a((function*(){if(false!==e.isEnabled()){try{if(yield e._loadScript(),!window.grecaptcha)throw new CaptchaError('grecaptcha is not available in window')}catch(e){if(e instanceof CaptchaError)throw new CaptchaError('grecaptcha is not available: '+e.message);throw e}var a=yield e.__createGoogleCaptchaTransaction();if(e._widgets.push(a),'string'==typeof a.token&&''!==a.token)return a.token}}))()}}RecaptchaService.RESOLVE_FUNC_NAME='recaptcha__GoogleRecaptchaResolved',RecaptchaService.REJECT_FUNC_NAME='recaptcha__GoogleRecaptchaRejected',RecaptchaService.EXPIRED_FUNC_NAME='recaptcha__GoogleRecaptchaExpired',exports.RecaptchaService=RecaptchaService;
@@ -1 +0,0 @@
1
- import e from'./../dependencies/@babel/runtime/helpers/esm/objectSpread2.mjs';import a from'./../dependencies/@babel/runtime/helpers/esm/asyncToGenerator.mjs';import{generateUUID as t}from'../utils/uuid.mjs';class CaptchaError extends Error{constructor(e,a){super(e),this.payload={},this.name='CaptchaError',this.message=e,a&&(this.payload=a)}}class RecaptchaService{constructor(e){var{sitekey:a,locale:t}=e;this._sitekey=null,this._locale='en',this._widgets=[],this._captcha=void 0,this._sitekey=null!=a?a:null,t&&(this._locale=t)}isEnabled(){return'string'==typeof this._sitekey&&''!==this._sitekey}__recaptchaReady(){this._captcha=window.grecaptcha}__destroyWidgetByUuid(e){if('string'==typeof e&&this._widgets.find((a=>a.uuid===e))){var a=this.__getGrecaptchaCallbackNames(e);window[a.resolve]&&delete window[a.resolve],window[a.reject]&&delete window[a.reject],window[a.expired]&&delete window[a.expired];var t=document.getElementById(e);t&&t.remove()}}__getGrecaptchaCallbackNames(e){return{expired:"".concat(RecaptchaService.EXPIRED_FUNC_NAME,"-").concat(e),reject:"".concat(RecaptchaService.REJECT_FUNC_NAME,"-").concat(e),resolve:"".concat(RecaptchaService.RESOLVE_FUNC_NAME,"-").concat(e)}}__appendScript(e){var t=this;return a((function*(){if(t._captcha)return Promise.resolve(t._captcha);if('string'!=typeof e||''===e)throw new TypeError('src script is not defined');var a=document.createElement('script');return a.src=e,document.body&&document.body.appendChild(a),new Promise(((e,t)=>{a.addEventListener('load',(()=>{e(true)})),a.addEventListener('error',(()=>{t()}))}))}))()}_loadScript(){var e=this;return a((function*(){if(e._captcha)return Promise.resolve(e._captcha);var t=function(){var t=a((function*(){return yield e.__appendScript("https://www.google.com/recaptcha/api.js?hl=".concat(e._locale,"&onload=__recaptchaReady__"))}));return function(){return t.apply(this,arguments)}}();return new Promise(((a,r)=>{window.__recaptchaReady__=()=>{e.__recaptchaReady(),e._captcha?a(e._captcha):r(new CaptchaError('Captcha is not available'))},t().catch((()=>r(new CaptchaError('Could not load recaptcha scripts'))))}))}))()}__renderRecaptcha(a,t){var r,c;var i=document.createElement('div');return i.style.display='none',i.id=a,document.body&&document.body.appendChild(i),console.debug("Render recaptcha widget",this._captcha),{id:null!==(r=null===(c=this._captcha)||void 0===c?void 0:c.render(a,e(e({},t),{},{sitekey:this._sitekey,size:'invisible'})))&&void 0!==r?r:NaN,uuid:a}}__executeRecaptchaWidget(e,t){var r=this;return a((function*(){var a=r.__getGrecaptchaCallbackNames(t);return new Promise(((c,i)=>{var o;window[a.resolve]=()=>{var a;var i=null===(a=r._captcha)||void 0===a?void 0:a.getResponse(e);c({id:e,token:i,uuid:t})},window[a.reject]=()=>{i(new CaptchaError('recaptcha is rejected'))},window[a.expired]=()=>{i(new CaptchaError('recaptcha is expired'))};var n=null===(o=r._captcha)||void 0===o?void 0:o.execute(e);n?n.catch((e=>{e instanceof Error?i(new CaptchaError(e.message)):'string'==typeof e&&i(new CaptchaError(e))})):i(new CaptchaError('cannot call method execute from grecaptcha'))}))}))()}__createGoogleCaptchaTransaction(){var e=this;return a((function*(){var a=t();var r=e.__getGrecaptchaCallbackNames(a);window[r.resolve]=function(){return null},window[r.reject]=function(){return null},window[r.expired]=function(){return null};var{id:c}=e.__renderRecaptcha(a,{callback:r.resolve,'error-callback':r.reject,'expired-callback':r.expired});if(isNaN(c))throw e.__destroyWidgetByUuid(a),new CaptchaError('Recaptcha is not available');try{return yield e.__executeRecaptchaWidget(c,a)}catch(e){if(e instanceof CaptchaError)throw new CaptchaError('Cannot execute recaptcha with reason: '+e.message,{id:c,uuid:a});throw e}finally{e.__destroyWidgetByUuid(a)}}))()}execute(){var e=this;return a((function*(){if(false!==e.isEnabled()){try{if(yield e._loadScript(),!window.grecaptcha)throw new CaptchaError('grecaptcha is not available in window')}catch(e){if(e instanceof CaptchaError)throw new CaptchaError('grecaptcha is not available: '+e.message);throw e}var a=yield e.__createGoogleCaptchaTransaction();if(e._widgets.push(a),'string'==typeof a.token&&''!==a.token)return a.token}}))()}}RecaptchaService.RESOLVE_FUNC_NAME='recaptcha__GoogleRecaptchaResolved',RecaptchaService.REJECT_FUNC_NAME='recaptcha__GoogleRecaptchaRejected',RecaptchaService.EXPIRED_FUNC_NAME='recaptcha__GoogleRecaptchaExpired';export{RecaptchaService};