cap-hydra-web-sdk 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +502 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.esm.js +2314 -0
- package/dist/index.js +2316 -0
- package/dist/index.umd.min.js +1 -0
- package/package.json +94 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).WebSDK=e()}(this,function(){"use strict";const t="/auth/nonce",e="/mapp/events",s=6e4,i={CATEGORIES:{USER:"USER",BEHAVIORAL:"BE"},STATUSES:{PENDING:"pending"},BATCH_SIZE:50,MAX_RETRY_ATTEMPTS:5,DEFAULT_RETRY_DELAYS:[6e4,12e4,24e4,48e4,9e5],RETRYABLE_HTTP_CODES:[408,429,500,502,503,504,401],GLOBAL_SUCCESS_CODE:200,PARTIAL_SUCCESS_CODE:201},n={NONCE_DATA:"websdk_nonce_data",USER_CONTEXT:"websdk_user_context",DEVICE_ID:"websdk_device_id",SESSION_ID:"websdk_session_id"},a=n;function r(t,e,s){const i=n[t],a=[];return e&&a.push(e),s&&a.push(s),a.length>0?`${a.join("_")}_${i}`:i}const o="websdk_storage_test",h="test_value",c="INIT_ERROR",d="AUTH_ERROR",u="NETWORK_ERROR",l="EVENT_ERROR",w="WebSDK initialized successfully",y="Failed to initialize WebSDK",f="WebSDK destroyed successfully",g="Authentication successful",m="Authentication failed",v="AuthManager initialized successfully",E="Nonce request successful",p="Nonce request failed",S="Request signature generated successfully",I="Failed to store nonce data",x="Failed to restore nonce data from storage",_="Failed to clear stored nonce data",D="EventTracker initialized successfully",b="EventTracker destroyed successfully",N="Failed to track event",k="Events sent successfully",U="Failed to send events",T="Failed to initialize storage:",A="Storage test failed:",C="Storage read/write test failed",R="StorageManager destroyed successfully",O="Error during storage cleanup:",z="Failed to track user signin event",M="Failed to track user signup event",$="Failed to track user update event",F="Failed to track user signout event",P="Failed to track behavioral event",B="web",q="",W="",L="",K="user_signin",Q="user_signup",H="user_update",X="user_signout",V="1.0.0";class J{constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,"")}async request(t,e={}){const{method:s="GET",headers:i={},body:n}=e,a=!t||t.startsWith("/")?t:`/${t}`,r=`${this.baseUrl}${a}`;try{const t={method:s,headers:{"Content-Type":"application/json",...i},body:n?JSON.stringify(n):null},e=await fetch(r,t);if(!e.ok){const t=await e.text();throw new Error(`HTTP ${e.status}: ${e.statusText} - ${t}`)}return await e.json()}catch(t){throw this.handleError(t)}}handleError(t){return t instanceof Error?"AbortError"===t.name?{code:u,message:"Request timeout",details:t}:t.message.includes("HTTP 401")||t.message.includes("HTTP 403")?{code:d,message:"Authentication failed",details:t}:(t.message.includes("HTTP"),{code:u,message:t.message,details:t}):{code:u,message:`Unknown error: ${String(t)}`,details:t}}async get(t,e={}){return this.request(t,{...e,method:"GET"})}async post(t,e,s={}){return this.request(t,{...s,method:"POST",body:e})}async put(t,e,s={}){return this.request(t,{...s,method:"PUT",body:e})}async delete(t,e={}){return this.request(t,{...e,method:"DELETE"})}}function G(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}function j(){return`session_${G()}`}async function Y(t,e,s,i){try{const n=i||Z(),a=function(t){const e=Object.keys(t).sort();return e.map(e=>`${e}=${t[e]}`).join("&")}({nonce:e,account_id:s,device_id:n,timestamp:Date.now(),payload:JSON.stringify(t,Object.keys(t).sort())}),r=await async function(t,e){const s=`${t}:${e}:cap-hydra-web-sdk`,i=(new TextEncoder).encode(s),n=await crypto.subtle.digest("SHA-256",i);return await crypto.subtle.importKey("raw",n,{name:"HMAC",hash:"SHA-256"},!1,["sign"])}(s,n);return await async function(t,e){const s=(new TextEncoder).encode(t),i=await crypto.subtle.sign("HMAC",e,s);return btoa(String.fromCharCode(...new Uint8Array(i)))}(a,r)}catch(t){throw new Error(`Signature generation failed: ${t instanceof Error?t.message:"Unknown error"}`)}}function Z(){const t=a.DEVICE_ID,e=localStorage.getItem(t);if(e)return e;const s=G();return localStorage.setItem(t,s),s}function tt(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return"UTC"}}function et(){return window.location.hostname||"localhost"}function st(t){const e=function(){const t=navigator.userAgent;let e="Unknown",s="Unknown";if(t.includes("Chrome")){e="Chrome";const i=t.match(/Chrome\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Firefox")){e="Firefox";const i=t.match(/Firefox\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Safari")&&!t.includes("Chrome")){e="Safari";const i=t.match(/Version\/([0-9.]+)/);s=i?.[1]??"Unknown"}else if(t.includes("Edge")){e="Edge";const i=t.match(/Edge\/([0-9.]+)/);s=i?.[1]??"Unknown"}let i="Unknown",n="Unknown";if(t.includes("Windows"))i="Windows",t.includes("Windows NT 10.0")?n="10":t.includes("Windows NT 6.3")?n="8.1":t.includes("Windows NT 6.2")?n="8":t.includes("Windows NT 6.1")&&(n="7");else if(t.includes("Mac OS X")){i="macOS";const e=t.match(/Mac OS X ([0-9_]+)/);n=e?.[1]?.replace(/_/g,".")??"Unknown"}else if(t.includes("Linux"))i="Linux",n="Unknown";else if(t.includes("Android")){i="Android";const e=t.match(/Android ([0-9.]+)/);n=e?.[1]??"Unknown"}else if(t.includes("iPhone")||t.includes("iPad")){i="iOS";const e=t.match(/OS ([0-9_]+)/);n=e?.[1]?.replace(/_/g,".")??"Unknown"}return{browserName:e,browserVersion:s,osName:i,osVersion:n}}(),s={width:window.innerWidth||document.documentElement.clientWidth||0,height:window.innerHeight||document.documentElement.clientHeight||0},i=Z();return{os_version:e.osVersion,country_code:t.country_code,os_name:e.osName,viewport_width:s.width,country:t.country,viewport_height:s.height,device_id:i,bundle_identifier:et(),last_seen:(new Date).toISOString(),city:t.city,sdk_version:V,platform:"web",browser_name:e.browserName,browser_version:e.browserVersion,browser_language:navigator.language||navigator.languages&&navigator.languages[0]||"en-US",timezone:tt()}}class it{constructor(t,e,s){this.httpClient=new J(t),this.logger=e,this.accountId=s}async getNonce(e,s){const i=s||Z();this.logger.info("Requesting nonce",{accountId:this.accountId,bundleIdentifier:e,deviceId:i});const n={account_id:this.accountId,bundle_identifier:e,device_id:i,timestamp:Date.now(),os_name:B};try{const e=await this.httpClient.post(t,n);return this.logger.info(E,{challengeId:e.challenge_id,expiresAt:e.expires_at}),e}catch(t){throw this.logger.error(p,t),t}}async sendEvents(t,s,i,n,a,r){this.logger.info("Sending events",{eventCount:t.length,cuid:s,challengeId:a});const o=r||Z(),h={system_data:st(i),request_id:G(),events:t,cuid:s};try{const s=await Y({...h,nonce:n,challenge_id:a},n,this.accountId,o);this.logger.info(S,{requestId:h.request_id,challengeId:a});const i={"X-Cap-Nonce":n,"X-Cap-Challenge-ID":a,"X-Cap-Signature":s,"X-Cap-Device-ID":o},r=await this.httpClient.post(e,h,{headers:i});return this.logger.info(k,{requestId:h.request_id,eventCount:t.length,success:r.status.success}),r}catch(e){throw this.logger.error(U,{requestId:h.request_id,eventCount:t.length,error:e}),e}}}class nt{constructor(t="WebSDK",e=2,s="data"){this.db=null,this.dbName=t,this.version=e,this.storeName=s,this.eventsStoreName="events"}async openDB(){return this.db?this.db:new Promise((t,e)=>{const s=indexedDB.open(this.dbName,this.version);s.onerror=()=>e(s.error),s.onsuccess=()=>{this.db=s.result,t(this.db)},s.onupgradeneeded=t=>{const e=t.target.result;if(e.objectStoreNames.contains(this.storeName)||e.createObjectStore(this.storeName),!e.objectStoreNames.contains(this.eventsStoreName)){const t=e.createObjectStore(this.eventsStoreName,{keyPath:"id"});t.createIndex("timestamp","timestamp",{unique:!1}),t.createIndex("status","status",{unique:!1})}}})}async getItem(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.storeName],"readonly").objectStore(this.storeName).get(t);n.onerror=()=>i(n.error),n.onsuccess=()=>{const t=n.result;s(null==t?null:"string"==typeof t?t:"object"==typeof t?JSON.stringify(t):String(t))}})}async setItem(t,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.storeName],"readwrite").objectStore(this.storeName).put(e,t);a.onerror=()=>n(a.error),a.onsuccess=()=>i()})}async removeItem(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.storeName],"readwrite").objectStore(this.storeName).delete(t);n.onerror=()=>i(n.error),n.onsuccess=()=>s()})}async clear(){const t=await this.openDB();return new Promise((e,s)=>{const i=t.transaction([this.storeName],"readwrite").objectStore(this.storeName).clear();i.onerror=()=>s(i.error),i.onsuccess=()=>e()})}async close(){this.db&&(this.db.close(),this.db=null)}async addEvent(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName).add(t);n.onerror=()=>i(n.error),n.onsuccess=()=>s()})}async getOldestPendingEvents(t=50,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).index("timestamp").openCursor(),r=[];let o=0;a.onerror=()=>n(a.error),a.onsuccess=s=>{const n=s.target.result;if(n&&o<t){const t=n.value;"pending"===t.status&&t.accountId===e&&(r.push(t),o++),n.continue()}else i(r)}})}async updateEventStatus(t,e,s,i){const n=await this.openDB();return new Promise((a,r)=>{const o=n.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName),h=o.get(t);h.onerror=()=>r(h.error),h.onsuccess=()=>{const n=h.result;if(n){n.status=e,n.lastAttempt=Date.now(),s&&(n.error=s),void 0!==i&&(n.attempts=i);const t=o.put(n);t.onerror=()=>r(t.error),t.onsuccess=()=>a()}else r(new Error(`Event with id ${t} not found`))}})}async removeEvents(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName);let a=0;const r=t.length;0!==r?t.forEach(t=>{const e=n.delete(t);e.onerror=()=>i(e.error),e.onsuccess=()=>{a++,a===r&&s()}}):s()})}async recoverOrphanedEvents(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readwrite").objectStore(this.eventsStoreName).openCursor();let a=0;n.onerror=()=>i(n.error),n.onsuccess=e=>{const i=e.target.result;if(i){const e=i.value;if("processing"===e.status&&e.accountId===t){e.status="failed",e.lastAttempt=Date.now(),e.error="Recovered from orphaned processing state";i.update(e).onsuccess=()=>{a++}}i.continue()}else s(a)}})}async getPendingEventCount(t){const e=await this.openDB();return new Promise((s,i)=>{const n=e.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).openCursor();let a=0;n.onerror=()=>i(n.error),n.onsuccess=e=>{const i=e.target.result;if(i){const e=i.value;"pending"===e.status&&e.accountId===t&&a++,i.continue()}else s(a)}})}async getRetryableEvents(t=5,e){const s=await this.openDB();return new Promise((i,n)=>{const a=s.transaction([this.eventsStoreName],"readonly").objectStore(this.eventsStoreName).openCursor(),r=[];a.onerror=()=>n(a.error),a.onsuccess=s=>{const n=s.target.result;if(n){const s=n.value;"failed"===s.status&&s.attempts<=t&&s.accountId===e&&r.push(s),n.continue()}else i(r)}})}}class at{constructor(t,e,s,n){if(this.systemDataArgs=null,this.currentAccountId=null,this.currentCuid=null,this.isProcessing=!1,this.processingPromise=null,this.BATCH_SIZE=i.BATCH_SIZE,this.authManager=t,this.logger=e,this.RETRY_DELAYS=n||i.DEFAULT_RETRY_DELAYS,s&&"getIndexedDBAdapter"in s){const t=s.getIndexedDBAdapter();t?(e.info("EventQueue: Reusing existing IndexedDB adapter from StorageManager"),this.storage=t):(e.warn("EventQueue: StorageManager has no IndexedDB adapter, creating new one"),this.storage=new nt)}else s?(e.info("EventQueue: Using provided IndexedDBStorage"),this.storage=s):(e.warn("EventQueue: No storage provided, creating new IndexedDBStorage"),this.storage=new nt)}async init(){this.logger.info("Initializing EventQueue"),await this.processQueueIfIdle(),this.logger.info("EventQueue initialized successfully")}async setUserContext(t,e,s){this.currentAccountId=t,this.currentCuid=s||null,this.systemDataArgs=e,this.logger.debug("EventQueue user context set",{accountId:t,cuid:s,systemDataArgs:e});const i=await this.storage.recoverOrphanedEvents(t);i>0&&this.logger.info(`Recovered ${i} orphaned processing events for account ${t}`)}getCurrentAccountId(){return this.currentAccountId}getCurrentCuid(){return this.currentCuid}async enqueue(t){try{if(!this.currentAccountId)throw new Error("Cannot enqueue event: No account context set");const e={id:G(),event:t,accountId:this.currentAccountId,timestamp:(new Date).toISOString(),attempts:0,status:i.STATUSES.PENDING};await this.storage.addEvent(e),this.logger.debug("Event added to queue",{eventId:e.id,eventType:t.category,eventName:t.name}),await this.processQueueIfIdle()}catch(e){throw this.logger.error("Failed to enqueue event",{event:t,error:e}),e}}async processQueueIfIdle(){if(!this.isProcessing)return this.processingPromise||(this.processingPromise=this.processQueue()),this.processingPromise;this.logger.debug("Queue processing already in progress, skipping")}async processQueue(){if(!this.isProcessing){this.isProcessing=!0,this.logger.debug("Starting queue processing");try{for(;;){if(await this.checkAndPromoteRetryEvents(),!this.currentAccountId){this.logger.debug("No account context, skipping event processing");break}const t=await this.storage.getOldestPendingEvents(this.BATCH_SIZE,this.currentAccountId);if(0===t.length){this.logger.debug("No pending events to process");break}this.logger.info("Processing batch of events",{batchSize:t.length,eventIds:t.map(t=>t.id)}),await this.markEventsAsProcessing(t),await this.sendBatch(t);if(0===await this.storage.getPendingEventCount(this.currentAccountId)){this.logger.debug("No more pending events");break}}}catch(t){this.logger.error("Queue processing failed",t)}finally{this.isProcessing=!1,this.processingPromise=null,this.logger.debug("Queue processing completed")}}}async markEventsAsProcessing(t){for(const e of t)try{await this.storage.updateEventStatus(e.id,"processing")}catch(t){this.logger.warn("Failed to mark event as processing",{eventId:e.id,error:t})}}async sendBatch(t){try{if(!this.currentAccountId)throw new Error("Missing account context for batch sending");const e=await this.authManager.getNonceData(),s=this.authManager.getApiClient(),i=t.map(t=>t.event),n=await s.sendEvents(i,this.currentCuid||"",this.systemDataArgs||{country:q,city:W,country_code:L},e.nonce,e.challengeId,e.deviceId);return await this.handleBatchResponse(t,n),!0}catch(e){const s=this.isRetryableHttpError(e);return this.logger.error("Failed to send batch",{batchSize:t.length,error:e,isRetryable:s}),s?await this.handleFailedBatch(t):await this.removeNonRetryableEvents(t),!1}}async removeSuccessfulEvents(t){const e=t.map(t=>t.id);try{await this.storage.removeEvents(e),this.logger.debug("Successfully removed events from storage",{count:e.length})}catch(t){this.logger.error("Failed to remove events from storage",{eventIds:e,error:t})}}async handleBatchResponse(t,e){const s=e.status.code;if(s===i.GLOBAL_SUCCESS_CODE)await this.removeSuccessfulEvents(t),this.logger.info("All events processed successfully",{count:t.length});else if(s===i.PARTIAL_SUCCESS_CODE)await this.handlePartialSuccess(t,e.events);else{i.RETRYABLE_HTTP_CODES.includes(parseInt(s))?(await this.handleFailedBatch(t),this.logger.warn("Batch failed with retryable error",{code:s,message:e.status.message})):(await this.removeNonRetryableEvents(t),this.logger.error("Batch failed with non-retryable error",{code:s,message:e.status.message}))}}async handlePartialSuccess(t,e){const s=new Map;e.forEach(t=>{s.set(t.event_id,t)});for(const e of t){const t=s.get(e.event.event_id);if(t)if(t.status.success)await this.storage.removeEvents([e.id]),this.logger.debug("Event processed successfully",{eventId:e.id});else{const s=parseInt(t.status.code);i.RETRYABLE_HTTP_CODES.includes(s)?(await this.markEventForRetry(e,t.status.message),this.logger.debug("Event marked for retry",{eventId:e.id,code:s,message:t.status.message})):(await this.storage.removeEvents([e.id]),this.logger.warn("Event permanently failed - removed",{eventId:e.id,code:s,message:t.status.message}))}else await this.markEventForRetry(e,"No response received")}}async markEventForRetry(t,e){const s=(t.attempts||0)+1;await this.storage.updateEventStatus(t.id,"failed",`Attempt ${s} failed: ${e}`,s);const i=Math.min(Math.max(s-1,0),this.RETRY_DELAYS.length-1),n=this.RETRY_DELAYS[i];this.logger.debug("Event marked for retry",{eventId:t.id,attempts:s,delay:n,isInfiniteRetry:s>this.RETRY_DELAYS.length})}async checkAndPromoteRetryEvents(){try{if(!this.currentAccountId)return void this.logger.debug("No account context, skipping retry check");const t=await this.storage.getRetryableEvents(Number.MAX_SAFE_INTEGER,this.currentAccountId);if(0===t.length)return;let e=0;for(const s of t){const t=Math.min(Math.max(s.attempts-1,0),this.RETRY_DELAYS.length-1),i=this.RETRY_DELAYS[t],n=Date.now()-(s.lastAttempt||0);n>=(i||0)&&(await this.storage.updateEventStatus(s.id,"pending"),e++,this.logger.debug("Failed event promoted to pending",{eventId:s.id,attempt:s.attempts+1,delay:i,timeSinceLastAttempt:n}))}e>0&&this.logger.debug(`Promoted ${e} failed events for retry`)}catch(t){this.logger.error("Failed to check retry events",t)}}isRetryableHttpError(t){if(t.code){const e=parseInt(t.code);return i.RETRYABLE_HTTP_CODES.includes(e)}return t.message?.includes("network")||t.message?.includes("timeout")||t.message?.includes("fetch")}async removeNonRetryableEvents(t){const e=t.map(t=>t.id);try{await this.storage.removeEvents(e),this.logger.warn("Non-retryable events removed permanently",{eventIds:e})}catch(t){this.logger.error("Failed to remove non-retryable events",{eventIds:e,error:t})}}async handleFailedBatch(t){for(const e of t)try{await this.markEventForRetry(e,"Batch failed")}catch(t){this.logger.error("Failed to mark event for retry",{eventId:e.id,error:t})}}async flush(){this.logger.info("Manual flush requested"),await this.processQueueIfIdle()}async destroy(){this.logger.info("Destroying EventQueue"),this.processingPromise&&await this.processingPromise,await this.storage.close(),this.logger.info("EventQueue destroyed")}async clear(){this.logger.warn("Clear method not implemented for IndexedDB queue")}}class rt{constructor(t,e,s,i){this.eventQueue=null,this.initialized=!1,this.config=t,this.logger=i,this.authManager=e,this.storageManager=s}async init(){this.initialized?this.logger.warn("EventTracker already initialized"):(this.logger.info("Initializing EventTracker with IndexedDB queue"),this.eventQueue=new at(this.authManager,this.logger,this.storageManager,this.config.retryDelays),await this.eventQueue.init(),this.initialized=!0,this.logger.info(D))}async setUserContext(t,e,s){if(!this.eventQueue)throw new Error("EventTracker not initialized");await this.eventQueue.setUserContext(t,e,s),this.logger.info("User context set",{accountId:t,systemDataArgs:e,cuid:s})}async track(t){if(!this.initialized||!this.eventQueue)throw new Error("EventTracker not initialized");this.logger.debug("Tracking event",{event:t});try{const e=this.convertToApiEvent(t);await this.eventQueue.enqueue(e)}catch(e){throw this.logger.error(N,{event:t,error:e}),new Error(`${l}: ${e}`)}}convertToApiEvent(t){const e="user"===t.type?i.CATEGORIES.USER:i.CATEGORIES.BEHAVIORAL,s={...t.data,device_id:Z()};if(!this.eventQueue)throw new Error("EventTracker not initialized");const n=this.eventQueue.getCurrentCuid();if(!n)throw new Error("User context not set. Call setUserContext() first.");return function(t,e,s,i){return{category:t,attributes:{...s,device_id:Z(),cuid:i},name:e,created_at:(new Date).toISOString(),event_id:G()}}(e,t.name||"custom",s,n)}async flush(){this.initialized&&this.eventQueue?(this.logger.info("Manual flush requested"),await this.eventQueue.flush()):this.logger.warn("Cannot flush events - EventTracker not initialized")}async destroy(){this.logger.info("Destroying EventTracker"),this.eventQueue&&await this.eventQueue.destroy(),this.initialized=!1,this.logger.info(b)}}class ot{constructor(t,e,s){this.initialized=!1,this.nonceData=null,this.config=t,this.logger=e,this.storageManager=s,this.apiClient=new it({baseUrl:t.baseURL},e,t.accountId)}async init(){this.initialized?this.logger.warn("AuthManager already initialized"):(this.logger.info("Initializing AuthManager",{accountId:this.config.accountId}),this.initialized=!0,this.logger.info(v))}async requestNonce(){if(!this.initialized)throw new Error("AuthManager not initialized");this.logger.info("Requesting nonce for authentication");try{const t=et(),e=Z(),s=await this.apiClient.getNonce(t,e);return this.nonceData={nonce:s.nonce,challengeId:s.challenge_id,expiresAt:s.expires_at,deviceId:e},await this.storeNonceData(),this.logger.info(g,{challengeId:s.challenge_id,expiresAt:s.expires_at}),this.nonceData}catch(t){throw this.logger.error(m,t),t}}async ensureValidNonce(){if(!this.initialized)throw new Error("AuthManager not initialized");this.logger.info("Ensuring valid nonce");try{return await this.restoreNonceData(),this.nonceData&&!this.isNonceExpired(this.nonceData.expiresAt)?(this.logger.info("Using existing valid nonce"),this.nonceData):(this.logger.info("No valid nonce found, requesting fresh"),await this.requestNonce())}catch(t){throw this.logger.error("Failed to ensure valid nonce",t),t}}async getNonceData(){return await this.ensureValidNonce()}isNonceExpired(t){return Date.now()>=t-s}hasValidNonce(){return!!this.nonceData&&!this.isNonceExpired(this.nonceData.expiresAt)}getApiClient(){return this.apiClient}async storeNonceData(){if(this.nonceData)try{await this.storageManager.set(a.NONCE_DATA,JSON.stringify(this.nonceData))}catch(t){this.logger.warn(I,t)}}async restoreNonceData(){try{const t=await this.storageManager.get(a.NONCE_DATA);t&&(this.nonceData=JSON.parse(t),this.logger.info("Nonce data restored from storage"))}catch(t){this.logger.warn(x,t),this.nonceData=null}}async clearNonceData(){this.nonceData=null;try{await this.storageManager.remove(a.NONCE_DATA)}catch(t){this.logger.warn(_,t)}}async destroy(){this.logger.info("Destroying AuthManager"),await this.clearNonceData(),this.initialized=!1,this.logger.info("AuthManager destroyed successfully")}}class ht{constructor(t,e,s){this.initialized=!1,this.logger=t,this.brandId=e,this.applicationId=s,this.adapter=new ct}async init(){if(this.initialized)this.logger.warn("StorageManager already initialized");else{this.logger.info("Initializing StorageManager");try{if(this.isIndexedDBSupported()){const t=["WebSDK"];this.brandId&&t.push(this.brandId),this.applicationId&&t.push(this.applicationId);const e=t.join("_"),s=new nt(e);await this.testStorageAdapter(s),this.adapter=s,this.logger.info("StorageManager initialized with IndexedDB",{dbName:e,brandId:this.brandId,applicationId:this.applicationId})}else await this.testStorageAdapter(this.adapter),this.logger.info("StorageManager initialized with localStorage");this.initialized=!0}catch(t){throw this.logger.error(T,t),new Error(`Storage initialization failed: ${t}`)}}}isIndexedDBSupported(){return"undefined"!=typeof window&&"indexedDB"in window&&null!==indexedDB}async testStorageAdapter(t){const e=o,s=h;try{await t.setItem(e,s);if(await t.getItem(e)!==s)throw new Error(C);await t.removeItem(e)}catch(t){throw new Error(`${A} ${t}`)}}async get(t){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.getItem(t)}async set(t,e){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.setItem(t,e)}async remove(t){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.removeItem(t)}async clear(){if(!this.initialized)throw new Error("StorageManager not initialized");return this.adapter.clear()}getIndexedDBAdapter(){return this.adapter instanceof nt?this.adapter:null}async destroy(){this.logger.info("Destroying StorageManager");try{this.adapter instanceof nt&&await this.adapter.close(),this.initialized=!1,this.logger.info(R)}catch(t){this.logger.error(O,t),this.initialized=!1}}}class ct{async getItem(t){try{return localStorage.getItem(t)}catch(t){throw new Error(`LocalStorage getItem failed: ${t}`)}}async setItem(t,e){try{localStorage.setItem(t,e)}catch(t){if(t instanceof DOMException&&(22===t.code||1014===t.code||"QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name))throw new Error("LocalStorage quota exceeded");throw new Error(`LocalStorage setItem failed: ${t}`)}}async removeItem(t){try{localStorage.removeItem(t)}catch(t){throw new Error(`LocalStorage removeItem failed: ${t}`)}}async clear(){try{localStorage.clear()}catch(t){throw new Error(`LocalStorage clear failed: ${t}`)}}}var dt;!function(t){t[t.VERBOSE=0]="VERBOSE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE"}(dt||(dt={}));class ut{constructor(t=!1,e=dt.INFO){this.logs=[],this.maxLogs=1e3,this.enabled=t,this.level=e}formatMessage(t,e){return`[${(new Date).toISOString()}] [WebSDK:${dt[t]}] ${e}`}log(t,e,s){if(!this.enabled||t<this.level)return;const i={level:t,message:e,timestamp:Date.now(),data:s};this.logs.push(i),this.logs.length>this.maxLogs&&this.logs.shift();const n=this.formatMessage(t,e),a=s?[n,s]:[n];switch(t){case dt.VERBOSE:case dt.DEBUG:break;case dt.INFO:console.info(...a);break;case dt.WARN:console.warn(...a);break;case dt.ERROR:console.error(...a)}}verbose(t,e){this.log(dt.VERBOSE,t,e)}debug(t,e){this.log(dt.DEBUG,t,e)}info(t,e){this.log(dt.INFO,t,e)}warn(t,e){this.log(dt.WARN,t,e)}error(t,e){this.log(dt.ERROR,t,e)}setLevel(t){this.level=t}setEnabled(t){this.enabled=t}getLogs(){return[...this.logs]}clearLogs(){this.logs=[]}}class lt{constructor(t){this.userContextSet=!1,this.initialized=!1,this.initializationPromise=null,this.config=t,this.logger=new ut(this.shouldEnableLogging(t.debugLevel)),this.sessionId="",this.storageManager=new ht(this.logger,t.brandId,t.applicationId),this.authManager=new ot(t,this.logger,this.storageManager),this.eventTracker=new rt(t,this.authManager,this.storageManager,this.logger)}static instanceWithConfig(t){return new lt(t)}shouldEnableLogging(t){return!(!t||"NONE"===t)&&["ERROR","WARN","INFO","DEBUG","VERBOSE"].includes(t)}async getOrCreateSessionId(){try{const t=r("SESSION_ID",this.config.brandId,this.config.applicationId),e=await this.storageManager.get(t);if(e)return e;const s=j();return await this.storageManager.set(t,s),s}catch(t){return this.logger.warn("Failed to get or create session ID",t),j()}}async restoreUserContext(){try{const t=r("USER_CONTEXT",this.config.brandId,this.config.applicationId),e=await this.storageManager.get(t);if(e){const t=JSON.parse(e),s=t.cuid;await this.eventTracker.setUserContext(this.config.accountId,t.systemDataArgs,s),this.userContextSet=!0,this.logger.info("User context restored from storage",{cuid:s,accountId:this.config.accountId})}}catch(t){this.logger.warn("Failed to restore user context from storage",t)}}async validateAndClearDifferentUserContext(t){try{const e=r("USER_CONTEXT",this.config.brandId,this.config.applicationId),s=await this.storageManager.get(e);if(s){const e=JSON.parse(s);e.cuid&&e.cuid!==t&&(this.logger.info("Different user detected, clearing previous user context",{previousCuid:e.cuid,newCuid:t}),await this.clearUserContext(),this.userContextSet=!1)}}catch(t){this.logger.warn("Error validating different user context",t),await this.clearUserContext(),this.userContextSet=!1}}async storeUserContext(t,e){try{const s={cuid:t,systemDataArgs:e,timestamp:Date.now()},i=r("USER_CONTEXT",this.config.brandId,this.config.applicationId);await this.storageManager.set(i,JSON.stringify(s))}catch(t){this.logger.warn("Failed to store user context",t)}}init(){this.initialized?this.logger.warn("WebSDK already initialized"):this.initializationPromise?this.logger.warn("WebSDK initialization already in progress"):this.initializationPromise=this.initializeAsync().catch(t=>{this.logger.error(y,t),this.initializationPromise=null})}async initializeAsync(){try{this.logger.info("Initializing WebSDK",{version:V,config:this.config}),await this.storageManager.init(),this.sessionId=await this.getOrCreateSessionId(),await this.authManager.init(),await this.eventTracker.init(),await this.authManager.ensureValidNonce(),await this.restoreUserContext(),this.initialized=!0,this.logger.info(w)}catch(t){throw new Error(`${c}: ${t}`)}}async setUserContext(t,e){if(!this.initialized)throw new Error("WebSDK must be initialized before setting user context");await this.validateAndClearDifferentUserContext(t),await this.eventTracker.setUserContext(this.config.accountId,e,t),this.userContextSet=!0,await this.storeUserContext(t,e),this.logger.info("User context set and persisted",{cuid:t,accountId:this.config.accountId})}async clearUserContext(){try{const t=r("USER_CONTEXT",this.config.brandId,this.config.applicationId);await this.storageManager.remove(t),this.userContextSet=!1,this.logger.info("User context cleared")}catch(t){this.logger.warn("Failed to clear user context",t),this.userContextSet=!1}}async track(t){if(!this.initialized)throw new Error("WebSDK must be initialized before tracking events");try{await this.eventTracker.track(t)}catch(e){throw this.logger.error(N,{event:t,error:e}),e}}async destroy(){this.logger.info("Destroying WebSDK instance");try{await this.eventTracker.flush(),await this.eventTracker.destroy(),await this.authManager.destroy(),await this.clearUserContext(),await this.storageManager.destroy(),this.initialized=!1,this.logger.info(f)}catch(t){throw this.logger.error(f,t),t}}pushUserSignin(t,e,s,i,n,a){this.pushUserSigninAsync(t,e,s,i,n,a).catch(e=>{this.logger.error(z,{cuid:t,error:e})})}async pushUserSigninAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,...e&&{first_name:e},...s&&{last_name:s},...i&&{email:i},...n&&{phone:n},...a&&{custom_data:a}},o={type:"user",name:K,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User signin event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error(z,{cuid:t,error:e}),e}}pushUserSignup(t,e,s,i,n,a){this.pushUserSignupAsync(t,e,s,i,n,a).catch(e=>{this.logger.error(M,{cuid:t,error:e})})}async pushUserSignupAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,first_name:e,last_name:s,email:i,phone:n,...a&&{custom_data:a}},o={type:"user",name:Q,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User signup event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error(M,{cuid:t,error:e}),e}}pushUserUpdate(t,e,s,i,n,a){this.pushUserUpdateAsync(t,e,s,i,n,a).catch(e=>{this.logger.error($,{cuid:t,error:e})})}async pushUserUpdateAsync(t,e,s,i,n,a){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const r={cuid:t,...e&&{first_name:e},...s&&{last_name:s},...i&&{email:i},...n&&{phone:n},...a&&{custom_data:a}},o={type:"user",name:H,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:r};try{await this.track(o),this.logger.info("User update event tracked",{cuid:t,firstName:e,lastName:s,email:i})}catch(e){throw this.logger.error($,{cuid:t,error:e}),e}}pushUserSignOut(t){this.pushUserSignOutAsync(t).catch(e=>{this.logger.error(F,{cuid:t,error:e}),this.destroy().catch(t=>{this.logger.error("Failed to destroy SDK after failed signout",t)})})}async pushUserSignOutAsync(t){await this.ensureInitialized(),await this.setUserContextIfNeeded(t);const e={type:"user",name:X,timestamp:Date.now(),sessionId:this.sessionId,userId:t,data:{cuid:t}};try{await this.track(e),this.logger.info("User signout event tracked",{cuid:t}),await this.destroy()}catch(e){this.logger.error(F,{cuid:t,error:e});try{await this.destroy()}catch(t){this.logger.error("Failed to destroy SDK after failed signout",t)}throw e}}pushEvent(t,e){this.pushEventAsync(t,e).catch(e=>{this.logger.error(P,{eventName:t,error:e})})}async pushEventAsync(t,e){if(await this.ensureInitialized(),!this.userContextSet)throw new Error("User context must be set before tracking behavioral events. Call setUserContext() first.");const s={event_name:t,...e&&e},i={type:"behavioral",name:t,timestamp:Date.now(),sessionId:this.sessionId,data:s};try{await this.track(i),this.logger.info("Behavioral event tracked",{eventName:t,attributes:e})}catch(e){throw this.logger.error(P,{eventName:t,error:e}),e}}async ensureInitialized(){if(this.initializationPromise)try{await this.initializationPromise}catch(t){throw new Error(`SDK initialization failed: ${t}`)}if(!this.initialized)throw new Error("WebSDK must be initialized before tracking events. Call init() first.")}async setUserContextIfNeeded(t){if(!this.userContextSet){const e={country:this.config.country,city:this.config.city,country_code:this.config.countryCode};await this.setUserContext(t,e),this.logger.debug("User context set automatically",{cuid:t,systemDataArgs:e})}}}return lt});
|
package/package.json
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cap-hydra-web-sdk",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Capillary Hydra WebSDK - JavaScript/TypeScript SDK for web applications",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"module": "dist/index.esm.js",
|
|
8
|
+
"umd": "dist/index.umd.min.js",
|
|
9
|
+
"types": "dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"import": "./dist/index.esm.js",
|
|
13
|
+
"require": "./dist/index.js",
|
|
14
|
+
"types": "./dist/index.d.ts"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist/index.js",
|
|
19
|
+
"dist/index.esm.js",
|
|
20
|
+
"dist/index.umd.min.js",
|
|
21
|
+
"dist/index.d.ts"
|
|
22
|
+
],
|
|
23
|
+
"scripts": {
|
|
24
|
+
"build": "cross-env NODE_ENV=production rollup -c",
|
|
25
|
+
"build:dev": "cross-env NODE_ENV=development rollup -c",
|
|
26
|
+
"build:watch": "cross-env NODE_ENV=development rollup -c --watch",
|
|
27
|
+
"dev": "cross-env NODE_ENV=development rollup -c --watch",
|
|
28
|
+
"test": "jest",
|
|
29
|
+
"test:watch": "jest --watch",
|
|
30
|
+
"test:coverage": "jest --coverage",
|
|
31
|
+
"test:unit": "jest tests/modules tests/shared tests/core",
|
|
32
|
+
"test:integration": "jest tests/integration",
|
|
33
|
+
"test:ci": "jest --coverage --watchAll=false --passWithNoTests",
|
|
34
|
+
"lint": "eslint src/**/*.ts",
|
|
35
|
+
"lint:fix": "eslint src/**/*.ts --fix",
|
|
36
|
+
"format": "prettier --write \"src/**/*.{ts,js}\"",
|
|
37
|
+
"format:check": "prettier --check \"src/**/*.{ts,js}\"",
|
|
38
|
+
"clean": "rm -rf dist",
|
|
39
|
+
"prepare": "npm run build",
|
|
40
|
+
"analyze-bundle": "npm run build && du -sh dist/* | sort -hr",
|
|
41
|
+
"analyze-bundle:dev": "npm run build:dev && du -sh dist/* | sort -hr",
|
|
42
|
+
"package-size": "npm pack --dry-run",
|
|
43
|
+
"package-size:dev": "npm run build:dev && npm pack --dry-run --ignore-scripts",
|
|
44
|
+
"size-check": "node scripts/bundle_size_check.cjs",
|
|
45
|
+
"size-check:ci": "node scripts/bundle_size_check.cjs --ci"
|
|
46
|
+
},
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/Capillary/hydra-sdk-web.git"
|
|
50
|
+
},
|
|
51
|
+
"keywords": [
|
|
52
|
+
"sdk",
|
|
53
|
+
"websdk",
|
|
54
|
+
"capillary",
|
|
55
|
+
"hydra",
|
|
56
|
+
"analytics",
|
|
57
|
+
"events",
|
|
58
|
+
"tracking"
|
|
59
|
+
],
|
|
60
|
+
"author": "Milan Prajapati",
|
|
61
|
+
"license": "ISC",
|
|
62
|
+
"bugs": {
|
|
63
|
+
"url": "https://github.com/Capillary/hydra-sdk-web/issues"
|
|
64
|
+
},
|
|
65
|
+
"homepage": "https://github.com/Capillary/hydra-sdk-web#readme",
|
|
66
|
+
"devDependencies": {
|
|
67
|
+
"@rollup/plugin-commonjs": "^28.0.6",
|
|
68
|
+
"@rollup/plugin-node-resolve": "^16.0.1",
|
|
69
|
+
"@rollup/plugin-replace": "^6.0.2",
|
|
70
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
71
|
+
"@rollup/plugin-typescript": "^12.1.4",
|
|
72
|
+
"@testing-library/dom": "^10.4.1",
|
|
73
|
+
"@testing-library/jest-dom": "^6.6.4",
|
|
74
|
+
"@testing-library/user-event": "^14.6.1",
|
|
75
|
+
"@types/jest": "^30.0.0",
|
|
76
|
+
"@types/node": "^24.1.0",
|
|
77
|
+
"@typescript-eslint/eslint-plugin": "^8.38.0",
|
|
78
|
+
"@typescript-eslint/parser": "^8.38.0",
|
|
79
|
+
"cross-env": "^10.0.0",
|
|
80
|
+
"eslint": "^9.32.0",
|
|
81
|
+
"jest": "^30.0.5",
|
|
82
|
+
"jest-environment-jsdom": "^30.0.5",
|
|
83
|
+
"prettier": "^3.6.2",
|
|
84
|
+
"rollup": "^4.46.1",
|
|
85
|
+
"rollup-plugin-dts": "^6.2.1",
|
|
86
|
+
"ts-jest": "^29.4.0",
|
|
87
|
+
"tslib": "^2.8.1",
|
|
88
|
+
"typescript": "^5.8.3"
|
|
89
|
+
},
|
|
90
|
+
"engines": {
|
|
91
|
+
"node": ">=18.0.0",
|
|
92
|
+
"npm": ">=8.0.0"
|
|
93
|
+
}
|
|
94
|
+
}
|