UNPKG

osmos-web-sdk

Version:

OnlineSales.ai Web SDK for Vue and React projects

3 lines (2 loc) 12.6 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).OsmosSDK={})}(this,function(t){"use strict";class e{constructor(t="(max-width: 767px)",e="(min-width: 768px) and (max-width: 1023px)",i=!1){this.mobileMediaQuery=t,this.tabletMediaQuery=e,this.detectDeviceViaUA=i}detectDevice(){return this.detectDeviceViaUA?this.detectDeviceViaUserAgent():this.detectDeviceViaMediaQuery()}detectDeviceViaMediaQuery(){return"undefined"==typeof window?"DESKTOP":window.matchMedia(this.mobileMediaQuery).matches?"MOBILE":window.matchMedia(this.tabletMediaQuery).matches?"TABLET":"DESKTOP"}detectDeviceViaUserAgent(){if("undefined"==typeof navigator)return"DESKTOP";const t=navigator.userAgent.toLowerCase();return/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(t)?/ipad|android(?=.*\b(?:tablet|playbook)\b)/i.test(t)?"TABLET":"MOBILE":"DESKTOP"}isMobile(){return"MOBILE"===this.detectDevice()}isTablet(){return"TABLET"===this.detectDevice()}isDesktop(){return"DESKTOP"===this.detectDevice()}}class i{constructor(t=0,e=!1){this.retryCount=t,this.debugMode=e}async request(t,e={},i=0){try{this.debugMode&&console.log(`[OsmosSDK] Making request to: ${t}`,e);const i=await fetch(t,{...e,headers:{"Content-Type":"application/json",...e.headers}});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);const s=await i.json();return this.debugMode&&console.log(`[OsmosSDK] Response from ${t}:`,s),s}catch(s){if(i<this.retryCount){this.debugMode&&console.log(`[OsmosSDK] Retry attempt ${i+1} for ${t}`);const s=1e3*Math.pow(2,i);return await this.sleep(s),this.request(t,e,i+1)}throw this.debugMode&&console.error(`[OsmosSDK] Request failed after ${i+1} attempts:`,s),s}}async get(t,e){const i=e?this.buildQueryString(e):"",s=i?`${t}?${i}`:t;return this.request(s,{method:"GET"})}async post(t,e){return this.request(t,{method:"POST",body:e?JSON.stringify(e):void 0})}buildQueryString(t){return Object.entries(t).filter(([t,e])=>null!=e).map(([t,e])=>Array.isArray(e)?e.map(e=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&"):`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join("&")}sleep(t){return new Promise(e=>setTimeout(e,t))}}class s{constructor(t,e,s=0,r=!1){this.productAdsHost=t,this.displayAdsHost=e,this.httpClient=new i(s,r)}async fetchDisplayAds(t){try{const e=`https://${this.displayAdsHost}/api/display-ads`,i={...t,adUnit:Array.isArray(t.adUnit)?t.adUnit.join(","):t.adUnit};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async fetchPLAProductPageAds(t){try{const e=`https://${this.productAdsHost}/api/pla/product-page`,i={...t,productCount:t.productCount||2,skuIds:t.skuIds.join(",")};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async fetchPLASearchPageAds(t){try{const e=`https://${this.productAdsHost}/api/pla/search-page`,i={...t,productCount:t.productCount||2};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async fetchPLACategoryPageAd(t){try{const e=`https://${this.productAdsHost}/api/pla/category-page`,i={...t,productCount:t.productCount||2,categoryId:t.categoryId,categories:t.categories?t.categories.join(","):void 0};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async fetchPLATPAPageAd(t){try{const e=`https://${this.productAdsHost}/api/pla/tpa-page`,i={...t,productCount:t.productCount||2,skuIds:t.skuIds?t.skuIds.join(","):void 0};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async fetchPLAPurchasePageAd(t){try{const e=`https://${this.productAdsHost}/api/pla/purchase-page`,i={...t,productCount:t.productCount||2,skuIds:t.skuIds.join(",")};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async fetchPLAHomePageAd(t){try{const e=`https://${this.productAdsHost}/api/pla/home-page`,i={...t,productCount:t.productCount||2};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}async fetchPLACustomPageAd(t){try{const e=`https://${this.productAdsHost}/api/pla/custom-page`,i={...t,productCount:t.productCount||2,mcategoriesIds:t.mcategoriesIds?t.mcategoriesIds.join(","):void 0,brands:t.brands?t.brands.join(","):void 0,categories:t.categories?t.categories.join(","):void 0};return{success:!0,data:await this.httpClient.get(e,i)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class r{constructor(t,e,s={}){var r,a,o,n,c,d,u,h;this.eventTrackingHost=t,this.clientId=e,this.cliUbid=s.cliUbid,this.enableTracking=null===(r=s.enableTracking)||void 0===r||r,this.fireDefaultPixel=null===(a=s.fireDefaultPixel)||void 0===a||a,this.trackingParams=s.trackingParams,this.searchKeywordKey=null!==(o=s.searchKeywordKey)&&void 0!==o?o:"keyword",this.customQueryParams=s.customQueryParams,this.queryToParamMapping=null!==(n=s.queryToParamMapping)&&void 0!==n?n:{},this.urlToParamMapping=null!==(c=s.urlToParamMapping)&&void 0!==c?c:{},this.videoView=null!==(d=s.videoView)&&void 0!==d?d:5,this.defaultTrackSeconds=null!==(u=s.defaultTrackSeconds)&&void 0!==u?u:[1,3],this.debugMode=null!==(h=s.debugMode)&&void 0!==h&&h,this.httpClient=new i(0,this.debugMode)}async trackEvent(t){if(this.enableTracking)try{const e={clientId:this.clientId,cliUbid:this.cliUbid,timestamp:t.timestamp||Date.now(),...t,...this.getTrackingParams(),...this.getCustomQueryParams()},i=`https://${this.eventTrackingHost}/api/track`;this.debugMode&&console.log("[OsmosSDK] Sending tracking event:",e),await this.httpClient.post(i,e)}catch(t){this.debugMode&&console.error("[OsmosSDK] Failed to send tracking event:",t)}else this.debugMode&&console.log("[OsmosSDK] Tracking disabled, skipping event:",t)}async trackProductView(t,e){await this.trackEvent({eventType:"PRODUCT_VIEW",skuId:t,...e})}async trackAddToCart(t,e=1,i){await this.trackEvent({eventType:"ADD_TO_CART",skuId:t,quantity:e,...i})}async trackPurchase(t,e,i){await this.trackEvent({eventType:"PURCHASE",skuIds:t,total:e,...i})}async trackAdClick(t,e,i){await this.trackEvent({eventType:"AD_CLICK",adId:t,adUnit:e,...i})}async trackVideoView(t,e,i){await this.trackEvent({eventType:"VIDEO_VIEW",videoId:t,duration:e,viewed:e>=this.videoView,...i})}async trackSearch(t,e,i){await this.trackEvent({eventType:"SEARCH",keyword:t,resultsCount:e,...i})}async trackPageView(t,e){await this.trackEvent({eventType:"PAGE_VIEW",pageName:t,url:"undefined"!=typeof window?window.location.href:void 0,...e})}getTrackingParams(){return"function"==typeof this.trackingParams?this.trackingParams():this.trackingParams||{}}getCustomQueryParams(){return"function"==typeof this.customQueryParams?this.customQueryParams():this.customQueryParams||{}}getSearchKeyword(){if("undefined"==typeof window)return null;return new URLSearchParams(window.location.search).get(this.searchKeywordKey)}getMappedParams(){if("undefined"==typeof window)return{};const t={},e=new URLSearchParams(window.location.search),i=window.location.pathname;return Object.entries(this.queryToParamMapping).forEach(([i,s])=>{const r=e.get(i);r&&(t[s]=r)}),Object.entries(this.urlToParamMapping).forEach(([e,s])=>{const r=new RegExp(e),a=i.match(r);a&&a[1]&&(t[s]=a[1])}),t}async fireDefaultTrackingPixel(){if(this.fireDefaultPixel&&this.enableTracking)try{const t=`https://${this.eventTrackingHost}/pixel.gif`,e={clientId:this.clientId,cliUbid:this.cliUbid,timestamp:Date.now(),...this.getTrackingParams()},i=`${t}?${new URLSearchParams(e).toString()}`;this.debugMode&&console.log("[OsmosSDK] Firing default pixel:",i);(new Image).src=i}catch(t){this.debugMode&&console.error("[OsmosSDK] Failed to fire default pixel:",t)}}}class a{constructor(){this.isInitialized=!1}initialize(t){if(this.isInitialized)return void console.warn("[OsmosSDK] SDK already initialized");if(!t.clientId)throw new Error("clientId is required");if(!t.productAdsHost)throw new Error("productAdsHost is required");if(!t.displayAdsHost)throw new Error("displayAdsHost is required");this.options={device:"DESKTOP",mobileMediaQuery:"(max-width: 767px)",tabletMediaQuery:"(min-width: 768px) and (max-width: 1023px)",detectDeviceViaUA:!1,enableTracking:!0,fireDefaultPixel:!0,searchKeywordKey:"keyword",queryToParamMapping:{},urlToParamMapping:{},videoView:5,defaultTrackSeconds:[1,3],enableOMSdk:!1,omSdkOptions:{},selectorPrefix:"os",retryCount:0,debugMode:!1,...t},this.deviceDetector=new e(this.options.mobileMediaQuery,this.options.tabletMediaQuery,this.options.detectDeviceViaUA),this._adFetcher=new s(this.options.productAdsHost,this.options.displayAdsHost,this.options.retryCount,this.options.debugMode);const i=this.options.eventTrackingHost||"tracking.onlinesales.ai";this.trackingService=new r(i,this.options.clientId,{cliUbid:this.options.cliUbid,enableTracking:this.options.enableTracking,fireDefaultPixel:this.options.fireDefaultPixel,trackingParams:this.options.trackingParams,searchKeywordKey:this.options.searchKeywordKey,customQueryParams:this.options.customQueryParams,queryToParamMapping:this.options.queryToParamMapping,urlToParamMapping:this.options.urlToParamMapping,videoView:this.options.videoView,defaultTrackSeconds:this.options.defaultTrackSeconds,debugMode:this.options.debugMode}),this.isInitialized=!0,this.options.debugMode&&console.log("[OsmosSDK] SDK initialized successfully",this.options),this.trackingService.fireDefaultTrackingPixel()}updateOptions(t){if(!this.isInitialized)throw new Error("SDK must be initialized before updating options");this.options={...this.options,...t},(t.mobileMediaQuery||t.tabletMediaQuery||t.detectDeviceViaUA)&&(this.deviceDetector=new e(this.options.mobileMediaQuery,this.options.tabletMediaQuery,this.options.detectDeviceViaUA)),(t.productAdsHost||t.displayAdsHost||t.retryCount||t.debugMode)&&(this._adFetcher=new s(this.options.productAdsHost,this.options.displayAdsHost,this.options.retryCount,this.options.debugMode)),this.options.debugMode&&console.log("[OsmosSDK] Options updated",this.options)}getDevice(){if(!this.isInitialized)throw new Error("SDK must be initialized before getting device type");return this.options.device||this.deviceDetector.detectDevice()}get adFetcher(){if(!this.isInitialized)throw new Error("SDK must be initialized before accessing adFetcher");return this._adFetcher}get tracking(){if(!this.isInitialized)throw new Error("SDK must be initialized before accessing tracking service");return this.trackingService}isReady(){return this.isInitialized}getConfig(){if(!this.isInitialized)throw new Error("SDK must be initialized before getting config");return{...this.options}}}let o=null;function n(){return o||(o=new a),o}"undefined"!=typeof window&&(window.osmos={initialize:t=>{const e=n();return e.initialize(t),e},updateOptions:t=>{n().updateOptions(t)},getDevice:()=>n().getDevice(),isReady:()=>n().isReady(),getConfig:()=>n().getConfig(),adFetcher:{fetchDisplayAds:t=>n().adFetcher.fetchDisplayAds(t),fetchPLAProductPageAds:t=>n().adFetcher.fetchPLAProductPageAds(t),fetchPLASearchPageAds:t=>n().adFetcher.fetchPLASearchPageAds(t),fetchPLACategoryPageAd:t=>n().adFetcher.fetchPLACategoryPageAd(t),fetchPLATPAPageAd:t=>n().adFetcher.fetchPLATPAPageAd(t),fetchPLAPurchasePageAd:t=>n().adFetcher.fetchPLAPurchasePageAd(t),fetchPLAHomePageAd:t=>n().adFetcher.fetchPLAHomePageAd(t),fetchPLACustomPageAd:t=>n().adFetcher.fetchPLACustomPageAd(t)},tracking:{trackEvent:t=>n().tracking.trackEvent(t),trackProductView:(t,e)=>n().tracking.trackProductView(t,e),trackAddToCart:(t,e,i)=>n().tracking.trackAddToCart(t,e,i),trackPurchase:(t,e,i)=>n().tracking.trackPurchase(t,e,i),trackAdClick:(t,e,i)=>n().tracking.trackAdClick(t,e,i),trackVideoView:(t,e,i)=>n().tracking.trackVideoView(t,e,i),trackSearch:(t,e,i)=>n().tracking.trackSearch(t,e,i),trackPageView:(t,e)=>n().tracking.trackPageView(t,e),getSearchKeyword:()=>n().tracking.getSearchKeyword(),getMappedParams:()=>n().tracking.getMappedParams()}}),t.AdFetcher=s,t.DeviceDetector=e,t.HttpClient=i,t.OsmosSDK=a,t.TrackingService=r,t.getOsmos=n,t.initializeOsmos=function(t){const e=n();return e.initialize(t),e}}); //# sourceMappingURL=index.min.js.map