@digitap.ai/sync-sdk 0.1.3 → 1.0.1

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.esm.js CHANGED
@@ -1 +1 @@
1
- var e=function(){return e=Object.assign||function(e){for(var t,r=1,n=arguments.length;r<n;r++)for(var o in t=arguments[r])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};var t="Blocked by CSP",r="The endpoint parameter is not a valid URL";function n(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 o=n("WrongRegion"),i=n("SubscriptionNotActive"),a=n("UnsupportedVersion"),s=n("InstallationMethodRestricted"),c=n("HostnameRestricted"),u=n("IntegrationFailed"),d=n("NetworkRestricted"),l=n("InvalidProxyIntegrationSecret"),f="API key required",R="API key not found",p="API key expired",E="Failed to load the JS script of the agent",I="9319";function g(e,n){var o,i,a,s,c,u=[],d=(o=function(e){var t=function(e,t,r){if(r||2===arguments.length)for(var n,o=0,i=t.length;o<i;o++)!n&&o in t||(n||(n=Array.prototype.slice.call(t,0,o)),n[o]=t[o]);return e.concat(n||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),s=0,i=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,s++))},a=new Set,[o.current(),function(e,n){var s,c=n instanceof Error?n.message:"";if(c===t||c===r)o.exclude(),s=0;else if(c===I)o.exclude();else if(c===E){var u=Date.now()-e.getTime()<50,d=o.current();d&&u&&!a.has(d)&&(a.add(d),s=0),o.postpone()}else o.postpone();var l=o.current();return void 0===l?void 0:[l,null!=s?s:e.getTime()+i()-Date.now()]}]),l=d[0],f=d[1];if(void 0===l)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var R=function(e){var t=new Date,r=function(r){return u.push({url:e,startedAt:t,finishedAt:new Date,error:r})},o=n(e);return o.then((function(){return r()}),r),o.catch((function(e){if(null!=c||(c=e),u.length>=5)throw c;var r=f(t,e);if(!r)throw c;var n,o=r[0],i=r[1];return(n=i,new Promise((function(e){return setTimeout(e,n)}))).then((function(){return R(o)}))}))};return R(l).then((function(e){return[e,u]}))}var v="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js";function y(e){return function(e,t,r,n){var o,i=document,a="securitypolicyviolation",s=function(t){var r=new URL(e,location.href),n=t.blockedURI;n!==r.href&&n!==r.protocol.slice(0,-1)&&n!==r.origin||(o=t,c())};i.addEventListener(a,s);var c=function(){return i.removeEventListener(a,s)};return null==n||n.then(c,c),Promise.resolve().then(t).then((function(e){return c(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(c(),o)return r(o);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,n){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(r);var o=document.createElement("script"),i=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},a=document.head||document.getElementsByTagName("head")[0];o.onload=function(){i(),t()},o.onerror=function(){i(),n(new Error(E))},o.async=!0,o.src=e,a.appendChild(o)}))}(e)}),(function(){throw new Error(t)})).then(m)}function m(){var e=window,t="__fpjs_p_l_b",r=e[t];if(function(e,t){var r,n=null===(r=Object.getOwnPropertyDescriptor)||void 0===r?void 0:r.call(Object,e,t);(null==n?void 0:n.configurable)?delete e[t]:n&&!n.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==r?void 0:r.load))throw new Error(I);return r}var h={load:function(t){var r;t.scriptUrlPattern;var n=t.token,o=t.apiKey,i=void 0===o?n:o,a=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]])}return r}(t,["scriptUrlPattern","token","apiKey"]),s=null!==(r=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(t,"scriptUrlPattern"))&&void 0!==r?r:v,c=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},r=function(e,t,r,n){return e.addEventListener(t,r,n),function(){return e.removeEventListener(t,r,n)}}(document,"visibilitychange",t);return t(),[e,r]}(),u=c[0],d=c[1];return Promise.resolve().then((function(){if(!i||"string"!=typeof i)throw new Error(f);return g(function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var r=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?r(t):"<loaderVersion>"===e?r("3.11.8"):e}))}(String(e),t)}))}(s,i),y)})).catch((function(e){throw d(),function(e){return e instanceof Error&&e.message===I?new Error(E):e}(e)})).then((function(t){var r=t[0],n=t[1];return d(),r.load(e(e({},a),{ldi:{attempts:n,visibilityStates:u}}))}))},defaultScriptUrlPattern:v,ERROR_SCRIPT_LOAD_FAIL:E,ERROR_API_KEY_EXPIRED:p,ERROR_API_KEY_INVALID:R,ERROR_API_KEY_MISSING:f,ERROR_BAD_REQUEST_FORMAT:"Request cannot be parsed",ERROR_BAD_RESPONSE_FORMAT:"Response cannot be parsed",ERROR_CLIENT_TIMEOUT:"Client timeout",ERROR_CSP_BLOCK:t,ERROR_FORBIDDEN_ENDPOINT:c,ERROR_FORBIDDEN_HEADER:"Not available with restricted header",ERROR_FORBIDDEN_ORIGIN:"Not available for this origin",ERROR_GENERAL_SERVER_FAILURE:"Request failed",ERROR_INSTALLATION_METHOD_RESTRICTED:s,ERROR_INTEGRATION_FAILURE:u,ERROR_INVALID_ENDPOINT:r,ERROR_INVALID_PROXY_INTEGRATION_HEADERS:n("InvalidProxyIntegrationHeaders"),ERROR_INVALID_PROXY_INTEGRATION_SECRET:l,ERROR_NETWORK_ABORT:"Network request aborted",ERROR_NETWORK_CONNECTION:"Network connection error",ERROR_NETWORK_RESTRICTED:d,ERROR_RATE_LIMIT:"Too many requests, rate limit exceeded",ERROR_SERVER_TIMEOUT:"Request failed to process",ERROR_SUBSCRIPTION_NOT_ACTIVE:i,ERROR_TOKEN_EXPIRED:p,ERROR_TOKEN_INVALID:R,ERROR_TOKEN_MISSING:f,ERROR_UNSUPPORTED_VERSION:a,ERROR_WRONG_REGION:o,defaultEndpoint:{default:"endpoint"},defaultTlsEndpoint:{default:"tlsEndpoint"}};async function _(e,t){try{const r=e.replace(/-/g,"+").replace(/_/g,"/"),n=function(e){const t=atob(e);return Uint8Array.from(t,(e=>e.charCodeAt(0)))}(r+"=".repeat((4-r.length%4)%4)),o=n.slice(0,12),i=n.slice(12),a=(new TextEncoder).encode(t),s=await crypto.subtle.importKey("raw",a,{name:"AES-GCM"},!1,["decrypt"]),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},s,i);return(new TextDecoder).decode(c)}catch(e){return console.error("Decryption error:",e),null}}let O=!1;const w={dev:"https://api.digitap.work/sync/",stage:"https://apistage.digitap.work/sync/",uat:"https://apidemo.digitap.work/sync/",prod:"https://api.digitap.ai/sync/"},T={code:1001,message:"Invalid Input"},N={code:1002,message:"Internal Error, Try after some time"},A={code:1003,message:"Server Error, Try after some time"},S={code:1004,message:"Internet not connected"},P={code:1005,message:"Previous sms sync is in progress, please try after some time"},b={code:1006,message:"Sync disabled"};async function D(){return localStorage.getItem("userId")}var L={start:async function(e,t,r,n){var o="",i="";try{if(!function(e){const t=String(e).trim();if(!t)return!1;if(!/^\d+$/.test(t))return!1;try{if(e.length<18)return!0;{const e=BigInt(t),r=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807");return e>=r&&e<=n}}catch{return!1}}(r))return n({status:"error",code:T.code,message:"Invalid userId",data:{userId:r||null,deviceId:null}});if(({deviceId:o,userAgent:i}=await async function(){let e=localStorage.getItem("sync_device_id"),t=localStorage.getItem("sync_user_agent");if(!e){const r=await h.load({apiKey:"w5EseVLxhpfRzzsVj0fl",region:"ap"}),n=await r.get();e=n?.visitorId,t=n?.components?.userAgent?.value||navigator?.userAgent,localStorage.setItem("sync_device_id",e),localStorage.setItem("sync_user_agent",t)}return{deviceId:e,userAgent:t}}()),O)return n({status:"failure",code:P.code,message:"Previous sms sync is initiated for the user_id "+D()+", please try after some time",data:{userId:r,deviceId:o}});if(!navigator.onLine)return n({status:"error",code:S.code,message:S.message,data:{userId:r,deviceId:o}});O=!0,async function(e){localStorage.setItem("userId",e)}(r);const s=await async function(){const e=await fetch("https://api.ipify.org?format=json");if(!e.ok)throw new Error("Failed to fetch IP address");return(await e.json()).ip}(),{latitude:c,longitude:u}=await async function(){return new Promise((e=>{if(!navigator.geolocation)return e({latitude:0,longitude:0});navigator.geolocation.getCurrentPosition((t=>{e({latitude:t.coords.latitude,longitude:t.coords.longitude})}),(()=>{e({latitude:0,longitude:0})}),{timeout:1e4})}))}(),d={customAuthenticationToken:e,sdkVersion:"1.0.0",userId:r,ipAddress:s,location:{latitude:c,longitude:u},deviceId:o,deviceType:"WEB",userAgent:i},l=await async function(e,t){const r=await fetch(w[t]+"sdk/auth",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error("Failed to send data to API");return await r.json()}(d,t);if(200==l.code)if(l.model?.isSyncEnabled){var a="";try{console.log("data:"+l.model?.data),a=await _(l.model?.data,"PpwCKmkiEE8Q0O0FmbpZ90ZbdNypVhkp")}catch(e){return void n({status:"failure",code:N.code,message:"Internal error, "+(e.message||"Unexpected error"),data:{userId:r,deviceId:o}})}if(console.log("Decrypted:",a),null!=a&&""!=a){const e=JSON.parse(a);n({status:"success",code:200,message:"Sync Completed",data:{syncId:e?.syncConfig?.syncId||null,userId:r,deviceId:o}})}else n({status:"failure",code:N.code,message:N.message,data:{userId:r,deviceId:o}})}else n({status:"failure",code:b.code,message:b.message,data:{syncId:l.syncId||null,userId:r,deviceId:o}});else n({status:"failure",code:A.code,message:"Server error, "+l.msg,data:{syncId:l.syncId||null,userId:r,deviceId:o}})}catch(e){n({status:"failure",code:N.code,message:"Internal error, "+(e.message||"Unexpected error"),data:{userId:r,deviceId:o}})}finally{O=!1}}};export{L as default};
1
+ function e(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function t(){const e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n;const r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(c);return n}function n(e,t){return(e-t+256)%256}const r="Blocked by CSP",o="The endpoint parameter is not a valid URL",i="Handle on demand agent data error";var a="3.12.16";const s="Failed to load the JS script of the agent",c="9319";function u(e,t){oe(e,e.len+t.length),e.arr.set(t,e.len),e.len+=t.length}const d="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",l=d;function f(e,t){try{document.cookie}catch(e){if(function(e){if(!(e instanceof DOMException))return!1;const t=e.message;return Z.test(t)||ee.test(t)||te.test(t)}(e))return t;throw e}return e()}function R(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r>127)return(new TextEncoder).encode(e);t[n]=r}return t}function E(e,t,...n){e&&async function(e){try{return await e()}catch(e){return void console.error(e)}}(()=>{const r=t(...n);void 0!==r&&e(r)})}function g({level:e,message:t}){"error"===e?console.error(t):"warning"===e?console.warn(t):console.log(t)}const h="_vid";function p(e){const t=location.hostname,n=function(){var e,t;const n=window;return["buildID"in navigator,"MozAppearance"in(null!==(t=null===(e=document.documentElement)||void 0===e?void 0:e.style)&&void 0!==t?t:{}),"onmozfullscreenchange"in n,"mozInnerScreenX"in n,"CSSMozDocumentRule"in n,"CanvasCaptureMediaStream"in n].reduce((e,t)=>e+(t?1:0),0)>=4}();(function(e,t){let n=e.length-("."===e.slice(-1)?1:0);do{if(n=n>0?e.lastIndexOf(".",n-1):-1,!0===t(e.slice(n+1)))return!0}while(n>=0);return!1})(t,r=>{if(!n||!/^([^.]{1,3}\.)*[^.]+\.?$/.test(r)||r===t)return e(r)})||e()}function I(e,t){const n=[],[i,a]=function(e){const t=function(e){const t=[...e];return{current:()=>t[0],postpone(){const e=t.shift();void 0!==e&&t.push(e)},exclude(){t.shift()}}}(e),n=function(){let e=0;return()=>Math.random()*Math.min(3e3,100*Math.pow(2,e++))}(),i=new Set;return[t.current(),(e,a)=>{let u;const d=a instanceof Error?a.message:"";if(d===r||d===o)t.exclude(),u=0;else if(d===c)t.exclude();else if(d===s){const n=Date.now()-e.getTime()<50,r=t.current();r&&n&&!i.has(r)&&(i.add(r),u=0),t.postpone()}else t.postpone();const l=t.current();return void 0===l?void 0:[l,null!=u?u:e.getTime()+n()-Date.now()]}]}(e);let u;if(void 0===i)return Promise.reject(new TypeError("The list of script URL patterns is empty"));const d=e=>{const r=new Date,o=t=>n.push({url:e,startedAt:r,finishedAt:new Date,error:t}),i=t(e);return i.then(()=>o(),o),i.catch(e=>{if(null!=u||(u=e),n.length>=5)throw u;const t=a(r,e);if(!t)throw u;const[o,i]=t;return(s=i,new Promise(e=>setTimeout(e,s))).then(()=>d(o));var s})};return d(i).then(e=>[e,n])}function m(e){return e>=S&&e<S+10||e===U}const y=34,v=44,w=58,_=32,O=9,A=13,T=10,N=92,S=48,b=101,P=117,D=69,C=43,U=45,L=46,k=91,x=93,M=123,K=125,V=new Uint8Array([110,P,108,108]),B=new Uint8Array([116,114,P,b]),j=new Uint8Array([102,97,108,115,b]),F={'"':'"',"\\":"\\","\b":"b","\f":"f","\n":"n","\r":"r","\t":"t"},G=(()=>{const e=new Uint8Array(128);for(const[t,n]of Object.entries(F))e[n.charCodeAt(0)]=t.charCodeAt(0);return e})(),$=re("WrongRegion"),H=re("SubscriptionNotActive"),q=re("UnsupportedVersion"),z=re("InstallationMethodRestricted"),W=re("HostnameRestricted"),X=re("IntegrationFailed"),Y=re("NetworkRestricted"),J=re("InvalidProxyIntegrationSecret");function Q(e,t,n,r){f(()=>{const o=`${e}=${t}`,i=`expires=${new Date(Date.now()+24*n*60*60*1e3).toUTCString()}`,a=r?`domain=${r}`:"";document.cookie=[o,"path=/",i,a,"SameSite=Lax"].join("; ")},void 0)}const Z=/The document is sandboxed and lacks the 'allow-same-origin' flag/,ee=/The operation is insecure/,te=/Forbidden in a sandboxed document without the 'allow-same-origin' flag/;function ne(e,t){oe(e,e.len+1),e.arr[e.len++]=t}function re(e){let t="";for(let n=0;n<e.length;++n)if(n>0){const r=e[n].toLowerCase();r!==e[n]?t+=` ${r}`:t+=e[n]}else t+=e[n].toUpperCase();return t}function oe(e,t){if(e.arr.length<t){const n=new Uint8Array(Math.max(2*e.arr.length,t));n.set(e.arr),e.arr=n}}const ie=[3,13];function ae(t){if("function"==typeof TextDecoder){const e=(new TextDecoder).decode(t);if(e)return e}const n=e(t);return decodeURIComponent(escape(String.fromCharCode.apply(null,n)))}function se(e){return function(e,t,n,r){const o=document,i="securitypolicyviolation";let a;const s=t=>{const n=new URL(e,location.href),{blockedURI:r}=t;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(a=t,c())};o.addEventListener(i,s);const c=()=>o.removeEventListener(i,s);return null==r||r.then(c,c),Promise.resolve().then(t).then(e=>(c(),e),e=>new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(null)}).then(()=>{if(c(),a)return n(a);throw e}))}(e,()=>function(e){return new Promise((t,n)=>{if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(o);const r=document.createElement("script"),i=()=>{var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},a=document.head||document.getElementsByTagName("head")[0];r.onload=()=>{i(),t()},r.onerror=()=>{i(),n(new Error(s))},r.async=!0,r.src=e,a.appendChild(r)})}(e),()=>{throw new Error(r)}).then(t)}const ce="API key required",ue="API key not found",de="API key expired";var le={load:function(e){var t,n;const{picked:r,rest:o}=function(e,t){const n={},r={};for(const[o,i]of Object.entries(e))t.includes(o)?n[o]=i:r[o]=i;return{picked:n,rest:r}}(e,["scriptUrlPattern","token","apiKey"]),i=r.token,u=null!==(t=r.apiKey)&&void 0!==t?t:i,l=null!==(n=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(e,"scriptUrlPattern"))&&void 0!==n?n:d,[f,R]=function(){const e=[],t=()=>{e.push({time:new Date,state:document.visibilityState})},n=(r=document,o="visibilitychange",i=t,r.addEventListener(o,i,a),()=>r.removeEventListener(o,i,a));var r,o,i,a;return t(),[e,n]}();return Promise.resolve().then(()=>{if(!u||"string"!=typeof u)throw new Error("API key required");return I(function(e,t){return(Array.isArray(e)?e:[e]).map(e=>function(e,t){const n=encodeURIComponent;return e.replace(/<[^<>]+>/g,e=>"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n(a):e)}(String(e),t))}(l,u),se)}).catch(e=>{throw R(),function(e){return e instanceof Error&&e.message===c?new Error(s):e}(e)}).then(([e,t])=>(R(),e.load({...o,ldi:{attempts:t,visibilityStates:f}})))},defaultScriptUrlPattern:l,ERROR_SCRIPT_LOAD_FAIL:s,ERROR_API_KEY_EXPIRED:de,ERROR_API_KEY_INVALID:ue,ERROR_API_KEY_MISSING:ce,ERROR_BAD_REQUEST_FORMAT:"Request cannot be parsed",ERROR_BAD_RESPONSE_FORMAT:"Response cannot be parsed",ERROR_CLIENT_TIMEOUT:"Client timeout",ERROR_CSP_BLOCK:r,ERROR_FORBIDDEN_ENDPOINT:W,ERROR_FORBIDDEN_HEADER:"Not available with restricted header",ERROR_FORBIDDEN_ORIGIN:"Not available for this origin",ERROR_GENERAL_SERVER_FAILURE:"Request failed",ERROR_HANDLE_AGENT_DATA:i,ERROR_INSTALLATION_METHOD_RESTRICTED:z,ERROR_INTEGRATION_FAILURE:X,ERROR_INVALID_ENDPOINT:o,ERROR_INVALID_PROXY_INTEGRATION_HEADERS:re("InvalidProxyIntegrationHeaders"),ERROR_INVALID_PROXY_INTEGRATION_SECRET:J,ERROR_NETWORK_ABORT:"Network request aborted",ERROR_NETWORK_CONNECTION:"Network connection error",ERROR_NETWORK_RESTRICTED:Y,ERROR_PROXY_INTEGRATION_SECRET_ENVIRONMENT_MISMATCH:re("ProxyIntegrationSecretEnvironmentMismatch"),ERROR_RATE_LIMIT:"Too many requests, rate limit exceeded",ERROR_SERVER_TIMEOUT:"Request failed to process",ERROR_SUBSCRIPTION_NOT_ACTIVE:H,ERROR_TOKEN_EXPIRED:de,ERROR_TOKEN_INVALID:ue,ERROR_TOKEN_MISSING:ce,ERROR_UNSUPPORTED_VERSION:q,ERROR_WRONG_REGION:$,defaultEndpoint:{default:"endpoint"},defaultTlsEndpoint:{default:"tlsEndpoint"},handleAgentData:function(t,r={}){const{storageKey:o=h,do:a}=r;try{const r=function(t){const r=function(e){const t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r}(t);let o=r;try{o=function(t,r){const o=()=>{throw new Error("Invalid data")},i=e(t);i.length<r.length+2&&o();for(let e=0;e<r.length;++e)n(i[1+e],i[0])!==r[e]&&o();const a=1+r.length,s=n(i[a],i[0]);i.length<a+1+s+9&&o();const c=a+1+s,u=c+9,d=new ArrayBuffer(i.length-u),l=new Uint8Array(d);for(let e=0;e<l.length;++e)l[e]=i[u+e]^i[c+e%9];return d}(r,ie)}catch(e){}try{return function(t){const n={len:0,arr:new Uint8Array(128)},r=e(t);let o=0;const i=()=>(l(),r[o]===y?a():m(r[o])?s():f(V)?(o+=V.length,null):f(B)?(o+=B.length,!0):f(j)?(o+=j.length,!1):r[o]===k?c():r[o]===M?d():E()),a=()=>{for(n.len=0;o++,r[o]!==y;){if(r[o]===N){if(o++,r[o]===P){const e=parseInt(ae(r.subarray(o+1,o+5)),16);u(n,R(String.fromCharCode(e))),o+=4;continue}const e=G[r[o]];if(e){ne(n,e);continue}return E()}if(void 0===r[o])return E();ne(n,r[o])}return o++,ae(function(e){return e.arr.subarray(0,e.len)}(n))},s=()=>{const e=o;for(;r[o]===L||r[o]===b||r[o]===D||r[o]===C||m(r[o]);)o++;return Number(ae(r.subarray(e,o)))},c=()=>{const e=[];for(o++;;){if(l(),r[o]===x){o++;break}if(e.length){if(r[o]!==v)return E();o++}e.push(i())}return e},d=()=>{const e={};let t=!0;for(o++;;){if(l(),r[o]===K){o++;break}if(!t){if(r[o]!==v)return E();o++,l()}if(r[o]!==y)return E();const n=a();if(l(),r[o]!==w)return E();o++,Object.defineProperty(e,n,{value:i(),configurable:!0,enumerable:!0,writable:!0}),t=!1}return e},l=()=>{for(;r[o]===_||r[o]===T||r[o]===A||r[o]===O;)o++},f=e=>{for(let t=0;t<e.length;t++)if(r[o+t]!==e[t])return!1;return!0},E=()=>{throw new SyntaxError("Unexpected "+(o<r.length?`byte ${o}`:"end"))},g=i();return l(),void 0!==r[o]&&E(),g}(o)}catch(e){}return null}(t);null!==r?(r.visitorToken&&function(e,t){(function(e,t){p(t=>{!function(e,t){Q(e,"",-1,t)}(e,t)}),p(n=>(Q(e,t,365,n),function(e){return f(()=>{const t=`${e}=`;for(const e of document.cookie.split(";")){let n=0;for(;" "===e[n]&&n<e.length;)++n;if(e.indexOf(t)===n)return e.slice(n+t.length)}},void 0)}(e)===t))})(t,e),function(e,t){var n;try{null===(n=null===localStorage||void 0===localStorage?void 0:localStorage.setItem)||void 0===n||n.call(localStorage,e,t)}catch(e){}}(t,e)}(r.visitorToken,`${o}_t`),null==(s=r.notifications)||s.forEach(g),E(a,()=>({e:25,result:{response:r}}))):E(a,()=>({e:25,result:{error:new Error("Failed to decode response")}}))}catch(e){throw E(a,()=>({e:25,result:{error:e instanceof Error?e:new Error(String(e))}})),function(e,t,n){const r=new Error(i);return void 0!==n&&(r.raw=n),r}(0,0,e)}var s}};async function fe(e,t){try{const n=e.replace(/-/g,"+").replace(/_/g,"/"),r=function(e){const t=atob(e);return Uint8Array.from(t,e=>e.charCodeAt(0))}(n+"=".repeat((4-n.length%4)%4)),o=r.slice(0,12),i=r.slice(12),a=(new TextEncoder).encode(t),s=await crypto.subtle.importKey("raw",a,{name:"AES-GCM"},!1,["decrypt"]),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:128},s,i);return(new TextDecoder).decode(c)}catch(e){return console.error("Decryption error:",e),null}}let Re=!1;const Ee={code:1001,message:"Invalid Input"},ge={code:1002,message:"Internal Error, Try after some time"},he={code:1003,message:"Server Error, Try after some time"},pe={code:1004,message:"Internet not connected"},Ie={code:1005,message:"Previous sms sync is in progress, please try after some time"},me={code:1006,message:"Sync disabled"};function ye(e,t){let n=t;isNullOrEmpty(t)||(n=btoa(t)),sessionStorage.setItem(e,n)}function ve(e){let t=sessionStorage.getItem(e);if(!isNullOrEmpty(t))try{return atob(t)}catch(e){console.error(e)}return t}async function we(){return ve("userId")}var _e={start:async function(e,t,n,r,o){var i="",a="";try{if(!function(e){const t=String(e).trim();if(!t)return!1;if(!/^\d+$/.test(t))return!1;try{if(e.length<18)return!0;{const e=BigInt(t),n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807");return e>=n&&e<=r}}catch{return!1}}(r))return o({status:"error",code:Ee.code,message:"Invalid userId",data:{userId:r||null,deviceId:null}});if(({deviceId:i,userAgent:a}=await async function(){let e=ve("sync_device_id"),t=ve("sync_user_agent");if(!e){const n=await le.load({apiKey:"w5EseVLxhpfRzzsVj0fl",region:"ap"}),r=await n.get();e=r?.visitorId,t=r?.components?.userAgent?.value||navigator?.userAgent,ye("sync_device_id",e),ye("sync_user_agent",t)}return{deviceId:e,userAgent:t}}()),Re)return o({status:"failure",code:Ie.code,message:"Previous sms sync is initiated for the user_id "+we()+", please try after some time",data:{userId:r,deviceId:i}});if(!navigator.onLine)return o({status:"error",code:pe.code,message:pe.message,data:{userId:r,deviceId:i}});Re=!0,async function(e){ye("userId",e)}(r);const t=await async function(){const e=await fetch("https://api.ipify.org?format=json");if(!e.ok)throw new Error("Failed to fetch IP address");return(await e.json()).ip}(),{latitude:c,longitude:u}=await async function(){return new Promise(e=>{if(!navigator.geolocation)return e({latitude:0,longitude:0});navigator.geolocation.getCurrentPosition(t=>{e({latitude:t.coords.latitude,longitude:t.coords.longitude})},()=>{e({latitude:0,longitude:0})},{timeout:1e4})})}(),d={customAuthenticationToken:e,sdkVersion:"1.0.1",userId:r,ipAddress:t,location:{latitude:c,longitude:u},deviceId:i,deviceType:"WEB",userAgent:a},l=await async function(e,t,n){const r=await fetch(n+"/sync/sdk/auth",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok)throw new Error("Failed to send data to API");return await r.json()}(d,0,n);if(200==l.code)if(l.model?.isSyncEnabled){var s="";try{console.log("data:"+l.model?.data),s=await fe(l.model?.data,"PpwCKmkiEE8Q0O0FmbpZ90ZbdNypVhkp")}catch(e){return void o({status:"failure",code:ge.code,message:"Internal error, "+(e.message||"Unexpected error"),data:{userId:r,deviceId:i}})}if(console.log("Decrypted:",s),null!=s&&""!=s){const e=JSON.parse(s);o({status:"success",code:200,message:"Sync Completed",data:{syncId:e?.syncConfig?.syncId||null,userId:r,deviceId:i}})}else o({status:"failure",code:ge.code,message:ge.message,data:{userId:r,deviceId:i}})}else o({status:"failure",code:me.code,message:me.message,data:{syncId:l.syncId||null,userId:r,deviceId:i}});else o({status:"failure",code:he.code,message:"Server error, "+l.msg,data:{syncId:l.syncId||null,userId:r,deviceId:i}})}catch(e){o({status:"failure",code:ge.code,message:"Internal error, "+(e.message||"Unexpected error"),data:{userId:r,deviceId:i}})}finally{Re=!1}}};export{_e as default};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Sync=t()}(this,(function(){"use strict";var e=function(){return e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},e.apply(this,arguments)};var t="Blocked by CSP",n="The endpoint parameter is not a valid URL";function r(e){for(var t="",n=0;n<e.length;++n)if(n>0){var r=e[n].toLowerCase();r!==e[n]?t+=" ".concat(r):t+=e[n]}else t+=e[n].toUpperCase();return t}var o=r("WrongRegion"),i=r("SubscriptionNotActive"),a=r("UnsupportedVersion"),s=r("InstallationMethodRestricted"),c=r("HostnameRestricted"),u=r("IntegrationFailed"),d=r("NetworkRestricted"),l=r("InvalidProxyIntegrationSecret"),f="API key required",p="API key not found",R="API key expired",E="Failed to load the JS script of the agent",I="9319";function y(e,r){var o,i,a,s,c,u=[],d=(o=function(e){var t=function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))}([],e,!0);return{current:function(){return t[0]},postpone:function(){var e=t.shift();void 0!==e&&t.push(e)},exclude:function(){t.shift()}}}(e),s=0,i=function(){return Math.random()*Math.min(3e3,100*Math.pow(2,s++))},a=new Set,[o.current(),function(e,r){var s,c=r instanceof Error?r.message:"";if(c===t||c===n)o.exclude(),s=0;else if(c===I)o.exclude();else if(c===E){var u=Date.now()-e.getTime()<50,d=o.current();d&&u&&!a.has(d)&&(a.add(d),s=0),o.postpone()}else o.postpone();var l=o.current();return void 0===l?void 0:[l,null!=s?s:e.getTime()+i()-Date.now()]}]),l=d[0],f=d[1];if(void 0===l)return Promise.reject(new TypeError("The list of script URL patterns is empty"));var p=function(e){var t=new Date,n=function(n){return u.push({url:e,startedAt:t,finishedAt:new Date,error:n})},o=r(e);return o.then((function(){return n()}),n),o.catch((function(e){if(null!=c||(c=e),u.length>=5)throw c;var n=f(t,e);if(!n)throw c;var r,o=n[0],i=n[1];return(r=i,new Promise((function(e){return setTimeout(e,r)}))).then((function(){return p(o)}))}))};return p(l).then((function(e){return[e,u]}))}var v="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js";function g(e){return function(e,t,n,r){var o,i=document,a="securitypolicyviolation",s=function(t){var n=new URL(e,location.href),r=t.blockedURI;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(o=t,c())};i.addEventListener(a,s);var c=function(){return i.removeEventListener(a,s)};return null==r||r.then(c,c),Promise.resolve().then(t).then((function(e){return c(),e}),(function(e){return new Promise((function(e){var t=new MessageChannel;t.port1.onmessage=function(){return e()},t.port2.postMessage(null)})).then((function(){if(c(),o)return n(o);throw e}))}))}(e,(function(){return function(e){return new Promise((function(t,r){if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(n);var o=document.createElement("script"),i=function(){var e;return null===(e=o.parentNode)||void 0===e?void 0:e.removeChild(o)},a=document.head||document.getElementsByTagName("head")[0];o.onload=function(){i(),t()},o.onerror=function(){i(),r(new Error(E))},o.async=!0,o.src=e,a.appendChild(o)}))}(e)}),(function(){throw new Error(t)})).then(_)}function _(){var e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n,r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(I);return n}var h={load:function(t){var n;t.scriptUrlPattern;var r=t.token,o=t.apiKey,i=void 0===o?r:o,a=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(t,["scriptUrlPattern","token","apiKey"]),s=null!==(n=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(t,"scriptUrlPattern"))&&void 0!==n?n:v,c=function(){var e=[],t=function(){e.push({time:new Date,state:document.visibilityState})},n=function(e,t,n,r){return e.addEventListener(t,n,r),function(){return e.removeEventListener(t,n,r)}}(document,"visibilitychange",t);return t(),[e,n]}(),u=c[0],d=c[1];return Promise.resolve().then((function(){if(!i||"string"!=typeof i)throw new Error(f);return y(function(e,t){return(Array.isArray(e)?e:[e]).map((function(e){return function(e,t){var n=encodeURIComponent;return e.replace(/<[^<>]+>/g,(function(e){return"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n("3.11.8"):e}))}(String(e),t)}))}(s,i),g)})).catch((function(e){throw d(),function(e){return e instanceof Error&&e.message===I?new Error(E):e}(e)})).then((function(t){var n=t[0],r=t[1];return d(),n.load(e(e({},a),{ldi:{attempts:r,visibilityStates:u}}))}))},defaultScriptUrlPattern:v,ERROR_SCRIPT_LOAD_FAIL:E,ERROR_API_KEY_EXPIRED:R,ERROR_API_KEY_INVALID:p,ERROR_API_KEY_MISSING:f,ERROR_BAD_REQUEST_FORMAT:"Request cannot be parsed",ERROR_BAD_RESPONSE_FORMAT:"Response cannot be parsed",ERROR_CLIENT_TIMEOUT:"Client timeout",ERROR_CSP_BLOCK:t,ERROR_FORBIDDEN_ENDPOINT:c,ERROR_FORBIDDEN_HEADER:"Not available with restricted header",ERROR_FORBIDDEN_ORIGIN:"Not available for this origin",ERROR_GENERAL_SERVER_FAILURE:"Request failed",ERROR_INSTALLATION_METHOD_RESTRICTED:s,ERROR_INTEGRATION_FAILURE:u,ERROR_INVALID_ENDPOINT:n,ERROR_INVALID_PROXY_INTEGRATION_HEADERS:r("InvalidProxyIntegrationHeaders"),ERROR_INVALID_PROXY_INTEGRATION_SECRET:l,ERROR_NETWORK_ABORT:"Network request aborted",ERROR_NETWORK_CONNECTION:"Network connection error",ERROR_NETWORK_RESTRICTED:d,ERROR_RATE_LIMIT:"Too many requests, rate limit exceeded",ERROR_SERVER_TIMEOUT:"Request failed to process",ERROR_SUBSCRIPTION_NOT_ACTIVE:i,ERROR_TOKEN_EXPIRED:R,ERROR_TOKEN_INVALID:p,ERROR_TOKEN_MISSING:f,ERROR_UNSUPPORTED_VERSION:a,ERROR_WRONG_REGION:o,defaultEndpoint:{default:"endpoint"},defaultTlsEndpoint:{default:"tlsEndpoint"}};function O(e,t){const n=m();return(O=function(e,t){return n[e-=422]})(e,t)}function m(){const e=["Decryption error:","join","3811026wiKeGX","encode","byteLength","decode","Encryption error:","8ltXuoN","1775110bGCYrp","error","set","encrypt","raw","length","8994337JXUZii","3230101AGpnsF","AES-GCM","replace","6341607Uwjifv","4anbSvG","importKey","decrypt","fromCharCode","72XbWYlw","10IlsjJZ","slice","subtle","from","400248YGeOcs","8639xWTbUE"];return(m=function(){return e})()}async function N(e,t){const n=O;try{const r=e.replace(/-/g,"+")[n(442)](/_/g,"/"),o=function(e){const t=O,n=atob(e);return Uint8Array[t(422)](n,(e=>e.charCodeAt(0)))}(r+"=".repeat((4-r[n(438)]%4)%4)),i=o.slice(0,12),a=o[n(450)](12),s=(new TextEncoder).encode(t),c=await crypto.subtle[n(445)](n(437),s,{name:"AES-GCM"},!1,[n(446)]),u=await crypto.subtle.decrypt({name:n(441),iv:i,tagLength:128},c,a);return(new TextDecoder)[n(430)](u)}catch(e){return console[n(434)](n(425),e),null}}!function(e){const t=O,n=e();for(;;)try{if(471926===parseInt(t(424))/1*(parseInt(t(448))/2)+-parseInt(t(423))/3+parseInt(t(444))/4*(parseInt(t(433))/5)+-parseInt(t(427))/6+parseInt(t(440))/7*(parseInt(t(432))/8)+parseInt(t(443))/9*(-parseInt(t(449))/10)+parseInt(t(439))/11)break;n.push(n.shift())}catch(e){n.push(n.shift())}}(m);const T=D;!function(e){const t=D,n=e();for(;;)try{if(566571===parseInt(t(399))/1*(parseInt(t(375))/2)+parseInt(t(425))/3+parseInt(t(386))/4+parseInt(t(384))/5*(-parseInt(t(369))/6)+-parseInt(t(385))/7+parseInt(t(363))/8+-parseInt(t(381))/9)break;n.push(n.shift())}catch(e){n.push(n.shift())}}(L);const w=T(382),S=T(393);let A=!1;const P={dev:T(371),stage:T(377),uat:"https://apidemo.digitap.work/sync/",prod:T(407)},b={INVALID_INPUT:{code:1001,message:T(412)},INTERNAL_ERROR:{code:1002,message:"Internal Error, Try after some time"},SERVER_ERROR:{code:1003,message:"Server Error, Try after some time"},INTERNET_NOT_CONNECTED:{code:1004,message:T(387)},SYNC_IN_PROGRESS:{code:1005,message:T(392)},SYNC_DISABLED:{code:1006,message:T(417)},SYNC_CANCELLED:{code:1007,message:T(361)}};function D(e,t){const n=L();return(D=function(e,t){return n[e-=358]})(e,t)}async function C(){const e=T;return localStorage[e(389)](e(404))}function L(){const e=["Invalid userId","-9223372036854775808","3900843Ldwpqm","1.0.0","Server error, ","3340ElyFYn","843437xZMzlW","198948NZMuKo","Internet not connected","json","getItem","SERVER_ERROR","msg","Previous sms sync is in progress, please try after some time","w5EseVLxhpfRzzsVj0fl","INTERNAL_ERROR","application/json","load","model","data","11yYMPmv","parse","length","Sync Completed","error","userId","stringify","Internal error, ","https://api.digitap.ai/sync/","syncId","Unexpected error","sync_device_id","isSyncEnabled","Invalid Input","trim","test","9223372036854775807","data:","Sync disabled","SYNC_IN_PROGRESS","Previous sms sync is initiated for the user_id ","components","syncConfig","coords","geolocation","getCurrentPosition","82152XIDQrO","code","Failed to fetch IP address","sync_user_agent","Sync cancelled due to it took more time and another sync initiated","message","3404616HokQor","failure","SYNC_DISABLED","sdk/auth","WEB","setItem","3582sqILjk","log","https://api.digitap.work/sync/","get",", please try after some time","latitude","184834LyOyOV","success","https://apistage.digitap.work/sync/","visitorId"];return(L=function(){return e})()}return{start:async function(e,t,n,r){const o=T;var i="",a="";try{if(!function(e){const t=T,n=String(e)[t(413)]();if(!n)return!1;if(!/^\d+$/[t(414)](n))return!1;try{if(e[t(401)]<18)return!0;{const e=BigInt(n),r=BigInt(t(380)),o=BigInt(t(415));return e>=r&&e<=o}}catch{return!1}}(n))return r({status:o(403),code:b.INVALID_INPUT[o(358)],message:o(379),data:{userId:n||null,deviceId:null}});if(({deviceId:i,userAgent:a}=await async function(){const e=T;let t=localStorage[e(389)](e(410)),n=localStorage[e(389)]("sync_user_agent");if(!t){const r=await h[e(396)]({apiKey:S,region:"ap"}),o=await r[e(372)]();t=o?.[e(378)],n=o?.[e(420)]?.userAgent?.value||navigator?.userAgent,localStorage.setItem(e(410),t),localStorage[e(368)](e(360),n)}return{deviceId:t,userAgent:n}}()),A)return r({status:"failure",code:b[o(418)][o(358)],message:o(419)+C()+o(373),data:{userId:n,deviceId:i}});if(!navigator.onLine)return r({status:"error",code:b.INTERNET_NOT_CONNECTED[o(358)],message:b.INTERNET_NOT_CONNECTED[o(362)],data:{userId:n,deviceId:i}});A=!0,async function(e){const t=T;localStorage[t(368)](t(404),e)}(n);const c=await async function(){const e=T,t=await fetch("https://api.ipify.org?format=json");if(!t.ok)throw new Error(e(359));return(await t[e(388)]()).ip}(),{latitude:u,longitude:d}=await async function(){return new Promise((e=>{const t=D;if(!navigator[t(423)])return e({latitude:0,longitude:0});navigator[t(423)][t(424)]((n=>{const r=t;e({latitude:n[r(422)][r(374)],longitude:n[r(422)].longitude})}),(()=>{e({latitude:0,longitude:0})}),{timeout:1e4})}))}(),l={customAuthenticationToken:e,sdkVersion:w,userId:n,ipAddress:c,location:{latitude:u,longitude:d},deviceId:i,deviceType:o(367),userAgent:a},f=await async function(e,t){const n=T,r=await fetch(P[t]+n(366),{method:"POST",headers:{"Content-Type":n(395)},body:JSON[n(405)](e)});if(!r.ok)throw new Error("Failed to send data to API");return await r.json()}(l,t);if(200==f[o(358)])if(f[o(397)]?.[o(411)]){var s="";try{console[o(370)](o(416)+f[o(397)]?.data),s=await N(f[o(397)]?.[o(398)],"PpwCKmkiEE8Q0O0FmbpZ90ZbdNypVhkp")}catch(e){return void r({status:o(364),code:b.INTERNAL_ERROR[o(358)],message:o(406)+(e[o(362)]||o(409)),data:{userId:n,deviceId:i}})}if(console[o(370)]("Decrypted:",s),null!=s&&""!=s){const e=JSON[o(400)](s);r({status:o(376),code:200,message:o(402),data:{syncId:e?.[o(421)]?.[o(408)]||null,userId:n,deviceId:i}})}else r({status:o(364),code:b[o(394)][o(358)],message:b[o(394)][o(362)],data:{userId:n,deviceId:i}})}else r({status:o(364),code:b[o(365)][o(358)],message:b[o(365)][o(362)],data:{syncId:f[o(408)]||null,userId:n,deviceId:i}});else r({status:o(364),code:b[o(390)][o(358)],message:o(383)+f[o(391)],data:{syncId:f[o(408)]||null,userId:n,deviceId:i}})}catch(e){r({status:o(364),code:b[o(394)][o(358)],message:o(406)+(e.message||"Unexpected error"),data:{userId:n,deviceId:i}})}finally{A=!1}}}}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Sync=t()}(this,function(){"use strict";function e(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function t(){const e=window,t="__fpjs_p_l_b",n=e[t];if(function(e,t){var n;const r=null===(n=Object.getOwnPropertyDescriptor)||void 0===n?void 0:n.call(Object,e,t);(null==r?void 0:r.configurable)?delete e[t]:r&&!r.writable||(e[t]=void 0)}(e,t),"function"!=typeof(null==n?void 0:n.load))throw new Error(c);return n}function n(e,t){return(e-t+256)%256}const r="Blocked by CSP",o="The endpoint parameter is not a valid URL",i="Handle on demand agent data error";var s="3.12.16";const a="Failed to load the JS script of the agent",c="9319";function u(e,t){oe(e,e.len+t.length),e.arr.set(t,e.len),e.len+=t.length}const d="https://fpnpmcdn.net/v<version>/<apiKey>/loader_v<loaderVersion>.js",l=d;function f(e,t){try{document.cookie}catch(e){if(function(e){if(!(e instanceof DOMException))return!1;const t=e.message;return Z.test(t)||ee.test(t)||te.test(t)}(e))return t;throw e}return e()}function R(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r>127)return(new TextEncoder).encode(e);t[n]=r}return t}function E(e,t,...n){e&&async function(e){try{return await e()}catch(e){return void console.error(e)}}(()=>{const r=t(...n);void 0!==r&&e(r)})}function p({level:e,message:t}){"error"===e?console.error(t):"warning"===e?console.warn(t):console.log(t)}const I="_vid";function h(e){const t=location.hostname,n=function(){var e,t;const n=window;return["buildID"in navigator,"MozAppearance"in(null!==(t=null===(e=document.documentElement)||void 0===e?void 0:e.style)&&void 0!==t?t:{}),"onmozfullscreenchange"in n,"mozInnerScreenX"in n,"CSSMozDocumentRule"in n,"CanvasCaptureMediaStream"in n].reduce((e,t)=>e+(t?1:0),0)>=4}();(function(e,t){let n=e.length-("."===e.slice(-1)?1:0);do{if(n=n>0?e.lastIndexOf(".",n-1):-1,!0===t(e.slice(n+1)))return!0}while(n>=0);return!1})(t,r=>{if(!n||!/^([^.]{1,3}\.)*[^.]+\.?$/.test(r)||r===t)return e(r)})||e()}function g(e,t){const n=[],[i,s]=function(e){const t=function(e){const t=[...e];return{current:()=>t[0],postpone(){const e=t.shift();void 0!==e&&t.push(e)},exclude(){t.shift()}}}(e),n=function(){let e=0;return()=>Math.random()*Math.min(3e3,100*Math.pow(2,e++))}(),i=new Set;return[t.current(),(e,s)=>{let u;const d=s instanceof Error?s.message:"";if(d===r||d===o)t.exclude(),u=0;else if(d===c)t.exclude();else if(d===a){const n=Date.now()-e.getTime()<50,r=t.current();r&&n&&!i.has(r)&&(i.add(r),u=0),t.postpone()}else t.postpone();const l=t.current();return void 0===l?void 0:[l,null!=u?u:e.getTime()+n()-Date.now()]}]}(e);let u;if(void 0===i)return Promise.reject(new TypeError("The list of script URL patterns is empty"));const d=e=>{const r=new Date,o=t=>n.push({url:e,startedAt:r,finishedAt:new Date,error:t}),i=t(e);return i.then(()=>o(),o),i.catch(e=>{if(null!=u||(u=e),n.length>=5)throw u;const t=s(r,e);if(!t)throw u;const[o,i]=t;return(a=i,new Promise(e=>setTimeout(e,a))).then(()=>d(o));var a})};return d(i).then(e=>[e,n])}function y(e){return e>=S&&e<S+10||e===L}const m=34,_=44,v=58,w=32,O=9,N=13,T=10,A=92,S=48,D=101,b=117,C=69,P=43,L=45,U=46,k=91,x=93,M=123,V=125,K=new Uint8Array([110,b,108,108]),B=new Uint8Array([116,114,b,D]),j=new Uint8Array([102,97,108,115,D]),F={'"':'"',"\\":"\\","\b":"b","\f":"f","\n":"n","\r":"r","\t":"t"},G=(()=>{const e=new Uint8Array(128);for(const[t,n]of Object.entries(F))e[n.charCodeAt(0)]=t.charCodeAt(0);return e})(),H=re("WrongRegion"),Y=re("SubscriptionNotActive"),$=re("UnsupportedVersion"),z=re("InstallationMethodRestricted"),q=re("HostnameRestricted"),X=re("IntegrationFailed"),W=re("NetworkRestricted"),J=re("InvalidProxyIntegrationSecret");function Q(e,t,n,r){f(()=>{const o=`${e}=${t}`,i=`expires=${new Date(Date.now()+24*n*60*60*1e3).toUTCString()}`,s=r?`domain=${r}`:"";document.cookie=[o,"path=/",i,s,"SameSite=Lax"].join("; ")},void 0)}const Z=/The document is sandboxed and lacks the 'allow-same-origin' flag/,ee=/The operation is insecure/,te=/Forbidden in a sandboxed document without the 'allow-same-origin' flag/;function ne(e,t){oe(e,e.len+1),e.arr[e.len++]=t}function re(e){let t="";for(let n=0;n<e.length;++n)if(n>0){const r=e[n].toLowerCase();r!==e[n]?t+=` ${r}`:t+=e[n]}else t+=e[n].toUpperCase();return t}function oe(e,t){if(e.arr.length<t){const n=new Uint8Array(Math.max(2*e.arr.length,t));n.set(e.arr),e.arr=n}}const ie=[3,13];function se(t){if("function"==typeof TextDecoder){const e=(new TextDecoder).decode(t);if(e)return e}const n=e(t);return decodeURIComponent(escape(String.fromCharCode.apply(null,n)))}function ae(e){return function(e,t,n,r){const o=document,i="securitypolicyviolation";let s;const a=t=>{const n=new URL(e,location.href),{blockedURI:r}=t;r!==n.href&&r!==n.protocol.slice(0,-1)&&r!==n.origin||(s=t,c())};o.addEventListener(i,a);const c=()=>o.removeEventListener(i,a);return null==r||r.then(c,c),Promise.resolve().then(t).then(e=>(c(),e),e=>new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=()=>e(),t.port2.postMessage(null)}).then(()=>{if(c(),s)return n(s);throw e}))}(e,()=>function(e){return new Promise((t,n)=>{if(function(e){if(URL.prototype)try{return new URL(e,location.href),!1}catch(e){if(e instanceof Error&&"TypeError"===e.name)return!0;throw e}}(e))throw new Error(o);const r=document.createElement("script"),i=()=>{var e;return null===(e=r.parentNode)||void 0===e?void 0:e.removeChild(r)},s=document.head||document.getElementsByTagName("head")[0];r.onload=()=>{i(),t()},r.onerror=()=>{i(),n(new Error(a))},r.async=!0,r.src=e,s.appendChild(r)})}(e),()=>{throw new Error(r)}).then(t)}const ce="API key required",ue="API key not found",de="API key expired";var le={load:function(e){var t,n;const{picked:r,rest:o}=function(e,t){const n={},r={};for(const[o,i]of Object.entries(e))t.includes(o)?n[o]=i:r[o]=i;return{picked:n,rest:r}}(e,["scriptUrlPattern","token","apiKey"]),i=r.token,u=null!==(t=r.apiKey)&&void 0!==t?t:i,l=null!==(n=function(e,t){return function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(e,t)?e[t]:void 0}(e,"scriptUrlPattern"))&&void 0!==n?n:d,[f,R]=function(){const e=[],t=()=>{e.push({time:new Date,state:document.visibilityState})},n=(r=document,o="visibilitychange",i=t,r.addEventListener(o,i,s),()=>r.removeEventListener(o,i,s));var r,o,i,s;return t(),[e,n]}();return Promise.resolve().then(()=>{if(!u||"string"!=typeof u)throw new Error("API key required");return g(function(e,t){return(Array.isArray(e)?e:[e]).map(e=>function(e,t){const n=encodeURIComponent;return e.replace(/<[^<>]+>/g,e=>"<version>"===e?"3":"<apiKey>"===e?n(t):"<loaderVersion>"===e?n(s):e)}(String(e),t))}(l,u),ae)}).catch(e=>{throw R(),function(e){return e instanceof Error&&e.message===c?new Error(a):e}(e)}).then(([e,t])=>(R(),e.load({...o,ldi:{attempts:t,visibilityStates:f}})))},defaultScriptUrlPattern:l,ERROR_SCRIPT_LOAD_FAIL:a,ERROR_API_KEY_EXPIRED:de,ERROR_API_KEY_INVALID:ue,ERROR_API_KEY_MISSING:ce,ERROR_BAD_REQUEST_FORMAT:"Request cannot be parsed",ERROR_BAD_RESPONSE_FORMAT:"Response cannot be parsed",ERROR_CLIENT_TIMEOUT:"Client timeout",ERROR_CSP_BLOCK:r,ERROR_FORBIDDEN_ENDPOINT:q,ERROR_FORBIDDEN_HEADER:"Not available with restricted header",ERROR_FORBIDDEN_ORIGIN:"Not available for this origin",ERROR_GENERAL_SERVER_FAILURE:"Request failed",ERROR_HANDLE_AGENT_DATA:i,ERROR_INSTALLATION_METHOD_RESTRICTED:z,ERROR_INTEGRATION_FAILURE:X,ERROR_INVALID_ENDPOINT:o,ERROR_INVALID_PROXY_INTEGRATION_HEADERS:re("InvalidProxyIntegrationHeaders"),ERROR_INVALID_PROXY_INTEGRATION_SECRET:J,ERROR_NETWORK_ABORT:"Network request aborted",ERROR_NETWORK_CONNECTION:"Network connection error",ERROR_NETWORK_RESTRICTED:W,ERROR_PROXY_INTEGRATION_SECRET_ENVIRONMENT_MISMATCH:re("ProxyIntegrationSecretEnvironmentMismatch"),ERROR_RATE_LIMIT:"Too many requests, rate limit exceeded",ERROR_SERVER_TIMEOUT:"Request failed to process",ERROR_SUBSCRIPTION_NOT_ACTIVE:Y,ERROR_TOKEN_EXPIRED:de,ERROR_TOKEN_INVALID:ue,ERROR_TOKEN_MISSING:ce,ERROR_UNSUPPORTED_VERSION:$,ERROR_WRONG_REGION:H,defaultEndpoint:{default:"endpoint"},defaultTlsEndpoint:{default:"tlsEndpoint"},handleAgentData:function(t,r={}){const{storageKey:o=I,do:s}=r;try{const r=function(t){const r=function(e){const t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return r}(t);let o=r;try{o=function(t,r){const o=()=>{throw new Error("Invalid data")},i=e(t);i.length<r.length+2&&o();for(let e=0;e<r.length;++e)n(i[1+e],i[0])!==r[e]&&o();const s=1+r.length,a=n(i[s],i[0]);i.length<s+1+a+9&&o();const c=s+1+a,u=c+9,d=new ArrayBuffer(i.length-u),l=new Uint8Array(d);for(let e=0;e<l.length;++e)l[e]=i[u+e]^i[c+e%9];return d}(r,ie)}catch(e){}try{return function(t){const n={len:0,arr:new Uint8Array(128)},r=e(t);let o=0;const i=()=>(l(),r[o]===m?s():y(r[o])?a():f(K)?(o+=K.length,null):f(B)?(o+=B.length,!0):f(j)?(o+=j.length,!1):r[o]===k?c():r[o]===M?d():E()),s=()=>{for(n.len=0;o++,r[o]!==m;){if(r[o]===A){if(o++,r[o]===b){const e=parseInt(se(r.subarray(o+1,o+5)),16);u(n,R(String.fromCharCode(e))),o+=4;continue}const e=G[r[o]];if(e){ne(n,e);continue}return E()}if(void 0===r[o])return E();ne(n,r[o])}return o++,se(function(e){return e.arr.subarray(0,e.len)}(n))},a=()=>{const e=o;for(;r[o]===U||r[o]===D||r[o]===C||r[o]===P||y(r[o]);)o++;return Number(se(r.subarray(e,o)))},c=()=>{const e=[];for(o++;;){if(l(),r[o]===x){o++;break}if(e.length){if(r[o]!==_)return E();o++}e.push(i())}return e},d=()=>{const e={};let t=!0;for(o++;;){if(l(),r[o]===V){o++;break}if(!t){if(r[o]!==_)return E();o++,l()}if(r[o]!==m)return E();const n=s();if(l(),r[o]!==v)return E();o++,Object.defineProperty(e,n,{value:i(),configurable:!0,enumerable:!0,writable:!0}),t=!1}return e},l=()=>{for(;r[o]===w||r[o]===T||r[o]===N||r[o]===O;)o++},f=e=>{for(let t=0;t<e.length;t++)if(r[o+t]!==e[t])return!1;return!0},E=()=>{throw new SyntaxError("Unexpected "+(o<r.length?`byte ${o}`:"end"))},p=i();return l(),void 0!==r[o]&&E(),p}(o)}catch(e){}return null}(t);null!==r?(r.visitorToken&&function(e,t){(function(e,t){h(t=>{!function(e,t){Q(e,"",-1,t)}(e,t)}),h(n=>(Q(e,t,365,n),function(e){return f(()=>{const t=`${e}=`;for(const e of document.cookie.split(";")){let n=0;for(;" "===e[n]&&n<e.length;)++n;if(e.indexOf(t)===n)return e.slice(n+t.length)}},void 0)}(e)===t))})(t,e),function(e,t){var n;try{null===(n=null===localStorage||void 0===localStorage?void 0:localStorage.setItem)||void 0===n||n.call(localStorage,e,t)}catch(e){}}(t,e)}(r.visitorToken,`${o}_t`),null==(a=r.notifications)||a.forEach(p),E(s,()=>({e:25,result:{response:r}}))):E(s,()=>({e:25,result:{error:new Error("Failed to decode response")}}))}catch(e){throw E(s,()=>({e:25,result:{error:e instanceof Error?e:new Error(String(e))}})),function(e,t,n){const r=new Error(e);return void 0!==n&&(r.raw=n),r}(i,0,e)}var a}};function fe(){const e=["join","charCodeAt","105496OztMNB","encrypt","4683348BEliea","112455yXsrJu","AES-GCM","encode","length","set","1024644ZuyUBK","decrypt","importKey","6291324WCMctH","raw","287MmEXLx","2506095fHQKga","error","decode","Encryption error:","getRandomValues","subtle","from","replace","4DEhkzM","slice","1765515LCaDVd"];return(fe=function(){return e})()}function Re(e,t){e-=306;return fe()[e]}async function Ee(e,t){const n=Re;try{const r=e[n(331)](/-/g,"+").replace(/_/g,"/"),o=function(e){const t=Re,n=atob(e);return Uint8Array[t(330)](n,e=>e[t(309)](0))}(r+"=".repeat((4-r.length%4)%4)),i=o[n(306)](0,12),s=o[n(306)](12),a=(new TextEncoder)[n(315)](t),c=await crypto[n(329)].importKey("raw",a,{name:n(314)},!1,["decrypt"]),u=await crypto[n(329)][n(319)]({name:n(314),iv:i,tagLength:128},c,s);return(new TextDecoder)[n(326)](u)}catch(e){return console[n(325)]("Decryption error:",e),null}}!function(e){const t=Re,n=e();for(;;)try{if(826943===parseInt(t(313))/1+parseInt(t(332))/2*(parseInt(t(318))/3)+parseInt(t(312))/4+-parseInt(t(307))/5+-parseInt(t(321))/6+parseInt(t(323))/7*(parseInt(t(310))/8)+-parseInt(t(324))/9)break;n.push(n.shift())}catch(e){n.push(n.shift())}}(fe);const pe=we;!function(e){const t=we,n=e();for(;;)try{if(844204===-parseInt(t(276))/1+-parseInt(t(320))/2*(parseInt(t(293))/3)+-parseInt(t(297))/4+parseInt(t(275))/5*(-parseInt(t(279))/6)+parseInt(t(272))/7+parseInt(t(277))/8*(-parseInt(t(300))/9)+parseInt(t(312))/10)break;n.push(n.shift())}catch(e){n.push(n.shift())}}(Oe);const Ie=pe(322),he=pe(283);let ge=!1;const ye={INVALID_INPUT:{code:1001,message:"Invalid Input"},INTERNAL_ERROR:{code:1002,message:pe(301)},SERVER_ERROR:{code:1003,message:"Server Error, Try after some time"},INTERNET_NOT_CONNECTED:{code:1004,message:"Internet not connected"},SYNC_IN_PROGRESS:{code:1005,message:pe(285)},SYNC_DISABLED:{code:1006,message:pe(305)},SYNC_CANCELLED:{code:1007,message:pe(325)}};function me(e,t){const n=pe;let r=t;!isNullOrEmpty(t)&&(r=btoa(t)),sessionStorage[n(286)](e,r)}function _e(e){let t=sessionStorage[pe(295)](e);if(!isNullOrEmpty(t))try{return atob(t)}catch(e){console.error(e)}return t}async function ve(){return _e("userId")}function we(e,t){e-=271;return Oe()[e]}function Oe(){const e=["userId","SYNC_IN_PROGRESS","6995807QrPETA","json","application/json","95najjjg","610812idVUSr","24VFMdwa","sync_user_agent","43914NDGOUd","SERVER_ERROR","geolocation","msg","w5EseVLxhpfRzzsVj0fl","model","Previous sms sync is in progress, please try after some time","setItem","error","Unexpected error","Decrypted:","Server error, ","test","coords","3Fkvhqy","data","getItem","parse","5296332llufKD","log","length","2449611IvznBi","Internal Error, Try after some time","Internal error, ","data:","-9223372036854775808","Sync disabled","syncId","https://api.ipify.org?format=json","WEB","latitude","9223372036854775807","SYNC_DISABLED","32293070tmHxOH","INTERNAL_ERROR","stringify","userAgent","load","sync_device_id","code","Invalid userId","988022KgowRd","longitude","1.0.1","value","message","Sync cancelled due to it took more time and another sync initiated","components","success","failure","INTERNET_NOT_CONNECTED"];return(Oe=function(){return e})()}return{start:async function(e,t,n,r,o){const i=pe;var s="",a="";try{if(!function(e){const t=pe,n=String(e).trim();if(!n)return!1;if(!/^\d+$/[t(291)](n))return!1;try{if(e[t(299)]<18)return!0;{const e=BigInt(n),r=BigInt(t(304)),o=BigInt(t(310));return e>=r&&e<=o}}catch{return!1}}(r))return o({status:i(287),code:ye.INVALID_INPUT[i(318)],message:i(319),data:{userId:r||null,deviceId:null}});if(({deviceId:s,userAgent:a}=await async function(){const e=pe;let t=_e(e(317)),n=_e(e(278));if(!t){const r=await le[e(316)]({apiKey:he,region:"ap"}),o=await r.get();t=o?.visitorId,n=o?.[e(326)]?.userAgent?.[e(323)]||navigator?.[e(315)],me("sync_device_id",t),me(e(278),n)}return{deviceId:t,userAgent:n}}()),ge)return o({status:"failure",code:ye[i(271)][i(318)],message:"Previous sms sync is initiated for the user_id "+ve()+", please try after some time",data:{userId:r,deviceId:s}});if(!navigator.onLine)return o({status:i(287),code:ye[i(329)][i(318)],message:ye[i(329)][i(324)],data:{userId:r,deviceId:s}});ge=!0,async function(e){me(pe(330),e)}(r);const t=await async function(){const e=pe,t=await fetch(e(307));if(!t.ok)throw new Error("Failed to fetch IP address");return(await t[e(273)]()).ip}(),{latitude:u,longitude:d}=await async function(){return new Promise(e=>{const t=we;if(!navigator[t(281)])return e({latitude:0,longitude:0});navigator.geolocation.getCurrentPosition(n=>{const r=t;e({latitude:n[r(292)][r(309)],longitude:n.coords[r(321)]})},()=>{e({latitude:0,longitude:0})},{timeout:1e4})})}(),l={customAuthenticationToken:e,sdkVersion:Ie,userId:r,ipAddress:t,location:{latitude:u,longitude:d},deviceId:s,deviceType:i(308),userAgent:a},f=await async function(e,t,n){const r=pe,o=await fetch(n+"/sync/sdk/auth",{method:"POST",headers:{"Content-Type":r(274)},body:JSON[r(314)](e)});if(!o.ok)throw new Error("Failed to send data to API");return await o[r(273)]()}(l,0,n);if(200==f[i(318)])if(f[i(284)]?.isSyncEnabled){var c="";try{console[i(298)](i(303)+f[i(284)]?.[i(294)]),c=await Ee(f.model?.[i(294)],"PpwCKmkiEE8Q0O0FmbpZ90ZbdNypVhkp")}catch(e){return void o({status:i(328),code:ye[i(313)].code,message:i(302)+(e.message||i(288)),data:{userId:r,deviceId:s}})}if(console[i(298)](i(289),c),null!=c&&""!=c){const e=JSON[i(296)](c);o({status:i(327),code:200,message:"Sync Completed",data:{syncId:e?.syncConfig?.[i(306)]||null,userId:r,deviceId:s}})}else o({status:i(328),code:ye.INTERNAL_ERROR[i(318)],message:ye[i(313)][i(324)],data:{userId:r,deviceId:s}})}else o({status:i(328),code:ye[i(311)][i(318)],message:ye[i(311)].message,data:{syncId:f[i(306)]||null,userId:r,deviceId:s}});else o({status:i(328),code:ye[i(280)][i(318)],message:i(290)+f[i(282)],data:{syncId:f.syncId||null,userId:r,deviceId:s}})}catch(e){o({status:i(328),code:ye[i(313)][i(318)],message:"Internal error, "+(e[i(324)]||i(288)),data:{userId:r,deviceId:s}})}finally{ge=!1}}}});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digitap.ai/sync-sdk",
3
- "version": "0.1.3",
3
+ "version": "1.0.1",
4
4
  "description": "DigiTap Web Sync SDK",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",