@dtect/security-sdk-js 0.0.11 → 0.0.12
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/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var J=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var nt=Object.prototype.hasOwnProperty;var it=(e,t)=>{for(var r in t)J(e,r,{get:t[r],enumerable:!0})},ot=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of rt(t))!nt.call(e,i)&&i!==r&&J(e,i,{get:()=>t[i],enumerable:!(n=tt(t,i))||n.enumerable});return e};var st=e=>ot(J({},"__esModule",{value:!0}),e);var tr={};it(tr,{SecurityAPIError:()=>ze,default:()=>er,getSecurityResult:()=>me,getSecurityToken:()=>Re,init:()=>Je});module.exports=st(tr);var M=function(){return M=Object.assign||function(t){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])}return t},M.apply(this,arguments)};function Te(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function Oe(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,s;n<i;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))}function at(e,t){return function(r,n){return Object.prototype.hasOwnProperty.call(r,n)}(e,t)?e[t]:void 0}function ut(e,t,r,n){var i,s=document,u="securitypolicyviolation",o=function(E){var l=new URL(e,location.href),d=E.blockedURI;d!==l.href&&d!==l.protocol.slice(0,-1)&&d!==l.origin||(i=E,a())};s.addEventListener(u,o);var a=function(){return s.removeEventListener(u,o)};return n?.then(a,a),Promise.resolve().then(t).then(function(E){return a(),E},function(E){return new Promise(function(l){var d=new MessageChannel;d.port1.onmessage=function(){return l()},d.port2.postMessage(null)}).then(function(){if(a(),i)return r(i);throw E})})}var ct={default:"endpoint"},lt={default:"tlsEndpoint"},ft="Client timeout",ht="Network connection error",dt="Network request aborted",pt="Response cannot be parsed",Z="Blocked by CSP",H="The endpoint parameter is not a valid URL";function A(e){for(var t="",r=0;r<e.length;++r)if(r>0){var n=e[r].toLowerCase();n!==e[r]?t+=" ".concat(n):t+=e[r]}else t+=e[r].toUpperCase();return t}var yt=A("WrongRegion"),Et=A("SubscriptionNotActive"),mt=A("UnsupportedVersion"),Rt=A("InstallationMethodRestricted"),Tt=A("HostnameRestricted"),Ot=A("IntegrationFailed"),ee="API key required",Ie="API key not found",_e="API key expired",It="Request cannot be parsed",_t="Request failed",vt="Request failed to process",wt="Too many requests, rate limit exceeded",gt="Not available for this origin",bt="Not available with restricted header",At=ee,Pt=Ie,Nt=_e,Dt="3.11.6",K="Failed to load the JS script of the agent",te="9319";function St(e,t){var r,n,i,s,u,o,a,E=[],l=(r=function(f){var c=Oe([],f,!0);return{current:function(){return c[0]},postpone:function(){var p=c.shift();p!==void 0&&c.push(p)},exclude:function(){c.shift()}}}(e),s=100,u=3e3,o=0,n=function(){return Math.random()*Math.min(u,s*Math.pow(2,o++))},i=new Set,[r.current(),function(f,c){var p,y=c instanceof Error?c.message:"";if(y===Z||y===H)r.exclude(),p=0;else if(y===te)r.exclude();else if(y===K){var T=Date.now()-f.getTime()<50,O=r.current();O&&T&&!i.has(O)&&(i.add(O),p=0),r.postpone()}else r.postpone();var w=r.current();return w===void 0?void 0:[w,p??f.getTime()+n()-Date.now()]}]),d=l[0],_=l[1];if(d===void 0)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var v=function(f){var c=new Date,p=function(T){return E.push({url:f,startedAt:c,finishedAt:new Date,error:T})},y=t(f);return y.then(function(){return p()},p),y.catch(function(T){if(a!=null||(a=T),E.length>=5)throw a;var O=_(c,T);if(!O)throw a;var w,z=O[0],He=O[1];return(w=He,new Promise(function(et){return setTimeout(et,w)})).then(function(){return v(z)})})};return v(d).then(function(f){return[f,E]})}var ve="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",Mt=ve;function xt(e){var t;e.scriptUrlPattern;var r=e.token,n=e.apiKey,i=n===void 0?r:n,s=Te(e,["scriptUrlPattern","token","apiKey"]),u=(t=at(e,"scriptUrlPattern"))!==null&&t!==void 0?t:ve,o=function(){var l=[],d=function(){l.push({time:new Date,state:document.visibilityState})},_=function(v,f,c,p){return v.addEventListener(f,c,p),function(){return v.removeEventListener(f,c,p)}}(document,"visibilitychange",d);return d(),[l,_]}(),a=o[0],E=o[1];return Promise.resolve().then(function(){if(!i||typeof i!="string")throw new Error(ee);var l=function(d,_){return(Array.isArray(d)?d:[d]).map(function(v){return function(f,c){var p=encodeURIComponent;return f.replace(/<[^<>]+>/g,function(y){return y==="<version>"?"3":y==="<apiKey>"?p(c):y==="<loaderVersion>"?p(Dt):y})}(String(v),_)})}(u,i);return St(l,Lt)}).catch(function(l){throw E(),function(d){return d instanceof Error&&d.message===te?new Error(K):d}(l)}).then(function(l){var d=l[0],_=l[1];return E(),d.load(M(M({},s),{ldi:{attempts:_,visibilityStates:a}}))})}function Lt(e){return ut(e,function(){return function(t){return new Promise(function(r,n){if(function(o){if(URL.prototype)try{return new URL(o,location.href),!1}catch(a){if(a instanceof Error&&a.name==="TypeError")return!0;throw a}}(t))throw new Error(H);var i=document.createElement("script"),s=function(){var o;return(o=i.parentNode)===null||o===void 0?void 0:o.removeChild(i)},u=document.head||document.getElementsByTagName("head")[0];i.onload=function(){s(),r()},i.onerror=function(){s(),n(new Error(K))},i.async=!0,i.src=t,u.appendChild(i)})}(e)},function(){throw new Error(Z)}).then(Ft)}function Ft(){var e=window,t="__fpjs_p_l_b",r=e[t];if(function(n,i){var s,u=(s=Object.getOwnPropertyDescriptor)===null||s===void 0?void 0:s.call(Object,n,i);u?.configurable?delete n[i]:u&&!u.writable||(n[i]=void 0)}(e,t),typeof r?.load!="function")throw new Error(te);return r}var P={load:xt,defaultScriptUrlPattern:Mt,ERROR_SCRIPT_LOAD_FAIL:K,ERROR_API_KEY_EXPIRED:_e,ERROR_API_KEY_INVALID:Ie,ERROR_API_KEY_MISSING:ee,ERROR_BAD_REQUEST_FORMAT:It,ERROR_BAD_RESPONSE_FORMAT:pt,ERROR_CLIENT_TIMEOUT:ft,ERROR_CSP_BLOCK:Z,ERROR_FORBIDDEN_ENDPOINT:Tt,ERROR_FORBIDDEN_HEADER:bt,ERROR_FORBIDDEN_ORIGIN:gt,ERROR_GENERAL_SERVER_FAILURE:_t,ERROR_INSTALLATION_METHOD_RESTRICTED:Rt,ERROR_INTEGRATION_FAILURE:Ot,ERROR_INVALID_ENDPOINT:H,ERROR_NETWORK_ABORT:dt,ERROR_NETWORK_CONNECTION:ht,ERROR_RATE_LIMIT:wt,ERROR_SERVER_TIMEOUT:vt,ERROR_SUBSCRIPTION_NOT_ACTIVE:Et,ERROR_TOKEN_EXPIRED:Nt,ERROR_TOKEN_INVALID:Pt,ERROR_TOKEN_MISSING:At,ERROR_UNSUPPORTED_VERSION:mt,ERROR_WRONG_REGION:yt,defaultEndpoint:ct,defaultTlsEndpoint:lt};var R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function we(e,t=0){return(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase()}var re,Ut=new Uint8Array(16);function ne(){if(!re){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");re=crypto.getRandomValues.bind(crypto)}return re(Ut)}var kt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ie={randomUUID:kt};function qt(e,t,r){if(ie.randomUUID&&!t&&!e)return ie.randomUUID();e=e||{};let n=e.random??e.rng?.()??ne();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return we(n)}var Q=qt;var jt={UNAUTHORIZED:"Unauthorized"},Kt={EXPIRED:"EXPIRED_TOKEN",INVALID_API_KEY:"INVALID_API_KEY",MISSING_AUTHENTICATION_TOKEN:"MISSING_AUTHENTICATION_TOKEN"},ge={INTERNAL_SERVER_ERROR:"Internal Server Error during API Request",MISSING_CREDENTIALS:"Missing Public Client ID or Public API Key",MAINTENANCE_MODE:"API Under Maintenance",RATE_LIMIT_REACHED:"Too many requests. Rate limit exceeded"},be={SDK_INIT_ERROR:"Internal Server Error during SDK Initialization",DUPLICATE_INITIALIZATION:"Multiple SDK Initializations Detected",NOT_INITIALIZED:"SDK Not Initialized"},Ae={INVALID_CREDENTIALS:"Invalid Public Client ID or Public API Key"},Pe={FAILED_TO_GET_SECURITY_RESULT:"Failed to Retrieve Security Result"},Ne={FAILED_TO_GET_SECURITY_TOKEN:" Failed to Generate Security Token"},h={...jt,...Kt,...ge,...be,...Ae,...Pe,...Ne},De={...ge,...be,...Ae,...Pe,...Ne};var g=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var b=typeof window>"u"||"Deno"in globalThis;function I(){}function xe(e,t){return typeof e=="function"?e(t):e}function Le(e){return typeof e=="number"&&e>=0&&e!==1/0}function Fe(e,t){return Math.max(e+(t||0)-Date.now(),0)}function se(e,t){return typeof e=="function"?e(t):e}function Ue(e,t){return typeof e=="function"?e(t):e}function ae(e,t){let{type:r="all",exact:n,fetchStatus:i,predicate:s,queryKey:u,stale:o}=e;if(u){if(n){if(t.queryHash!==x(u,t.options))return!1}else if(!D(t.queryKey,u))return!1}if(r!=="all"){let a=t.isActive();if(r==="active"&&!a||r==="inactive"&&a)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||i&&i!==t.state.fetchStatus||s&&!s(t))}function ue(e,t){let{exact:r,status:n,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(r){if(N(t.options.mutationKey)!==N(s))return!1}else if(!D(t.options.mutationKey,s))return!1}return!(n&&t.state.status!==n||i&&!i(t))}function x(e,t){return(t?.queryKeyHashFn||N)(e)}function N(e){return JSON.stringify(e,(t,r)=>oe(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function D(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(r=>!D(e[r],t[r])):!1}function ke(e,t){if(e===t)return e;let r=Se(e)&&Se(t);if(r||oe(e)&&oe(t)){let n=r?e:Object.keys(e),i=n.length,s=r?t:Object.keys(t),u=s.length,o=r?[]:{},a=0;for(let E=0;E<u;E++){let l=r?E:s[E];(!r&&n.includes(l)||r)&&e[l]===void 0&&t[l]===void 0?(o[l]=void 0,a++):(o[l]=ke(e[l],t[l]),o[l]===e[l]&&e[l]!==void 0&&a++)}return i===u&&a===i?e:o}return t}function Se(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function oe(e){if(!Me(e))return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(!Me(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Me(e){return Object.prototype.toString.call(e)==="[object Object]"}function qe(e){return new Promise(t=>{setTimeout(t,e)})}function je(e,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(e,t):r.structuralSharing!==!1?ke(e,t):t}function Ke(e,t,r=0){let n=[...e,t];return r&&n.length>r?n.slice(1):n}function Qe(e,t,r=0){let n=[t,...e];return r&&n.length>r?n.slice(0,-1):n}var L=Symbol();function G(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===L?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Qt=class extends g{#e;#t;#r;constructor(){super(),this.#r=e=>{if(!b&&window.addEventListener){let t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},B=new Qt;var Gt=class extends g{#e=!0;#t;#r;constructor(){super(),this.#r=e=>{if(!b&&window.addEventListener){let t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(r=>{r(e)}))}isOnline(){return this.#e}},S=new Gt;function Ge(){let e,t,r=new Promise((i,s)=>{e=i,t=s});r.status="pending",r.catch(()=>{});function n(i){Object.assign(r,i),delete r.resolve,delete r.reject}return r.resolve=i=>{n({status:"fulfilled",value:i}),e(i)},r.reject=i=>{n({status:"rejected",reason:i}),t(i)},r}function Bt(e){return Math.min(1e3*2**e,3e4)}function ce(e){return(e??"online")==="online"?S.isOnline():!0}var Be=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function V(e){return e instanceof Be}function C(e){let t=!1,r=0,n=!1,i,s=Ge(),u=c=>{n||(_(new Be(c)),e.abort?.())},o=()=>{t=!0},a=()=>{t=!1},E=()=>B.isFocused()&&(e.networkMode==="always"||S.isOnline())&&e.canRun(),l=()=>ce(e.networkMode)&&e.canRun(),d=c=>{n||(n=!0,e.onSuccess?.(c),i?.(),s.resolve(c))},_=c=>{n||(n=!0,e.onError?.(c),i?.(),s.reject(c))},v=()=>new Promise(c=>{i=p=>{(n||E())&&c(p)},e.onPause?.()}).then(()=>{i=void 0,n||e.onContinue?.()}),f=()=>{if(n)return;let c,p=r===0?e.initialPromise:void 0;try{c=p??e.fn()}catch(y){c=Promise.reject(y)}Promise.resolve(c).then(d).catch(y=>{if(n)return;let T=e.retry??(b?0:3),O=e.retryDelay??Bt,w=typeof O=="function"?O(r,y):O,z=T===!0||typeof T=="number"&&r<T||typeof T=="function"&&T(r,y);if(t||!z){_(y);return}r++,e.onFail?.(r,y),qe(w).then(()=>E()?void 0:v()).then(()=>{t?_(y):f()})})};return{promise:s,cancel:u,continue:()=>(i?.(),s),cancelRetry:o,continueRetry:a,canStart:l,start:()=>(l()?f():v().then(f),s)}}function Vt(){let e=[],t=0,r=o=>{o()},n=o=>{o()},i=o=>setTimeout(o,0),s=o=>{t?e.push(o):i(()=>{r(o)})},u=()=>{let o=e;e=[],o.length&&i(()=>{n(()=>{o.forEach(a=>{r(a)})})})};return{batch:o=>{let a;t++;try{a=o()}finally{t--,t||u()}return a},batchCalls:o=>(...a)=>{s(()=>{o(...a)})},schedule:s,setNotifyFunction:o=>{r=o},setBatchNotifyFunction:o=>{n=o},setScheduler:o=>{i=o}}}var m=Vt();var Y=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Le(this.gcTime)&&(this.#e=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(b?1/0:5*60*1e3))}clearGcTimeout(){this.#e&&(clearTimeout(this.#e),this.#e=void 0)}};var Ve=class extends Y{#e;#t;#r;#n;#s;#o;constructor(e){super(),this.#o=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.cache,this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=Yt(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#n?.promise}setOptions(e){this.options={...this.#s,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){let r=je(this.state.data,e,this.options);return this.#i({data:r,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),r}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){let t=this.#n?.promise;return this.#n?.cancel(e),t?t.then(I).catch(I):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>Ue(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===L||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!Fe(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#n?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#n?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#n&&(this.#o?this.#n.cancel({revert:!0}):this.#n.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#n)return this.#n.continueRetry(),this.#n.promise}if(e&&this.setOptions(e),!this.options.queryFn){let o=this.observers.find(a=>a.options.queryFn);o&&this.setOptions(o.options)}let r=new AbortController,n=o=>{Object.defineProperty(o,"signal",{enumerable:!0,get:()=>(this.#o=!0,r.signal)})},i=()=>{let o=G(this.options,t),a={queryKey:this.queryKey,meta:this.meta};return n(a),this.#o=!1,this.options.persister?this.options.persister(o,a,this):o(a)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:i};n(s),this.options.behavior?.onFetch(s,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#i({type:"fetch",meta:s.fetchOptions?.meta});let u=o=>{V(o)&&o.silent||this.#i({type:"error",error:o}),V(o)||(this.#r.config.onError?.(o,this),this.#r.config.onSettled?.(this.state.data,o,this)),this.scheduleGc()};return this.#n=C({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:r.abort.bind(r),onSuccess:o=>{if(o===void 0){u(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(o)}catch(a){u(a);return}this.#r.config.onSuccess?.(o,this),this.#r.config.onSettled?.(o,this.state.error,this),this.scheduleGc()},onError:u,onFail:(o,a)=>{this.#i({type:"failed",failureCount:o,error:a})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#n.start()}#i(e){let t=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ct(r.data,this.options),fetchMeta:e.meta??null};case"success":return{...r,data:e.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":let n=e.error;return V(n)&&n.revert&&this.#t?{...this.#t,fetchStatus:"idle"}:{...r,error:n,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=t(this.state),m.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Ct(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ce(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Yt(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,r=t!==void 0,n=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var F=class extends g{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,r){let n=t.queryKey,i=t.queryHash??x(n,t),s=this.get(i);return s||(s=new Ve({cache:this,queryKey:n,queryHash:i,options:e.defaultQueryOptions(t),state:r,defaultOptions:e.getQueryDefaults(n)}),this.add(s)),s}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){m.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(r=>ae(t,r))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(r=>ae(e,r)):t}notify(e){m.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){m.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){m.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}};var Ce=class extends Y{#e;#t;#r;constructor(e){super(),this.mutationId=e.mutationId,this.#t=e.mutationCache,this.#e=[],this.state=e.state||Wt(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#t.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#t.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#t.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){this.#r=C({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(n,i)=>{this.#n({type:"failed",failureCount:n,error:i})},onPause:()=>{this.#n({type:"pause"})},onContinue:()=>{this.#n({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#t.canRun(this)});let t=this.state.status==="pending",r=!this.#r.canStart();try{if(!t){this.#n({type:"pending",variables:e,isPaused:r}),await this.#t.config.onMutate?.(e,this);let i=await this.options.onMutate?.(e);i!==this.state.context&&this.#n({type:"pending",context:i,variables:e,isPaused:r})}let n=await this.#r.start();return await this.#t.config.onSuccess?.(n,e,this.state.context,this),await this.options.onSuccess?.(n,e,this.state.context),await this.#t.config.onSettled?.(n,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(n,null,e,this.state.context),this.#n({type:"success",data:n}),n}catch(n){try{throw await this.#t.config.onError?.(n,e,this.state.context,this),await this.options.onError?.(n,e,this.state.context),await this.#t.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,n,e,this.state.context),n}finally{this.#n({type:"error",error:n})}}finally{this.#t.runNext(this)}}#n(e){let t=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),m.batch(()=>{this.#e.forEach(r=>{r.onMutationUpdate(e)}),this.#t.notify({mutation:this,type:"updated",action:e})})}};function Wt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var U=class extends g{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(e,t,r){let n=new Ce({mutationCache:this,mutationId:++this.#r,options:e.defaultMutationOptions(t),state:r});return this.add(n),n}add(e){this.#e.add(e);let t=W(e);if(typeof t=="string"){let r=this.#t.get(t);r?r.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){let t=W(e);if(typeof t=="string"){let r=this.#t.get(t);if(r)if(r.length>1){let n=r.indexOf(e);n!==-1&&r.splice(n,1)}else r[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){let t=W(e);if(typeof t=="string"){let n=this.#t.get(t)?.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){let t=W(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){m.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(r=>ue(t,r))}findAll(e={}){return this.getAll().filter(t=>ue(e,t))}notify(e){m.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(t=>t.state.isPaused);return m.batch(()=>Promise.all(e.map(t=>t.continue().catch(I))))}};function W(e){return e.options.scope?.id}function le(e){return{onFetch:(t,r)=>{let n=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],u=t.state.data?.pageParams||[],o={pages:[],pageParams:[]},a=0,E=async()=>{let l=!1,d=f=>{Object.defineProperty(f,"signal",{enumerable:!0,get:()=>(t.signal.aborted?l=!0:t.signal.addEventListener("abort",()=>{l=!0}),t.signal)})},_=G(t.options,t.fetchOptions),v=async(f,c,p)=>{if(l)return Promise.reject();if(c==null&&f.pages.length)return Promise.resolve(f);let y={queryKey:t.queryKey,pageParam:c,direction:p?"backward":"forward",meta:t.options.meta};d(y);let T=await _(y),{maxPages:O}=t.options,w=p?Qe:Ke;return{pages:w(f.pages,T,O),pageParams:w(f.pageParams,c,O)}};if(i&&s.length){let f=i==="backward",c=f?Xt:Ye,p={pages:s,pageParams:u},y=c(n,p);o=await v(p,y,f)}else{let f=e??s.length;do{let c=a===0?u[0]??n.initialPageParam:Ye(n,o);if(a>0&&c==null)break;o=await v(o,c),a++}while(a<f)}return o};t.options.persister?t.fetchFn=()=>t.options.persister?.(E,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r):t.fetchFn=E}}}function Ye(e,{pages:t,pageParams:r}){let n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,r[n],r):void 0}function Xt(e,{pages:t,pageParams:r}){return t.length>0?e.getPreviousPageParam?.(t[0],t,r[0],r):void 0}var fe=class{#e;#t;#r;#n;#s;#o;#i;#a;constructor(e={}){this.#e=e.queryCache||new F,this.#t=e.mutationCache||new U,this.#r=e.defaultOptions||{},this.#n=new Map,this.#s=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=B.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=S.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#i?.(),this.#i=void 0,this.#a?.(),this.#a=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),r=this.#e.build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(se(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:r})=>{let n=r.data;return[t,n]})}setQueryData(e,t,r){let n=this.defaultQueryOptions({queryKey:e}),s=this.#e.get(n.queryHash)?.state.data,u=xe(t,s);if(u!==void 0)return this.#e.build(this,n).setData(u,{...r,manual:!0})}setQueriesData(e,t,r){return m.batch(()=>this.#e.findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;m.batch(()=>{t.findAll(e).forEach(r=>{t.remove(r)})})}resetQueries(e,t){let r=this.#e,n={type:"active",...e};return m.batch(()=>(r.findAll(e).forEach(i=>{i.reset()}),this.refetchQueries(n,t)))}cancelQueries(e,t={}){let r={revert:!0,...t},n=m.batch(()=>this.#e.findAll(e).map(i=>i.cancel(r)));return Promise.all(n).then(I).catch(I)}invalidateQueries(e,t={}){return m.batch(()=>{if(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none")return Promise.resolve();let r={...e,type:e?.refetchType??e?.type??"active"};return this.refetchQueries(r,t)})}refetchQueries(e,t={}){let r={...t,cancelRefetch:t.cancelRefetch??!0},n=m.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()).map(i=>{let s=i.fetch(void 0,r);return r.throwOnError||(s=s.catch(I)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(n).then(I)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let r=this.#e.build(this,t);return r.isStaleByTime(se(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(I).catch(I)}fetchInfiniteQuery(e){return e.behavior=le(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(I).catch(I)}ensureInfiniteQueryData(e){return e.behavior=le(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return S.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(e){this.#r=e}setQueryDefaults(e,t){this.#n.set(N(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#n.values()],r={};return t.forEach(n=>{D(e,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(e,t){this.#s.set(N(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#s.values()],r={};return t.forEach(n=>{D(e,n.mutationKey)&&(r={...r,...n.defaultOptions})}),r}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#r.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=x(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===L&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#r.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var $t=new fe({defaultOptions:{queries:{staleTime:3e4}},queryCache:new F({onError:(e,t)=>{}}),mutationCache:new U}),We=$t;var zt=(e,t={})=>({"Content-Type":"application/json",...e?.accessToken&&{Authorization:`Bearer ${e?.accessToken}`},...t}),Jt=async(e,t)=>{if(!e.ok){let r=await e.text();throw new Error(r)}return t==="file"?e.blob():t==="json"?e.json():t==="text"?e.text():null},Xe=async({url:e,auth:t,body:r,method:n="GET",headers:i={},responseType:s="json"})=>{let u={method:n,headers:zt(t,i),...r?{body:r instanceof FormData?r:JSON.stringify(r)}:{}},o=await fetch(e,u);return Jt(o,s)},$e=e=>Xe({...e,method:"GET"}),he=e=>Xe({...e,method:"POST"});var de,pe="https://api.dtect.io/security",q="",j="",ye="",Zt="20000000-aaaa-bbbb-cccc-000000000002",X,k={isLoading:!1},ze=De;function $(){let e=window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"),t=document.querySelector("#dtect-h-captcha");return!!(de&&(t||e))}function Ee(){return!!(q&&j)}async function Ht({behaviorKey:e}){let t=await P.load({apiKey:e,endpoint:["https://fp.dtect.io",P.defaultEndpoint],scriptUrlPattern:["https://fp.dtect.io/web/v<version>/<apiKey>/loader_v<loaderVersion>.js",P.defaultScriptUrlPattern]});if(await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:ye,size:"invisible"}),t)de=t;else throw new Error(h.SDK_INIT_ERROR)}async function Je(e){if(!e?.clientId||!e?.apiKey)throw new Error(h.MISSING_CREDENTIALS);let{clientId:t,apiKey:r,endpoint:n="https://api.dtect.io/security"}=e;if(pe=n,k.isLoading){if($())return X;throw new Error(h.DUPLICATE_INITIALIZATION)}if(q=t,j=r,k={...k,isLoading:!0},!Ee())throw new Error(h.MISSING_CREDENTIALS);if($())return X;let i=document.querySelector("head"),s=document.querySelector("body");if(!(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))){s?.insertAdjacentHTML("beforeend",'<div id="dtect-h-captcha" ></div>');let o=document.createElement("script");o.setAttribute("src","https://js.hcaptcha.com/1/api.js"),o.setAttribute("async","true"),o.setAttribute("defer","true"),i?.append(o)}try{let o=await We.fetchQuery({queryKey:["getKeys",t,r],queryFn:()=>$e({url:`${n}/client/config`,headers:{"client-id":q,"x-api-key":j}})});if(o?.automationKey&&o?.behaviorKey)return ye=o.automationKey,Ht({...o}).then(()=>({getSecurityResult:me,getSecurityToken:Re,SecurityAPIError:ze})).catch(a=>{throw new Error(a.message)});throw new Error}catch(o){if(o instanceof Error){if(o?.message?.includes("maintenance_mode"))throw new Error(h.MAINTENANCE_MODE);if([h.INVALID_API_KEY,h.UNAUTHORIZED].includes(o?.message))throw new Error(h.INVALID_CREDENTIALS)}throw new Error(h.SDK_INIT_ERROR)}finally{k={...k,isLoading:!1}}}async function Ze(){let e=new Promise(i=>{let s=de?.get();i(s)}),t=new Promise(async i=>{(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))&&i({response:Zt}),document.querySelector("#dtect-h-captcha")||await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:ye,size:"invisible"});let o=window?.hcaptcha?.execute({async:!0});i(o)}),[r,n]=await Promise.all([t,e]);return{behaviorRequestId:n?.requestId,behaviorToken:n?.sealedResult,automationToken:r?.response}}async function me(e){if(!$())throw new Error(h.NOT_INITIALIZED);if(!Ee())throw new Error(h.MISSING_CREDENTIALS);if(!e||!e?.projectId?.trim())throw new Error(h.FAILED_TO_GET_SECURITY_RESULT);try{let t=await Ze();if(t?.behaviorToken&&t?.behaviorRequestId&&t?.automationToken){let r={...e,projectId:e?.projectId?.trim(),visitorId:e?.visitorId?.trim()||Q(),visitorData:{behaviorToken:t.behaviorToken,automationToken:t.automationToken,behaviorRequestId:t.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.11"},n=await he({url:`${pe}/client/check/results`,body:{...r},headers:{"client-id":q,"x-api-key":j}});if(n?.results?.dtectScore)return n}throw new Error(h.INTERNAL_SERVER_ERROR)}catch(t){if(t instanceof Error){if(t?.message?.includes("maintenance_mode"))throw new Error(h.MAINTENANCE_MODE);if(t?.message?.includes("rate-limited")||t?.message?.includes("429"))throw new Error(h.RATE_LIMIT_REACHED);switch(t?.message){case P.ERROR_RATE_LIMIT:throw new Error(h.RATE_LIMIT_REACHED);default:throw new Error(h.INTERNAL_SERVER_ERROR)}}throw new Error(h.FAILED_TO_GET_SECURITY_RESULT)}}async function Re(e){if(!$())throw new Error(h.NOT_INITIALIZED);if(!Ee())throw new Error(h.MISSING_CREDENTIALS);if(!e||!e?.projectId?.trim())throw new Error(h.FAILED_TO_GET_SECURITY_TOKEN);try{let t=await Ze();if(t?.behaviorToken&&t?.behaviorRequestId&&t?.automationToken){let r={...e,projectId:e.projectId?.trim(),visitorId:e.visitorId?.trim()||Q(),visitorData:{behaviorToken:t.behaviorToken,automationToken:t.automationToken,behaviorRequestId:t.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.11"},n=await he({url:`${pe}/client/check/token`,body:{...r},headers:{"client-id":q,"x-api-key":j}});if(n?.token)return n}throw new Error(h.INTERNAL_SERVER_ERROR)}catch(t){if(t instanceof Error){if(t?.message?.includes("maintenance_mode"))throw new Error(h.MAINTENANCE_MODE);if(t?.message?.includes("rate-limited"))throw new Error(h.RATE_LIMIT_REACHED);switch(t?.message){case P.ERROR_RATE_LIMIT:throw new Error(h.RATE_LIMIT_REACHED);default:throw new Error(h.INTERNAL_SERVER_ERROR)}}throw new Error(h.FAILED_TO_GET_SECURITY_TOKEN)}}X={init:Je,getSecurityResult:me,getSecurityToken:Re};var er=X;
|
|
1
|
+
"use strict";var M=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Ie=Object.prototype.hasOwnProperty;var he=(r,e)=>{for(var n in e)M(r,n,{get:e[n],enumerable:!0})},Oe=(r,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of Te(e))!Ie.call(r,t)&&t!==n&&M(r,t,{get:()=>e[t],enumerable:!(o=_e(e,t))||o.enumerable});return r};var pe=r=>Oe(M({},"__esModule",{value:!0}),r);var ar={};he(ar,{SecurityAPIError:()=>se,default:()=>ir,getSecurityResult:()=>Q,getSecurityToken:()=>Z,init:()=>ue});module.exports=pe(ar);var v=function(){return v=Object.assign||function(e){for(var n,o=1,t=arguments.length;o<t;o++){n=arguments[o];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},v.apply(this,arguments)};function $(r,e){var n={};for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&e.indexOf(o)<0&&(n[o]=r[o]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var t=0,o=Object.getOwnPropertySymbols(r);t<o.length;t++)e.indexOf(o[t])<0&&Object.prototype.propertyIsEnumerable.call(r,o[t])&&(n[o[t]]=r[o[t]]);return n}function J(r,e,n){if(n||arguments.length===2)for(var o=0,t=e.length,i;o<t;o++)(i||!(o in e))&&(i||(i=Array.prototype.slice.call(e,0,o)),i[o]=e[o]);return r.concat(i||Array.prototype.slice.call(e))}function de(r,e){return function(n,o){return Object.prototype.hasOwnProperty.call(n,o)}(r,e)?r[e]:void 0}function ye(r,e,n,o){var t,i=document,u="securitypolicyviolation",a=function(I){var E=new URL(r,location.href),s=I.blockedURI;s!==E.href&&s!==E.protocol.slice(0,-1)&&s!==E.origin||(t=I,l())};i.addEventListener(u,a);var l=function(){return i.removeEventListener(u,a)};return o?.then(l,l),Promise.resolve().then(e).then(function(I){return l(),I},function(I){return new Promise(function(E){var s=new MessageChannel;s.port1.onmessage=function(){return E()},s.port2.postMessage(null)}).then(function(){if(l(),t)return n(t);throw I})})}var me={default:"endpoint"},we={default:"tlsEndpoint"},Ae="Client timeout",Ne="Network connection error",ve="Network request aborted",De="Response cannot be parsed",S="Blocked by CSP",k="The endpoint parameter is not a valid URL";function m(r){for(var e="",n=0;n<r.length;++n)if(n>0){var o=r[n].toLowerCase();o!==r[n]?e+=" ".concat(o):e+=r[n]}else e+=r[n].toUpperCase();return e}var Pe=m("WrongRegion"),be=m("SubscriptionNotActive"),ge=m("UnsupportedVersion"),Le=m("InstallationMethodRestricted"),xe=m("HostnameRestricted"),Ue=m("IntegrationFailed"),j="API key required",z="API key not found",C="API key expired",Me="Request cannot be parsed",Se="Request failed",ke="Request failed to process",je="Too many requests, rate limit exceeded",Ge="Not available for this origin",Fe="Not available with restricted header",Ke=j,Ve=z,Be=C,qe="3.11.6",P="Failed to load the JS script of the agent",G="9319";function Ye(r,e){var n,o,t,i,u,a,l,I=[],E=(n=function(T){var _=J([],T,!0);return{current:function(){return _[0]},postpone:function(){var R=_.shift();R!==void 0&&_.push(R)},exclude:function(){_.shift()}}}(r),i=100,u=3e3,a=0,o=function(){return Math.random()*Math.min(u,i*Math.pow(2,a++))},t=new Set,[n.current(),function(T,_){var R,h=_ instanceof Error?_.message:"";if(h===S||h===k)n.exclude(),R=0;else if(h===G)n.exclude();else if(h===P){var y=Date.now()-T.getTime()<50,d=n.current();d&&y&&!t.has(d)&&(t.add(d),R=0),n.postpone()}else n.postpone();var N=n.current();return N===void 0?void 0:[N,R??T.getTime()+o()-Date.now()]}]),s=E[0],O=E[1];if(s===void 0)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var p=function(T){var _=new Date,R=function(y){return I.push({url:T,startedAt:_,finishedAt:new Date,error:y})},h=e(T);return h.then(function(){return R()},R),h.catch(function(y){if(l!=null||(l=y),I.length>=5)throw l;var d=O(_,y);if(!d)throw l;var N,fe=d[0],le=d[1];return(N=le,new Promise(function(Re){return setTimeout(Re,N)})).then(function(){return p(fe)})})};return p(s).then(function(T){return[T,I]})}var H="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",Xe=H;function We(r){var e;r.scriptUrlPattern;var n=r.token,o=r.apiKey,t=o===void 0?n:o,i=$(r,["scriptUrlPattern","token","apiKey"]),u=(e=de(r,"scriptUrlPattern"))!==null&&e!==void 0?e:H,a=function(){var E=[],s=function(){E.push({time:new Date,state:document.visibilityState})},O=function(p,T,_,R){return p.addEventListener(T,_,R),function(){return p.removeEventListener(T,_,R)}}(document,"visibilitychange",s);return s(),[E,O]}(),l=a[0],I=a[1];return Promise.resolve().then(function(){if(!t||typeof t!="string")throw new Error(j);var E=function(s,O){return(Array.isArray(s)?s:[s]).map(function(p){return function(T,_){var R=encodeURIComponent;return T.replace(/<[^<>]+>/g,function(h){return h==="<version>"?"3":h==="<apiKey>"?R(_):h==="<loaderVersion>"?R(qe):h})}(String(p),O)})}(u,t);return Ye(E,Qe)}).catch(function(E){throw I(),function(s){return s instanceof Error&&s.message===G?new Error(P):s}(E)}).then(function(E){var s=E[0],O=E[1];return I(),s.load(v(v({},i),{ldi:{attempts:O,visibilityStates:l}}))})}function Qe(r){return ye(r,function(){return function(e){return new Promise(function(n,o){if(function(a){if(URL.prototype)try{return new URL(a,location.href),!1}catch(l){if(l instanceof Error&&l.name==="TypeError")return!0;throw l}}(e))throw new Error(k);var t=document.createElement("script"),i=function(){var a;return(a=t.parentNode)===null||a===void 0?void 0:a.removeChild(t)},u=document.head||document.getElementsByTagName("head")[0];t.onload=function(){i(),n()},t.onerror=function(){i(),o(new Error(P))},t.async=!0,t.src=e,u.appendChild(t)})}(r)},function(){throw new Error(S)}).then(Ze)}function Ze(){var r=window,e="__fpjs_p_l_b",n=r[e];if(function(o,t){var i,u=(i=Object.getOwnPropertyDescriptor)===null||i===void 0?void 0:i.call(Object,o,t);u?.configurable?delete o[t]:u&&!u.writable||(o[t]=void 0)}(r,e),typeof n?.load!="function")throw new Error(G);return n}var w={load:We,defaultScriptUrlPattern:Xe,ERROR_SCRIPT_LOAD_FAIL:P,ERROR_API_KEY_EXPIRED:C,ERROR_API_KEY_INVALID:z,ERROR_API_KEY_MISSING:j,ERROR_BAD_REQUEST_FORMAT:Me,ERROR_BAD_RESPONSE_FORMAT:De,ERROR_CLIENT_TIMEOUT:Ae,ERROR_CSP_BLOCK:S,ERROR_FORBIDDEN_ENDPOINT:xe,ERROR_FORBIDDEN_HEADER:Fe,ERROR_FORBIDDEN_ORIGIN:Ge,ERROR_GENERAL_SERVER_FAILURE:Se,ERROR_INSTALLATION_METHOD_RESTRICTED:Le,ERROR_INTEGRATION_FAILURE:Ue,ERROR_INVALID_ENDPOINT:k,ERROR_NETWORK_ABORT:ve,ERROR_NETWORK_CONNECTION:Ne,ERROR_RATE_LIMIT:je,ERROR_SERVER_TIMEOUT:ke,ERROR_SUBSCRIPTION_NOT_ACTIVE:be,ERROR_TOKEN_EXPIRED:Be,ERROR_TOKEN_INVALID:Ve,ERROR_TOKEN_MISSING:Ke,ERROR_UNSUPPORTED_VERSION:ge,ERROR_WRONG_REGION:Pe,defaultEndpoint:me,defaultTlsEndpoint:we};var f=[];for(let r=0;r<256;++r)f.push((r+256).toString(16).slice(1));function ee(r,e=0){return(f[r[e+0]]+f[r[e+1]]+f[r[e+2]]+f[r[e+3]]+"-"+f[r[e+4]]+f[r[e+5]]+"-"+f[r[e+6]]+f[r[e+7]]+"-"+f[r[e+8]]+f[r[e+9]]+"-"+f[r[e+10]]+f[r[e+11]]+f[r[e+12]]+f[r[e+13]]+f[r[e+14]]+f[r[e+15]]).toLowerCase()}var F,$e=new Uint8Array(16);function K(){if(!F){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");F=crypto.getRandomValues.bind(crypto)}return F($e)}var Je=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),V={randomUUID:Je};function ze(r,e,n){if(V.randomUUID&&!e&&!r)return V.randomUUID();r=r||{};let o=r.random??r.rng?.()??K();if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let t=0;t<16;++t)e[n+t]=o[t];return e}return ee(o)}var b=ze;var Ce={UNAUTHORIZED:"Unauthorized"},He={EXPIRED:"EXPIRED_TOKEN",INVALID_API_KEY:"INVALID_API_KEY",MISSING_AUTHENTICATION_TOKEN:"MISSING_AUTHENTICATION_TOKEN"},re={INTERNAL_SERVER_ERROR:"Internal Server Error during API Request",MISSING_CREDENTIALS:"Missing Public Client ID or Public API Key",MAINTENANCE_MODE:"API Under Maintenance",RATE_LIMIT_REACHED:"Too many requests. Rate limit exceeded"},ne={SDK_INIT_ERROR:"Internal Server Error during SDK Initialization",DUPLICATE_INITIALIZATION:"Multiple SDK Initializations Detected",NOT_INITIALIZED:"SDK Not Initialized"},oe={INVALID_CREDENTIALS:"Invalid Public Client ID or Public API Key"},te={FAILED_TO_GET_SECURITY_RESULT:"Failed to Retrieve Security Result"},ie={FAILED_TO_GET_SECURITY_TOKEN:" Failed to Generate Security Token"},c={...Ce,...He,...re,...ne,...oe,...te,...ie},ae={...re,...ne,...oe,...te,...ie};var er=(r,e={})=>({"Content-Type":"application/json",...r?.accessToken&&{Authorization:`Bearer ${r?.accessToken}`},...e}),rr=async(r,e)=>{if(!r.ok){let n=await r.text();throw new Error(n)}return e==="file"?r.blob():e==="json"?r.json():e==="text"?r.text():null},nr=async({url:r,auth:e,body:n,method:o="GET",headers:t={},responseType:i="json"})=>{let u={method:o,headers:er(e,t),...n?{body:n instanceof FormData?n:JSON.stringify(n)}:{}},a=await fetch(r,u);return rr(a,i)};var B=r=>nr({...r,method:"POST"});var q,Y="https://api.dtect.io/security",A="",U="",ce="7166bf18-b91e-407a-84fc-d57ac104de98",X,g,or="20000000-aaaa-bbbb-cccc-000000000002",L,D={isLoading:!1},se=ae;function x(){let r=window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"),e=document.querySelector("#dtect-h-captcha");return!!(q&&(e||r))}function W(){return!!(A&&U)}async function tr({behaviorKey:r}){let e=await w.load({apiKey:r,endpoint:["https://fp.dtect.io",w.defaultEndpoint],scriptUrlPattern:["https://fp.dtect.io/web/v<version>/<apiKey>/loader_v<loaderVersion>.js",w.defaultScriptUrlPattern]});if(await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:ce,size:"invisible"}),e)q=e;else throw new Error(c.SDK_INIT_ERROR)}async function ue(r){if(!r?.clientId||!r?.apiKey)throw new Error(c.MISSING_CREDENTIALS);X=performance.now();let{clientId:e,apiKey:n,endpoint:o="https://api.dtect.io/security"}=r;if(Y=o,D.isLoading){if(x())return L;throw new Error(c.DUPLICATE_INITIALIZATION)}if(A=e,U=n,D={...D,isLoading:!0},!W())throw new Error(c.MISSING_CREDENTIALS);if(x())return L;let t=document.querySelector("head"),i=document.querySelector("body");if(!(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))){i?.insertAdjacentHTML("beforeend",'<div id="dtect-h-captcha" ></div>');let a=document.createElement("script");a.setAttribute("src","https://js.hcaptcha.com/1/api.js"),a.setAttribute("async","true"),a.setAttribute("defer","true"),t?.append(a)}try{return tr({behaviorKey:"bwDZ0V3Zrb4SB6g4lZwW"}).then(()=>({getSecurityResult:Q,getSecurityToken:Z,SecurityAPIError:se})).catch(a=>{throw new Error(a.message)})}catch(a){if(a instanceof Error){if(a?.message?.includes("maintenance_mode"))throw new Error(c.MAINTENANCE_MODE);if([c.INVALID_API_KEY,c.UNAUTHORIZED].includes(a?.message))throw new Error(c.INVALID_CREDENTIALS)}throw new Error(c.SDK_INIT_ERROR)}finally{D={...D,isLoading:!1}}}async function Ee(){let r=new Promise(t=>{let i=q?.get();t(i)}),e=new Promise(async t=>{(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))&&t({response:or}),document.querySelector("#dtect-h-captcha")||await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:ce,size:"invisible"});let a=window?.hcaptcha?.execute({async:!0});t(a)}),[n,o]=await Promise.all([e,r]);return{behaviorRequestId:o?.requestId,behaviorToken:o?.sealedResult,automationToken:n?.response}}async function Q(r){if(!x())throw new Error(c.NOT_INITIALIZED);if(!W())throw new Error(c.MISSING_CREDENTIALS);if(!r||!r?.projectId?.trim())throw new Error(c.FAILED_TO_GET_SECURITY_RESULT);try{let e=await Ee();if(e?.behaviorToken&&e?.behaviorRequestId&&e?.automationToken){g=performance.now();let n=(g-X).toFixed(),o={...r,projectId:r?.projectId?.trim(),visitorId:r?.visitorId?.trim()||b(),visitorData:{behaviorToken:e.behaviorToken,automationToken:e.automationToken,behaviorRequestId:e.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.12"},t=await B({url:`${Y}/client/check/results?clientId=${A}&diff=${n}`,body:{...o},headers:{"client-id":A,"x-api-key":U}});if(t?.results?.dtectScore)return t}throw new Error(c.INTERNAL_SERVER_ERROR)}catch(e){if(e instanceof Error){if(e?.message?.includes("maintenance_mode"))throw new Error(c.MAINTENANCE_MODE);if(e?.message?.includes("rate-limited")||e?.message?.includes("429"))throw new Error(c.RATE_LIMIT_REACHED);switch(e?.message){case w.ERROR_RATE_LIMIT:throw new Error(c.RATE_LIMIT_REACHED);default:throw new Error(c.INTERNAL_SERVER_ERROR)}}throw new Error(c.FAILED_TO_GET_SECURITY_RESULT)}}async function Z(r){if(!x())throw new Error(c.NOT_INITIALIZED);if(!W())throw new Error(c.MISSING_CREDENTIALS);if(!r||!r?.projectId?.trim())throw new Error(c.FAILED_TO_GET_SECURITY_TOKEN);try{let e=await Ee();if(e?.behaviorToken&&e?.behaviorRequestId&&e?.automationToken){g=performance.now();let n=(g-X).toFixed(),o={...r,projectId:r.projectId?.trim(),visitorId:r.visitorId?.trim()||b(),visitorData:{behaviorToken:e.behaviorToken,automationToken:e.automationToken,behaviorRequestId:e.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.12"},t=await B({url:`${Y}/client/check/token?clientId=${A}&diff=${n}`,body:{...o},headers:{"client-id":A,"x-api-key":U}});if(t?.token)return t}throw new Error(c.INTERNAL_SERVER_ERROR)}catch(e){if(e instanceof Error){if(e?.message?.includes("maintenance_mode"))throw new Error(c.MAINTENANCE_MODE);if(e?.message?.includes("rate-limited"))throw new Error(c.RATE_LIMIT_REACHED);switch(e?.message){case w.ERROR_RATE_LIMIT:throw new Error(c.RATE_LIMIT_REACHED);default:throw new Error(c.INTERNAL_SERVER_ERROR)}}throw new Error(c.FAILED_TO_GET_SECURITY_TOKEN)}}L={init:ue,getSecurityResult:Q,getSecurityToken:Z};var ir=L;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var M=function(){return M=Object.assign||function(t){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(t[s]=r[s])}return t},M.apply(this,arguments)};function Ee(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function me(e,t,r){if(r||arguments.length===2)for(var n=0,i=t.length,s;n<i;n++)(s||!(n in t))&&(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))}function Ze(e,t){return function(r,n){return Object.prototype.hasOwnProperty.call(r,n)}(e,t)?e[t]:void 0}function He(e,t,r,n){var i,s=document,u="securitypolicyviolation",o=function(E){var l=new URL(e,location.href),d=E.blockedURI;d!==l.href&&d!==l.protocol.slice(0,-1)&&d!==l.origin||(i=E,a())};s.addEventListener(u,o);var a=function(){return s.removeEventListener(u,o)};return n?.then(a,a),Promise.resolve().then(t).then(function(E){return a(),E},function(E){return new Promise(function(l){var d=new MessageChannel;d.port1.onmessage=function(){return l()},d.port2.postMessage(null)}).then(function(){if(a(),i)return r(i);throw E})})}var et={default:"endpoint"},tt={default:"tlsEndpoint"},rt="Client timeout",nt="Network connection error",it="Network request aborted",ot="Response cannot be parsed",J="Blocked by CSP",Z="The endpoint parameter is not a valid URL";function A(e){for(var t="",r=0;r<e.length;++r)if(r>0){var n=e[r].toLowerCase();n!==e[r]?t+=" ".concat(n):t+=e[r]}else t+=e[r].toUpperCase();return t}var st=A("WrongRegion"),at=A("SubscriptionNotActive"),ut=A("UnsupportedVersion"),ct=A("InstallationMethodRestricted"),lt=A("HostnameRestricted"),ft=A("IntegrationFailed"),H="API key required",Re="API key not found",Te="API key expired",ht="Request cannot be parsed",dt="Request failed",pt="Request failed to process",yt="Too many requests, rate limit exceeded",Et="Not available for this origin",mt="Not available with restricted header",Rt=H,Tt=Re,Ot=Te,It="3.11.6",K="Failed to load the JS script of the agent",ee="9319";function _t(e,t){var r,n,i,s,u,o,a,E=[],l=(r=function(f){var c=me([],f,!0);return{current:function(){return c[0]},postpone:function(){var p=c.shift();p!==void 0&&c.push(p)},exclude:function(){c.shift()}}}(e),s=100,u=3e3,o=0,n=function(){return Math.random()*Math.min(u,s*Math.pow(2,o++))},i=new Set,[r.current(),function(f,c){var p,y=c instanceof Error?c.message:"";if(y===J||y===Z)r.exclude(),p=0;else if(y===ee)r.exclude();else if(y===K){var T=Date.now()-f.getTime()<50,O=r.current();O&&T&&!i.has(O)&&(i.add(O),p=0),r.postpone()}else r.postpone();var w=r.current();return w===void 0?void 0:[w,p??f.getTime()+n()-Date.now()]}]),d=l[0],_=l[1];if(d===void 0)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var v=function(f){var c=new Date,p=function(T){return E.push({url:f,startedAt:c,finishedAt:new Date,error:T})},y=t(f);return y.then(function(){return p()},p),y.catch(function(T){if(a!=null||(a=T),E.length>=5)throw a;var O=_(c,T);if(!O)throw a;var w,z=O[0],ze=O[1];return(w=ze,new Promise(function(Je){return setTimeout(Je,w)})).then(function(){return v(z)})})};return v(d).then(function(f){return[f,E]})}var Oe="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",vt=Oe;function wt(e){var t;e.scriptUrlPattern;var r=e.token,n=e.apiKey,i=n===void 0?r:n,s=Ee(e,["scriptUrlPattern","token","apiKey"]),u=(t=Ze(e,"scriptUrlPattern"))!==null&&t!==void 0?t:Oe,o=function(){var l=[],d=function(){l.push({time:new Date,state:document.visibilityState})},_=function(v,f,c,p){return v.addEventListener(f,c,p),function(){return v.removeEventListener(f,c,p)}}(document,"visibilitychange",d);return d(),[l,_]}(),a=o[0],E=o[1];return Promise.resolve().then(function(){if(!i||typeof i!="string")throw new Error(H);var l=function(d,_){return(Array.isArray(d)?d:[d]).map(function(v){return function(f,c){var p=encodeURIComponent;return f.replace(/<[^<>]+>/g,function(y){return y==="<version>"?"3":y==="<apiKey>"?p(c):y==="<loaderVersion>"?p(It):y})}(String(v),_)})}(u,i);return _t(l,gt)}).catch(function(l){throw E(),function(d){return d instanceof Error&&d.message===ee?new Error(K):d}(l)}).then(function(l){var d=l[0],_=l[1];return E(),d.load(M(M({},s),{ldi:{attempts:_,visibilityStates:a}}))})}function gt(e){return He(e,function(){return function(t){return new Promise(function(r,n){if(function(o){if(URL.prototype)try{return new URL(o,location.href),!1}catch(a){if(a instanceof Error&&a.name==="TypeError")return!0;throw a}}(t))throw new Error(Z);var i=document.createElement("script"),s=function(){var o;return(o=i.parentNode)===null||o===void 0?void 0:o.removeChild(i)},u=document.head||document.getElementsByTagName("head")[0];i.onload=function(){s(),r()},i.onerror=function(){s(),n(new Error(K))},i.async=!0,i.src=t,u.appendChild(i)})}(e)},function(){throw new Error(J)}).then(bt)}function bt(){var e=window,t="__fpjs_p_l_b",r=e[t];if(function(n,i){var s,u=(s=Object.getOwnPropertyDescriptor)===null||s===void 0?void 0:s.call(Object,n,i);u?.configurable?delete n[i]:u&&!u.writable||(n[i]=void 0)}(e,t),typeof r?.load!="function")throw new Error(ee);return r}var P={load:wt,defaultScriptUrlPattern:vt,ERROR_SCRIPT_LOAD_FAIL:K,ERROR_API_KEY_EXPIRED:Te,ERROR_API_KEY_INVALID:Re,ERROR_API_KEY_MISSING:H,ERROR_BAD_REQUEST_FORMAT:ht,ERROR_BAD_RESPONSE_FORMAT:ot,ERROR_CLIENT_TIMEOUT:rt,ERROR_CSP_BLOCK:J,ERROR_FORBIDDEN_ENDPOINT:lt,ERROR_FORBIDDEN_HEADER:mt,ERROR_FORBIDDEN_ORIGIN:Et,ERROR_GENERAL_SERVER_FAILURE:dt,ERROR_INSTALLATION_METHOD_RESTRICTED:ct,ERROR_INTEGRATION_FAILURE:ft,ERROR_INVALID_ENDPOINT:Z,ERROR_NETWORK_ABORT:it,ERROR_NETWORK_CONNECTION:nt,ERROR_RATE_LIMIT:yt,ERROR_SERVER_TIMEOUT:pt,ERROR_SUBSCRIPTION_NOT_ACTIVE:at,ERROR_TOKEN_EXPIRED:Ot,ERROR_TOKEN_INVALID:Tt,ERROR_TOKEN_MISSING:Rt,ERROR_UNSUPPORTED_VERSION:ut,ERROR_WRONG_REGION:st,defaultEndpoint:et,defaultTlsEndpoint:tt};var R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function Ie(e,t=0){return(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase()}var te,At=new Uint8Array(16);function re(){if(!te){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");te=crypto.getRandomValues.bind(crypto)}return te(At)}var Pt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ne={randomUUID:Pt};function Nt(e,t,r){if(ne.randomUUID&&!t&&!e)return ne.randomUUID();e=e||{};let n=e.random??e.rng?.()??re();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){if(r=r||0,r<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)t[r+i]=n[i];return t}return Ie(n)}var Q=Nt;var Dt={UNAUTHORIZED:"Unauthorized"},St={EXPIRED:"EXPIRED_TOKEN",INVALID_API_KEY:"INVALID_API_KEY",MISSING_AUTHENTICATION_TOKEN:"MISSING_AUTHENTICATION_TOKEN"},_e={INTERNAL_SERVER_ERROR:"Internal Server Error during API Request",MISSING_CREDENTIALS:"Missing Public Client ID or Public API Key",MAINTENANCE_MODE:"API Under Maintenance",RATE_LIMIT_REACHED:"Too many requests. Rate limit exceeded"},ve={SDK_INIT_ERROR:"Internal Server Error during SDK Initialization",DUPLICATE_INITIALIZATION:"Multiple SDK Initializations Detected",NOT_INITIALIZED:"SDK Not Initialized"},we={INVALID_CREDENTIALS:"Invalid Public Client ID or Public API Key"},ge={FAILED_TO_GET_SECURITY_RESULT:"Failed to Retrieve Security Result"},be={FAILED_TO_GET_SECURITY_TOKEN:" Failed to Generate Security Token"},h={...Dt,...St,..._e,...ve,...we,...ge,...be},Ae={..._e,...ve,...we,...ge,...be};var g=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var b=typeof window>"u"||"Deno"in globalThis;function I(){}function De(e,t){return typeof e=="function"?e(t):e}function Se(e){return typeof e=="number"&&e>=0&&e!==1/0}function Me(e,t){return Math.max(e+(t||0)-Date.now(),0)}function oe(e,t){return typeof e=="function"?e(t):e}function xe(e,t){return typeof e=="function"?e(t):e}function se(e,t){let{type:r="all",exact:n,fetchStatus:i,predicate:s,queryKey:u,stale:o}=e;if(u){if(n){if(t.queryHash!==x(u,t.options))return!1}else if(!D(t.queryKey,u))return!1}if(r!=="all"){let a=t.isActive();if(r==="active"&&!a||r==="inactive"&&a)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||i&&i!==t.state.fetchStatus||s&&!s(t))}function ae(e,t){let{exact:r,status:n,predicate:i,mutationKey:s}=e;if(s){if(!t.options.mutationKey)return!1;if(r){if(N(t.options.mutationKey)!==N(s))return!1}else if(!D(t.options.mutationKey,s))return!1}return!(n&&t.state.status!==n||i&&!i(t))}function x(e,t){return(t?.queryKeyHashFn||N)(e)}function N(e){return JSON.stringify(e,(t,r)=>ie(r)?Object.keys(r).sort().reduce((n,i)=>(n[i]=r[i],n),{}):r)}function D(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(r=>!D(e[r],t[r])):!1}function Le(e,t){if(e===t)return e;let r=Pe(e)&&Pe(t);if(r||ie(e)&&ie(t)){let n=r?e:Object.keys(e),i=n.length,s=r?t:Object.keys(t),u=s.length,o=r?[]:{},a=0;for(let E=0;E<u;E++){let l=r?E:s[E];(!r&&n.includes(l)||r)&&e[l]===void 0&&t[l]===void 0?(o[l]=void 0,a++):(o[l]=Le(e[l],t[l]),o[l]===e[l]&&e[l]!==void 0&&a++)}return i===u&&a===i?e:o}return t}function Pe(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ie(e){if(!Ne(e))return!1;let t=e.constructor;if(t===void 0)return!0;let r=t.prototype;return!(!Ne(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ne(e){return Object.prototype.toString.call(e)==="[object Object]"}function Fe(e){return new Promise(t=>{setTimeout(t,e)})}function Ue(e,t,r){return typeof r.structuralSharing=="function"?r.structuralSharing(e,t):r.structuralSharing!==!1?Le(e,t):t}function ke(e,t,r=0){let n=[...e,t];return r&&n.length>r?n.slice(1):n}function qe(e,t,r=0){let n=[t,...e];return r&&n.length>r?n.slice(0,-1):n}var L=Symbol();function G(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===L?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}var Mt=class extends g{#e;#t;#r;constructor(){super(),this.#r=e=>{if(!b&&window.addEventListener){let t=()=>e();return window.addEventListener("visibilitychange",t,!1),()=>{window.removeEventListener("visibilitychange",t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(t=>{typeof t=="boolean"?this.setFocused(t):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},B=new Mt;var xt=class extends g{#e=!0;#t;#r;constructor(){super(),this.#r=e=>{if(!b&&window.addEventListener){let t=()=>e(!0),r=()=>e(!1);return window.addEventListener("online",t,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",t),window.removeEventListener("offline",r)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#r=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(r=>{r(e)}))}isOnline(){return this.#e}},S=new xt;function je(){let e,t,r=new Promise((i,s)=>{e=i,t=s});r.status="pending",r.catch(()=>{});function n(i){Object.assign(r,i),delete r.resolve,delete r.reject}return r.resolve=i=>{n({status:"fulfilled",value:i}),e(i)},r.reject=i=>{n({status:"rejected",reason:i}),t(i)},r}function Lt(e){return Math.min(1e3*2**e,3e4)}function ue(e){return(e??"online")==="online"?S.isOnline():!0}var Ke=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function V(e){return e instanceof Ke}function C(e){let t=!1,r=0,n=!1,i,s=je(),u=c=>{n||(_(new Ke(c)),e.abort?.())},o=()=>{t=!0},a=()=>{t=!1},E=()=>B.isFocused()&&(e.networkMode==="always"||S.isOnline())&&e.canRun(),l=()=>ue(e.networkMode)&&e.canRun(),d=c=>{n||(n=!0,e.onSuccess?.(c),i?.(),s.resolve(c))},_=c=>{n||(n=!0,e.onError?.(c),i?.(),s.reject(c))},v=()=>new Promise(c=>{i=p=>{(n||E())&&c(p)},e.onPause?.()}).then(()=>{i=void 0,n||e.onContinue?.()}),f=()=>{if(n)return;let c,p=r===0?e.initialPromise:void 0;try{c=p??e.fn()}catch(y){c=Promise.reject(y)}Promise.resolve(c).then(d).catch(y=>{if(n)return;let T=e.retry??(b?0:3),O=e.retryDelay??Lt,w=typeof O=="function"?O(r,y):O,z=T===!0||typeof T=="number"&&r<T||typeof T=="function"&&T(r,y);if(t||!z){_(y);return}r++,e.onFail?.(r,y),Fe(w).then(()=>E()?void 0:v()).then(()=>{t?_(y):f()})})};return{promise:s,cancel:u,continue:()=>(i?.(),s),cancelRetry:o,continueRetry:a,canStart:l,start:()=>(l()?f():v().then(f),s)}}function Ft(){let e=[],t=0,r=o=>{o()},n=o=>{o()},i=o=>setTimeout(o,0),s=o=>{t?e.push(o):i(()=>{r(o)})},u=()=>{let o=e;e=[],o.length&&i(()=>{n(()=>{o.forEach(a=>{r(a)})})})};return{batch:o=>{let a;t++;try{a=o()}finally{t--,t||u()}return a},batchCalls:o=>(...a)=>{s(()=>{o(...a)})},schedule:s,setNotifyFunction:o=>{r=o},setBatchNotifyFunction:o=>{n=o},setScheduler:o=>{i=o}}}var m=Ft();var Y=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Se(this.gcTime)&&(this.#e=setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(b?1/0:5*60*1e3))}clearGcTimeout(){this.#e&&(clearTimeout(this.#e),this.#e=void 0)}};var Qe=class extends Y{#e;#t;#r;#n;#s;#o;constructor(e){super(),this.#o=!1,this.#s=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.cache,this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=kt(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#n?.promise}setOptions(e){this.options={...this.#s,...e},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(e,t){let r=Ue(this.state.data,e,this.options);return this.#i({data:r,type:"success",dataUpdatedAt:t?.updatedAt,manual:t?.manual}),r}setState(e,t){this.#i({type:"setState",state:e,setStateOptions:t})}cancel(e){let t=this.#n?.promise;return this.#n?.cancel(e),t?t.then(I).catch(I):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>xe(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===L||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStale(){return this.state.isInvalidated?!0:this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0}isStaleByTime(e=0){return this.state.isInvalidated||this.state.data===void 0||!Me(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(t=>t.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#n?.continue()}onOnline(){this.observers.find(t=>t.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#n?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#n&&(this.#o?this.#n.cancel({revert:!0}):this.#n.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#i({type:"invalidate"})}fetch(e,t){if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#n)return this.#n.continueRetry(),this.#n.promise}if(e&&this.setOptions(e),!this.options.queryFn){let o=this.observers.find(a=>a.options.queryFn);o&&this.setOptions(o.options)}let r=new AbortController,n=o=>{Object.defineProperty(o,"signal",{enumerable:!0,get:()=>(this.#o=!0,r.signal)})},i=()=>{let o=G(this.options,t),a={queryKey:this.queryKey,meta:this.meta};return n(a),this.#o=!1,this.options.persister?this.options.persister(o,a,this):o(a)},s={fetchOptions:t,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:i};n(s),this.options.behavior?.onFetch(s,this),this.#t=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==s.fetchOptions?.meta)&&this.#i({type:"fetch",meta:s.fetchOptions?.meta});let u=o=>{V(o)&&o.silent||this.#i({type:"error",error:o}),V(o)||(this.#r.config.onError?.(o,this),this.#r.config.onSettled?.(this.state.data,o,this)),this.scheduleGc()};return this.#n=C({initialPromise:t?.initialPromise,fn:s.fetchFn,abort:r.abort.bind(r),onSuccess:o=>{if(o===void 0){u(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(o)}catch(a){u(a);return}this.#r.config.onSuccess?.(o,this),this.#r.config.onSettled?.(o,this.state.error,this),this.scheduleGc()},onError:u,onFail:(o,a)=>{this.#i({type:"failed",failureCount:o,error:a})},onPause:()=>{this.#i({type:"pause"})},onContinue:()=>{this.#i({type:"continue"})},retry:s.options.retry,retryDelay:s.options.retryDelay,networkMode:s.options.networkMode,canRun:()=>!0}),this.#n.start()}#i(e){let t=r=>{switch(e.type){case"failed":return{...r,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ut(r.data,this.options),fetchMeta:e.meta??null};case"success":return{...r,data:e.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:e.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!e.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":let n=e.error;return V(n)&&n.revert&&this.#t?{...this.#t,fetchStatus:"idle"}:{...r,error:n,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:n,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...e.state}}};this.state=t(this.state),m.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:e})})}};function Ut(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ue(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function kt(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,r=t!==void 0,n=r?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:r?n??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}var F=class extends g{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,r){let n=t.queryKey,i=t.queryHash??x(n,t),s=this.get(i);return s||(s=new Qe({cache:this,queryKey:n,queryHash:i,options:e.defaultQueryOptions(t),state:r,defaultOptions:e.getQueryDefaults(n)}),this.add(s)),s}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:"added",query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:"removed",query:e}))}clear(){m.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(r=>se(t,r))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(r=>se(e,r)):t}notify(e){m.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){m.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){m.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}};var Ge=class extends Y{#e;#t;#r;constructor(e){super(),this.mutationId=e.mutationId,this.#t=e.mutationCache,this.#e=[],this.state=e.state||qt(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#e.includes(e)||(this.#e.push(e),this.clearGcTimeout(),this.#t.notify({type:"observerAdded",mutation:this,observer:e}))}removeObserver(e){this.#e=this.#e.filter(t=>t!==e),this.scheduleGc(),this.#t.notify({type:"observerRemoved",mutation:this,observer:e})}optionalRemove(){this.#e.length||(this.state.status==="pending"?this.scheduleGc():this.#t.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){this.#r=C({fn:()=>this.options.mutationFn?this.options.mutationFn(e):Promise.reject(new Error("No mutationFn found")),onFail:(n,i)=>{this.#n({type:"failed",failureCount:n,error:i})},onPause:()=>{this.#n({type:"pause"})},onContinue:()=>{this.#n({type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#t.canRun(this)});let t=this.state.status==="pending",r=!this.#r.canStart();try{if(!t){this.#n({type:"pending",variables:e,isPaused:r}),await this.#t.config.onMutate?.(e,this);let i=await this.options.onMutate?.(e);i!==this.state.context&&this.#n({type:"pending",context:i,variables:e,isPaused:r})}let n=await this.#r.start();return await this.#t.config.onSuccess?.(n,e,this.state.context,this),await this.options.onSuccess?.(n,e,this.state.context),await this.#t.config.onSettled?.(n,null,this.state.variables,this.state.context,this),await this.options.onSettled?.(n,null,e,this.state.context),this.#n({type:"success",data:n}),n}catch(n){try{throw await this.#t.config.onError?.(n,e,this.state.context,this),await this.options.onError?.(n,e,this.state.context),await this.#t.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this),await this.options.onSettled?.(void 0,n,e,this.state.context),n}finally{this.#n({type:"error",error:n})}}finally{this.#t.runNext(this)}}#n(e){let t=r=>{switch(e.type){case"failed":return{...r,failureCount:e.failureCount,failureReason:e.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:"pending",variables:e.variables,submittedAt:Date.now()};case"success":return{...r,data:e.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:e.error,failureCount:r.failureCount+1,failureReason:e.error,isPaused:!1,status:"error"}}};this.state=t(this.state),m.batch(()=>{this.#e.forEach(r=>{r.onMutationUpdate(e)}),this.#t.notify({mutation:this,type:"updated",action:e})})}};function qt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var U=class extends g{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(e,t,r){let n=new Ge({mutationCache:this,mutationId:++this.#r,options:e.defaultMutationOptions(t),state:r});return this.add(n),n}add(e){this.#e.add(e);let t=W(e);if(typeof t=="string"){let r=this.#t.get(t);r?r.push(e):this.#t.set(t,[e])}this.notify({type:"added",mutation:e})}remove(e){if(this.#e.delete(e)){let t=W(e);if(typeof t=="string"){let r=this.#t.get(t);if(r)if(r.length>1){let n=r.indexOf(e);n!==-1&&r.splice(n,1)}else r[0]===e&&this.#t.delete(t)}}this.notify({type:"removed",mutation:e})}canRun(e){let t=W(e);if(typeof t=="string"){let n=this.#t.get(t)?.find(i=>i.state.status==="pending");return!n||n===e}else return!0}runNext(e){let t=W(e);return typeof t=="string"?this.#t.get(t)?.find(n=>n!==e&&n.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){m.batch(()=>{this.#e.forEach(e=>{this.notify({type:"removed",mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(r=>ae(t,r))}findAll(e={}){return this.getAll().filter(t=>ae(e,t))}notify(e){m.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(t=>t.state.isPaused);return m.batch(()=>Promise.all(e.map(t=>t.continue().catch(I))))}};function W(e){return e.options.scope?.id}function ce(e){return{onFetch:(t,r)=>{let n=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,s=t.state.data?.pages||[],u=t.state.data?.pageParams||[],o={pages:[],pageParams:[]},a=0,E=async()=>{let l=!1,d=f=>{Object.defineProperty(f,"signal",{enumerable:!0,get:()=>(t.signal.aborted?l=!0:t.signal.addEventListener("abort",()=>{l=!0}),t.signal)})},_=G(t.options,t.fetchOptions),v=async(f,c,p)=>{if(l)return Promise.reject();if(c==null&&f.pages.length)return Promise.resolve(f);let y={queryKey:t.queryKey,pageParam:c,direction:p?"backward":"forward",meta:t.options.meta};d(y);let T=await _(y),{maxPages:O}=t.options,w=p?qe:ke;return{pages:w(f.pages,T,O),pageParams:w(f.pageParams,c,O)}};if(i&&s.length){let f=i==="backward",c=f?jt:Be,p={pages:s,pageParams:u},y=c(n,p);o=await v(p,y,f)}else{let f=e??s.length;do{let c=a===0?u[0]??n.initialPageParam:Be(n,o);if(a>0&&c==null)break;o=await v(o,c),a++}while(a<f)}return o};t.options.persister?t.fetchFn=()=>t.options.persister?.(E,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},r):t.fetchFn=E}}}function Be(e,{pages:t,pageParams:r}){let n=t.length-1;return t.length>0?e.getNextPageParam(t[n],t,r[n],r):void 0}function jt(e,{pages:t,pageParams:r}){return t.length>0?e.getPreviousPageParam?.(t[0],t,r[0],r):void 0}var le=class{#e;#t;#r;#n;#s;#o;#i;#a;constructor(e={}){this.#e=e.queryCache||new F,this.#t=e.mutationCache||new U,this.#r=e.defaultOptions||{},this.#n=new Map,this.#s=new Map,this.#o=0}mount(){this.#o++,this.#o===1&&(this.#i=B.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=S.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#o--,this.#o===0&&(this.#i?.(),this.#i=void 0,this.#a?.(),this.#a=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return this.#t.findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),r=this.#e.build(this,t),n=r.state.data;return n===void 0?this.fetchQuery(e):(e.revalidateIfStale&&r.isStaleByTime(oe(t.staleTime,r))&&this.prefetchQuery(t),Promise.resolve(n))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:t,state:r})=>{let n=r.data;return[t,n]})}setQueryData(e,t,r){let n=this.defaultQueryOptions({queryKey:e}),s=this.#e.get(n.queryHash)?.state.data,u=De(t,s);if(u!==void 0)return this.#e.build(this,n).setData(u,{...r,manual:!0})}setQueriesData(e,t,r){return m.batch(()=>this.#e.findAll(e).map(({queryKey:n})=>[n,this.setQueryData(n,t,r)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;m.batch(()=>{t.findAll(e).forEach(r=>{t.remove(r)})})}resetQueries(e,t){let r=this.#e,n={type:"active",...e};return m.batch(()=>(r.findAll(e).forEach(i=>{i.reset()}),this.refetchQueries(n,t)))}cancelQueries(e,t={}){let r={revert:!0,...t},n=m.batch(()=>this.#e.findAll(e).map(i=>i.cancel(r)));return Promise.all(n).then(I).catch(I)}invalidateQueries(e,t={}){return m.batch(()=>{if(this.#e.findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none")return Promise.resolve();let r={...e,type:e?.refetchType??e?.type??"active"};return this.refetchQueries(r,t)})}refetchQueries(e,t={}){let r={...t,cancelRefetch:t.cancelRefetch??!0},n=m.batch(()=>this.#e.findAll(e).filter(i=>!i.isDisabled()).map(i=>{let s=i.fetch(void 0,r);return r.throwOnError||(s=s.catch(I)),i.state.fetchStatus==="paused"?Promise.resolve():s}));return Promise.all(n).then(I)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let r=this.#e.build(this,t);return r.isStaleByTime(oe(t.staleTime,r))?r.fetch(t):Promise.resolve(r.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(I).catch(I)}fetchInfiniteQuery(e){return e.behavior=ce(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(I).catch(I)}ensureInfiniteQueryData(e){return e.behavior=ce(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return S.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(e){this.#r=e}setQueryDefaults(e,t){this.#n.set(N(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#n.values()],r={};return t.forEach(n=>{D(e,n.queryKey)&&Object.assign(r,n.defaultOptions)}),r}setMutationDefaults(e,t){this.#s.set(N(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#s.values()],r={};return t.forEach(n=>{D(e,n.mutationKey)&&(r={...r,...n.defaultOptions})}),r}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#r.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=x(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===L&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#r.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var Kt=new le({defaultOptions:{queries:{staleTime:3e4}},queryCache:new F({onError:(e,t)=>{}}),mutationCache:new U}),Ve=Kt;var Qt=(e,t={})=>({"Content-Type":"application/json",...e?.accessToken&&{Authorization:`Bearer ${e?.accessToken}`},...t}),Gt=async(e,t)=>{if(!e.ok){let r=await e.text();throw new Error(r)}return t==="file"?e.blob():t==="json"?e.json():t==="text"?e.text():null},Ce=async({url:e,auth:t,body:r,method:n="GET",headers:i={},responseType:s="json"})=>{let u={method:n,headers:Qt(t,i),...r?{body:r instanceof FormData?r:JSON.stringify(r)}:{}},o=await fetch(e,u);return Gt(o,s)},Ye=e=>Ce({...e,method:"GET"}),fe=e=>Ce({...e,method:"POST"});var he,de="https://api.dtect.io/security",q="",j="",pe="",Bt="20000000-aaaa-bbbb-cccc-000000000002",X,k={isLoading:!1},Vt=Ae;function $(){let e=window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"),t=document.querySelector("#dtect-h-captcha");return!!(he&&(t||e))}function ye(){return!!(q&&j)}async function Ct({behaviorKey:e}){let t=await P.load({apiKey:e,endpoint:["https://fp.dtect.io",P.defaultEndpoint],scriptUrlPattern:["https://fp.dtect.io/web/v<version>/<apiKey>/loader_v<loaderVersion>.js",P.defaultScriptUrlPattern]});if(await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:pe,size:"invisible"}),t)he=t;else throw new Error(h.SDK_INIT_ERROR)}async function Yt(e){if(!e?.clientId||!e?.apiKey)throw new Error(h.MISSING_CREDENTIALS);let{clientId:t,apiKey:r,endpoint:n="https://api.dtect.io/security"}=e;if(de=n,k.isLoading){if($())return X;throw new Error(h.DUPLICATE_INITIALIZATION)}if(q=t,j=r,k={...k,isLoading:!0},!ye())throw new Error(h.MISSING_CREDENTIALS);if($())return X;let i=document.querySelector("head"),s=document.querySelector("body");if(!(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))){s?.insertAdjacentHTML("beforeend",'<div id="dtect-h-captcha" ></div>');let o=document.createElement("script");o.setAttribute("src","https://js.hcaptcha.com/1/api.js"),o.setAttribute("async","true"),o.setAttribute("defer","true"),i?.append(o)}try{let o=await Ve.fetchQuery({queryKey:["getKeys",t,r],queryFn:()=>Ye({url:`${n}/client/config`,headers:{"client-id":q,"x-api-key":j}})});if(o?.automationKey&&o?.behaviorKey)return pe=o.automationKey,Ct({...o}).then(()=>({getSecurityResult:Xe,getSecurityToken:$e,SecurityAPIError:Vt})).catch(a=>{throw new Error(a.message)});throw new Error}catch(o){if(o instanceof Error){if(o?.message?.includes("maintenance_mode"))throw new Error(h.MAINTENANCE_MODE);if([h.INVALID_API_KEY,h.UNAUTHORIZED].includes(o?.message))throw new Error(h.INVALID_CREDENTIALS)}throw new Error(h.SDK_INIT_ERROR)}finally{k={...k,isLoading:!1}}}async function We(){let e=new Promise(i=>{let s=he?.get();i(s)}),t=new Promise(async i=>{(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))&&i({response:Bt}),document.querySelector("#dtect-h-captcha")||await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:pe,size:"invisible"});let o=window?.hcaptcha?.execute({async:!0});i(o)}),[r,n]=await Promise.all([t,e]);return{behaviorRequestId:n?.requestId,behaviorToken:n?.sealedResult,automationToken:r?.response}}async function Xe(e){if(!$())throw new Error(h.NOT_INITIALIZED);if(!ye())throw new Error(h.MISSING_CREDENTIALS);if(!e||!e?.projectId?.trim())throw new Error(h.FAILED_TO_GET_SECURITY_RESULT);try{let t=await We();if(t?.behaviorToken&&t?.behaviorRequestId&&t?.automationToken){let r={...e,projectId:e?.projectId?.trim(),visitorId:e?.visitorId?.trim()||Q(),visitorData:{behaviorToken:t.behaviorToken,automationToken:t.automationToken,behaviorRequestId:t.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.11"},n=await fe({url:`${de}/client/check/results`,body:{...r},headers:{"client-id":q,"x-api-key":j}});if(n?.results?.dtectScore)return n}throw new Error(h.INTERNAL_SERVER_ERROR)}catch(t){if(t instanceof Error){if(t?.message?.includes("maintenance_mode"))throw new Error(h.MAINTENANCE_MODE);if(t?.message?.includes("rate-limited")||t?.message?.includes("429"))throw new Error(h.RATE_LIMIT_REACHED);switch(t?.message){case P.ERROR_RATE_LIMIT:throw new Error(h.RATE_LIMIT_REACHED);default:throw new Error(h.INTERNAL_SERVER_ERROR)}}throw new Error(h.FAILED_TO_GET_SECURITY_RESULT)}}async function $e(e){if(!$())throw new Error(h.NOT_INITIALIZED);if(!ye())throw new Error(h.MISSING_CREDENTIALS);if(!e||!e?.projectId?.trim())throw new Error(h.FAILED_TO_GET_SECURITY_TOKEN);try{let t=await We();if(t?.behaviorToken&&t?.behaviorRequestId&&t?.automationToken){let r={...e,projectId:e.projectId?.trim(),visitorId:e.visitorId?.trim()||Q(),visitorData:{behaviorToken:t.behaviorToken,automationToken:t.automationToken,behaviorRequestId:t.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.11"},n=await fe({url:`${de}/client/check/token`,body:{...r},headers:{"client-id":q,"x-api-key":j}});if(n?.token)return n}throw new Error(h.INTERNAL_SERVER_ERROR)}catch(t){if(t instanceof Error){if(t?.message?.includes("maintenance_mode"))throw new Error(h.MAINTENANCE_MODE);if(t?.message?.includes("rate-limited"))throw new Error(h.RATE_LIMIT_REACHED);switch(t?.message){case P.ERROR_RATE_LIMIT:throw new Error(h.RATE_LIMIT_REACHED);default:throw new Error(h.INTERNAL_SERVER_ERROR)}}throw new Error(h.FAILED_TO_GET_SECURITY_TOKEN)}}X={init:Yt,getSecurityResult:Xe,getSecurityToken:$e};var Cn=X;export{Vt as SecurityAPIError,Cn as default,Xe as getSecurityResult,$e as getSecurityToken,Yt as init};
|
|
1
|
+
var v=function(){return v=Object.assign||function(e){for(var n,o=1,t=arguments.length;o<t;o++){n=arguments[o];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},v.apply(this,arguments)};function W(r,e){var n={};for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&e.indexOf(o)<0&&(n[o]=r[o]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var t=0,o=Object.getOwnPropertySymbols(r);t<o.length;t++)e.indexOf(o[t])<0&&Object.prototype.propertyIsEnumerable.call(r,o[t])&&(n[o[t]]=r[o[t]]);return n}function Q(r,e,n){if(n||arguments.length===2)for(var o=0,t=e.length,i;o<t;o++)(i||!(o in e))&&(i||(i=Array.prototype.slice.call(e,0,o)),i[o]=e[o]);return r.concat(i||Array.prototype.slice.call(e))}function fe(r,e){return function(n,o){return Object.prototype.hasOwnProperty.call(n,o)}(r,e)?r[e]:void 0}function le(r,e,n,o){var t,i=document,u="securitypolicyviolation",a=function(I){var E=new URL(r,location.href),s=I.blockedURI;s!==E.href&&s!==E.protocol.slice(0,-1)&&s!==E.origin||(t=I,l())};i.addEventListener(u,a);var l=function(){return i.removeEventListener(u,a)};return o?.then(l,l),Promise.resolve().then(e).then(function(I){return l(),I},function(I){return new Promise(function(E){var s=new MessageChannel;s.port1.onmessage=function(){return E()},s.port2.postMessage(null)}).then(function(){if(l(),t)return n(t);throw I})})}var Re={default:"endpoint"},_e={default:"tlsEndpoint"},Te="Client timeout",Ie="Network connection error",he="Network request aborted",Oe="Response cannot be parsed",M="Blocked by CSP",S="The endpoint parameter is not a valid URL";function m(r){for(var e="",n=0;n<r.length;++n)if(n>0){var o=r[n].toLowerCase();o!==r[n]?e+=" ".concat(o):e+=r[n]}else e+=r[n].toUpperCase();return e}var pe=m("WrongRegion"),de=m("SubscriptionNotActive"),ye=m("UnsupportedVersion"),me=m("InstallationMethodRestricted"),we=m("HostnameRestricted"),Ae=m("IntegrationFailed"),k="API key required",Z="API key not found",$="API key expired",Ne="Request cannot be parsed",ve="Request failed",De="Request failed to process",Pe="Too many requests, rate limit exceeded",be="Not available for this origin",ge="Not available with restricted header",Le=k,xe=Z,Ue=$,Me="3.11.6",P="Failed to load the JS script of the agent",j="9319";function Se(r,e){var n,o,t,i,u,a,l,I=[],E=(n=function(T){var _=Q([],T,!0);return{current:function(){return _[0]},postpone:function(){var R=_.shift();R!==void 0&&_.push(R)},exclude:function(){_.shift()}}}(r),i=100,u=3e3,a=0,o=function(){return Math.random()*Math.min(u,i*Math.pow(2,a++))},t=new Set,[n.current(),function(T,_){var R,h=_ instanceof Error?_.message:"";if(h===M||h===S)n.exclude(),R=0;else if(h===j)n.exclude();else if(h===P){var y=Date.now()-T.getTime()<50,d=n.current();d&&y&&!t.has(d)&&(t.add(d),R=0),n.postpone()}else n.postpone();var N=n.current();return N===void 0?void 0:[N,R??T.getTime()+o()-Date.now()]}]),s=E[0],O=E[1];if(s===void 0)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var p=function(T){var _=new Date,R=function(y){return I.push({url:T,startedAt:_,finishedAt:new Date,error:y})},h=e(T);return h.then(function(){return R()},R),h.catch(function(y){if(l!=null||(l=y),I.length>=5)throw l;var d=O(_,y);if(!d)throw l;var N,se=d[0],ue=d[1];return(N=ue,new Promise(function(Ee){return setTimeout(Ee,N)})).then(function(){return p(se)})})};return p(s).then(function(T){return[T,I]})}var J="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",ke=J;function je(r){var e;r.scriptUrlPattern;var n=r.token,o=r.apiKey,t=o===void 0?n:o,i=W(r,["scriptUrlPattern","token","apiKey"]),u=(e=fe(r,"scriptUrlPattern"))!==null&&e!==void 0?e:J,a=function(){var E=[],s=function(){E.push({time:new Date,state:document.visibilityState})},O=function(p,T,_,R){return p.addEventListener(T,_,R),function(){return p.removeEventListener(T,_,R)}}(document,"visibilitychange",s);return s(),[E,O]}(),l=a[0],I=a[1];return Promise.resolve().then(function(){if(!t||typeof t!="string")throw new Error(k);var E=function(s,O){return(Array.isArray(s)?s:[s]).map(function(p){return function(T,_){var R=encodeURIComponent;return T.replace(/<[^<>]+>/g,function(h){return h==="<version>"?"3":h==="<apiKey>"?R(_):h==="<loaderVersion>"?R(Me):h})}(String(p),O)})}(u,t);return Se(E,Ge)}).catch(function(E){throw I(),function(s){return s instanceof Error&&s.message===j?new Error(P):s}(E)}).then(function(E){var s=E[0],O=E[1];return I(),s.load(v(v({},i),{ldi:{attempts:O,visibilityStates:l}}))})}function Ge(r){return le(r,function(){return function(e){return new Promise(function(n,o){if(function(a){if(URL.prototype)try{return new URL(a,location.href),!1}catch(l){if(l instanceof Error&&l.name==="TypeError")return!0;throw l}}(e))throw new Error(S);var t=document.createElement("script"),i=function(){var a;return(a=t.parentNode)===null||a===void 0?void 0:a.removeChild(t)},u=document.head||document.getElementsByTagName("head")[0];t.onload=function(){i(),n()},t.onerror=function(){i(),o(new Error(P))},t.async=!0,t.src=e,u.appendChild(t)})}(r)},function(){throw new Error(M)}).then(Fe)}function Fe(){var r=window,e="__fpjs_p_l_b",n=r[e];if(function(o,t){var i,u=(i=Object.getOwnPropertyDescriptor)===null||i===void 0?void 0:i.call(Object,o,t);u?.configurable?delete o[t]:u&&!u.writable||(o[t]=void 0)}(r,e),typeof n?.load!="function")throw new Error(j);return n}var w={load:je,defaultScriptUrlPattern:ke,ERROR_SCRIPT_LOAD_FAIL:P,ERROR_API_KEY_EXPIRED:$,ERROR_API_KEY_INVALID:Z,ERROR_API_KEY_MISSING:k,ERROR_BAD_REQUEST_FORMAT:Ne,ERROR_BAD_RESPONSE_FORMAT:Oe,ERROR_CLIENT_TIMEOUT:Te,ERROR_CSP_BLOCK:M,ERROR_FORBIDDEN_ENDPOINT:we,ERROR_FORBIDDEN_HEADER:ge,ERROR_FORBIDDEN_ORIGIN:be,ERROR_GENERAL_SERVER_FAILURE:ve,ERROR_INSTALLATION_METHOD_RESTRICTED:me,ERROR_INTEGRATION_FAILURE:Ae,ERROR_INVALID_ENDPOINT:S,ERROR_NETWORK_ABORT:he,ERROR_NETWORK_CONNECTION:Ie,ERROR_RATE_LIMIT:Pe,ERROR_SERVER_TIMEOUT:De,ERROR_SUBSCRIPTION_NOT_ACTIVE:de,ERROR_TOKEN_EXPIRED:Ue,ERROR_TOKEN_INVALID:xe,ERROR_TOKEN_MISSING:Le,ERROR_UNSUPPORTED_VERSION:ye,ERROR_WRONG_REGION:pe,defaultEndpoint:Re,defaultTlsEndpoint:_e};var f=[];for(let r=0;r<256;++r)f.push((r+256).toString(16).slice(1));function z(r,e=0){return(f[r[e+0]]+f[r[e+1]]+f[r[e+2]]+f[r[e+3]]+"-"+f[r[e+4]]+f[r[e+5]]+"-"+f[r[e+6]]+f[r[e+7]]+"-"+f[r[e+8]]+f[r[e+9]]+"-"+f[r[e+10]]+f[r[e+11]]+f[r[e+12]]+f[r[e+13]]+f[r[e+14]]+f[r[e+15]]).toLowerCase()}var G,Ke=new Uint8Array(16);function F(){if(!G){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");G=crypto.getRandomValues.bind(crypto)}return G(Ke)}var Ve=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),K={randomUUID:Ve};function Be(r,e,n){if(K.randomUUID&&!e&&!r)return K.randomUUID();r=r||{};let o=r.random??r.rng?.()??F();if(o.length<16)throw new Error("Random bytes length must be >= 16");if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let t=0;t<16;++t)e[n+t]=o[t];return e}return z(o)}var b=Be;var qe={UNAUTHORIZED:"Unauthorized"},Ye={EXPIRED:"EXPIRED_TOKEN",INVALID_API_KEY:"INVALID_API_KEY",MISSING_AUTHENTICATION_TOKEN:"MISSING_AUTHENTICATION_TOKEN"},C={INTERNAL_SERVER_ERROR:"Internal Server Error during API Request",MISSING_CREDENTIALS:"Missing Public Client ID or Public API Key",MAINTENANCE_MODE:"API Under Maintenance",RATE_LIMIT_REACHED:"Too many requests. Rate limit exceeded"},H={SDK_INIT_ERROR:"Internal Server Error during SDK Initialization",DUPLICATE_INITIALIZATION:"Multiple SDK Initializations Detected",NOT_INITIALIZED:"SDK Not Initialized"},ee={INVALID_CREDENTIALS:"Invalid Public Client ID or Public API Key"},re={FAILED_TO_GET_SECURITY_RESULT:"Failed to Retrieve Security Result"},ne={FAILED_TO_GET_SECURITY_TOKEN:" Failed to Generate Security Token"},c={...qe,...Ye,...C,...H,...ee,...re,...ne},oe={...C,...H,...ee,...re,...ne};var Xe=(r,e={})=>({"Content-Type":"application/json",...r?.accessToken&&{Authorization:`Bearer ${r?.accessToken}`},...e}),We=async(r,e)=>{if(!r.ok){let n=await r.text();throw new Error(n)}return e==="file"?r.blob():e==="json"?r.json():e==="text"?r.text():null},Qe=async({url:r,auth:e,body:n,method:o="GET",headers:t={},responseType:i="json"})=>{let u={method:o,headers:Xe(e,t),...n?{body:n instanceof FormData?n:JSON.stringify(n)}:{}},a=await fetch(r,u);return We(a,i)};var V=r=>Qe({...r,method:"POST"});var B,q="https://api.dtect.io/security",A="",U="",te="7166bf18-b91e-407a-84fc-d57ac104de98",Y,g,Ze="20000000-aaaa-bbbb-cccc-000000000002",L,D={isLoading:!1},$e=oe;function x(){let r=window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"),e=document.querySelector("#dtect-h-captcha");return!!(B&&(e||r))}function X(){return!!(A&&U)}async function Je({behaviorKey:r}){let e=await w.load({apiKey:r,endpoint:["https://fp.dtect.io",w.defaultEndpoint],scriptUrlPattern:["https://fp.dtect.io/web/v<version>/<apiKey>/loader_v<loaderVersion>.js",w.defaultScriptUrlPattern]});if(await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:te,size:"invisible"}),e)B=e;else throw new Error(c.SDK_INIT_ERROR)}async function ze(r){if(!r?.clientId||!r?.apiKey)throw new Error(c.MISSING_CREDENTIALS);Y=performance.now();let{clientId:e,apiKey:n,endpoint:o="https://api.dtect.io/security"}=r;if(q=o,D.isLoading){if(x())return L;throw new Error(c.DUPLICATE_INITIALIZATION)}if(A=e,U=n,D={...D,isLoading:!0},!X())throw new Error(c.MISSING_CREDENTIALS);if(x())return L;let t=document.querySelector("head"),i=document.querySelector("body");if(!(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))){i?.insertAdjacentHTML("beforeend",'<div id="dtect-h-captcha" ></div>');let a=document.createElement("script");a.setAttribute("src","https://js.hcaptcha.com/1/api.js"),a.setAttribute("async","true"),a.setAttribute("defer","true"),t?.append(a)}try{return Je({behaviorKey:"bwDZ0V3Zrb4SB6g4lZwW"}).then(()=>({getSecurityResult:ae,getSecurityToken:ce,SecurityAPIError:$e})).catch(a=>{throw new Error(a.message)})}catch(a){if(a instanceof Error){if(a?.message?.includes("maintenance_mode"))throw new Error(c.MAINTENANCE_MODE);if([c.INVALID_API_KEY,c.UNAUTHORIZED].includes(a?.message))throw new Error(c.INVALID_CREDENTIALS)}throw new Error(c.SDK_INIT_ERROR)}finally{D={...D,isLoading:!1}}}async function ie(){let r=new Promise(t=>{let i=B?.get();t(i)}),e=new Promise(async t=>{(window?.location?.href?.includes("localhost")||window?.location?.href?.includes("file:///"))&&t({response:Ze}),document.querySelector("#dtect-h-captcha")||await window?.hcaptcha?.render("dtect-h-captcha",{sitekey:te,size:"invisible"});let a=window?.hcaptcha?.execute({async:!0});t(a)}),[n,o]=await Promise.all([e,r]);return{behaviorRequestId:o?.requestId,behaviorToken:o?.sealedResult,automationToken:n?.response}}async function ae(r){if(!x())throw new Error(c.NOT_INITIALIZED);if(!X())throw new Error(c.MISSING_CREDENTIALS);if(!r||!r?.projectId?.trim())throw new Error(c.FAILED_TO_GET_SECURITY_RESULT);try{let e=await ie();if(e?.behaviorToken&&e?.behaviorRequestId&&e?.automationToken){g=performance.now();let n=(g-Y).toFixed(),o={...r,projectId:r?.projectId?.trim(),visitorId:r?.visitorId?.trim()||b(),visitorData:{behaviorToken:e.behaviorToken,automationToken:e.automationToken,behaviorRequestId:e.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.12"},t=await V({url:`${q}/client/check/results?clientId=${A}&diff=${n}`,body:{...o},headers:{"client-id":A,"x-api-key":U}});if(t?.results?.dtectScore)return t}throw new Error(c.INTERNAL_SERVER_ERROR)}catch(e){if(e instanceof Error){if(e?.message?.includes("maintenance_mode"))throw new Error(c.MAINTENANCE_MODE);if(e?.message?.includes("rate-limited")||e?.message?.includes("429"))throw new Error(c.RATE_LIMIT_REACHED);switch(e?.message){case w.ERROR_RATE_LIMIT:throw new Error(c.RATE_LIMIT_REACHED);default:throw new Error(c.INTERNAL_SERVER_ERROR)}}throw new Error(c.FAILED_TO_GET_SECURITY_RESULT)}}async function ce(r){if(!x())throw new Error(c.NOT_INITIALIZED);if(!X())throw new Error(c.MISSING_CREDENTIALS);if(!r||!r?.projectId?.trim())throw new Error(c.FAILED_TO_GET_SECURITY_TOKEN);try{let e=await ie();if(e?.behaviorToken&&e?.behaviorRequestId&&e?.automationToken){g=performance.now();let n=(g-Y).toFixed(),o={...r,projectId:r.projectId?.trim(),visitorId:r.visitorId?.trim()||b(),visitorData:{behaviorToken:e.behaviorToken,automationToken:e.automationToken,behaviorRequestId:e.behaviorRequestId,entryLink:window?.location?.href},version:"0.0.12"},t=await V({url:`${q}/client/check/token?clientId=${A}&diff=${n}`,body:{...o},headers:{"client-id":A,"x-api-key":U}});if(t?.token)return t}throw new Error(c.INTERNAL_SERVER_ERROR)}catch(e){if(e instanceof Error){if(e?.message?.includes("maintenance_mode"))throw new Error(c.MAINTENANCE_MODE);if(e?.message?.includes("rate-limited"))throw new Error(c.RATE_LIMIT_REACHED);switch(e?.message){case w.ERROR_RATE_LIMIT:throw new Error(c.RATE_LIMIT_REACHED);default:throw new Error(c.INTERNAL_SERVER_ERROR)}}throw new Error(c.FAILED_TO_GET_SECURITY_TOKEN)}}L={init:ze,getSecurityResult:ae,getSecurityToken:ce};var Kr=L;export{$e as SecurityAPIError,Kr as default,ae as getSecurityResult,ce as getSecurityToken,ze as init};
|