@seeka-labs/sdk-apps-server 2.0.19-alpha.0 → 2.0.21-alpha.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.
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import*as e from"crypto";import t from"crypto";import i from"axios";import*as r from"openid-client";import s from"winston";import*as n from"memory-cache";import a from"http";import o from"https";class c{constructor(){this.appId=void 0,this.appSecret=void 0,this.ingestUrl=void 0,this.issuerUrl=void 0,this.organisationId=void 0,this.applicationInstallId=void 0,this.runtime=void 0,this.logger=void 0,this.grantedPermissions=void 0,this.transformApiRequest=void 0,this.transformApiResponse=void 0,this.hasAnyPermissions=void 0,this.hasAllPermissions=void 0,this.hasPermission=void 0}}class l{constructor(e){this.config=void 0,this.transformOptions=async e=>await this.config.transformApiRequest(e),this.transformResult=async(e,t,i)=>await this.config.transformApiResponse(e,t,i),this.config=e}}class d extends l{constructor(e,t,r){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=r||i.create(),this.baseUrl=null!=t?t:"https://api-localdev-env0-seeka.au.ngrok.io"}merge(e,t){let i=this.baseUrl+"/api/identity";i=i.replace(/[?&]$/,"");const r=JSON.stringify(e);return this.transformOptions({data:r,method:"POST",url:i,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(D(e)&&e.response)return e.response;throw e}).then(e=>this.transformResult(i,e,e=>this.processMerge(e)))}processMerge(e){const t=e.status;let i={};if(e.headers&&"object"==typeof e.headers)for(const t in e.headers)e.headers.hasOwnProperty(t)&&(i[t]=e.headers[t]);if(200===t){let t=null;return t=JSON.parse(e.data),Promise.resolve(t)}if(401===t){const r=e.data;let s=null;return s=JSON.parse(r),F("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),F("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),F("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?F("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}class u extends l{constructor(e,t,r){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=r||i.create(),this.baseUrl=null!=t?t:"https://api-localdev-env0-seeka.au.ngrok.io"}batch(e,t){let i=this.baseUrl+"/api/ingest";i=i.replace(/[?&]$/,"");const r=JSON.stringify(e);return this.transformOptions({data:r,method:"POST",url:i,headers:{"Content-Type":"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(D(e)&&e.response)return e.response;throw e}).then(e=>this.transformResult(i,e,e=>this.processBatch(e)))}processBatch(e){const t=e.status;let i={};if(e.headers&&"object"==typeof e.headers)for(const t in e.headers)e.headers.hasOwnProperty(t)&&(i[t]=e.headers[t]);if(202===t)return Promise.resolve(null);if(401===t){const r=e.data;let s=null;return s=JSON.parse(r),F("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),F("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),F("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?F("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}var h,p,g,f,v,m,y,k,I,A,P,S,w,b,x,C,U,E,_,O,N,T,M,B;!function(e){e.Undefined="undefined",e.Success="success",e.Failed="failed"}(h||(h={})),function(e){e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive"}(p||(p={})),function(e){e.Browser="browser",e.Server="server",e.Mobile="mobile",e.Desktop="desktop",e.PhysicalStore="physicalStore",e.Email="email",e.Phone="phone",e.Chat="chat",e.Automatic="automatic"}(g||(g={})),function(e){e.Undefined="undefined",e.PageViewOrganic="pageViewOrganic",e.PageViewUtmAttributed="pageViewUtmAttributed",e.AddPaymentMethod="addPaymentMethod",e.AddToWishlist="addToWishlist",e.ContactMessage="contactMessage",e.Custom="custom",e.SyncCart="syncCart",e.Order="order",e.InitiateCheckout="initiateCheckout",e.AddToCart="addToCart",e.RemoveFromCart="removeFromCart",e.OneTimeItemPurchase="oneTimeItemPurchase",e.SubscriptionItemPurchase="subscriptionItemPurchase",e.ViewProduct="viewProduct",e.ViewPage="viewPage",e.ApplyPromotionalCode="applyPromotionalCode",e.KeywordSearch="keywordSearch",e.UserLoginSignup="userLoginSignup",e.UserLogin="userLogin",e.NewsletterSignup="newsletterSignup",e.Lead="lead",e.ChangeProductAttribute="changeProductAttribute",e.FilterItemsByAttribute="filterItemsByAttribute",e.Schedule="schedule",e.ViewContentItem="viewContentItem",e.StartTrial="startTrial"}(f||(f={})),function(e){e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection"}(v||(v={})),function(e){e.None="none",e.BigCommerce="bigCommerce",e.Shopify="shopify",e.OrderGroove="orderGroove",e.Magento="magento",e.Generic="generic",e.WooCommerce="wooCommerce",e.Demandware="demandware"}(m||(m={})),function(e){e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled",e.Pending="pending"}(y||(y={})),function(e){e.Undefined="undefined",e.Pending="pending",e.Authorized="authorized",e.PartiallyPaid="partiallyPaid",e.Paid="paid",e.PartiallyRefunded="partiallyRefunded",e.Refunded="refunded",e.Voided="voided"}(k||(k={})),function(e){e.Generic="generic",e.ActivityIngress="activityIngress",e.ActivityEgress="activityEgress",e.UserProfile="userProfile",e.SdkLog="sdkLog",e.Detections="detections",e.ActivityEgressFilter="activityEgressFilter",e.Diagnosis="diagnosis",e.PipelineIntegrationOutput="pipelineIntegrationOutput"}(I||(I={})),function(e){e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose"}(A||(A={})),function(e){e.None="none",e.Probe="probe",e.AppInstalled="appInstalled",e.IdentityChanged="identityChanged",e.ActivityAccepted="activityAccepted",e.AppInstallSettingsUpdated="appInstallSettingsUpdated",e.AppUninstalled="appUninstalled",e.BrowserSdkPlugin="browserSdkPlugin"}(P||(P={})),function(e){e.Unknown="unknown",e.Google="google",e.Meta="meta",e.Snapchat="snapchat",e.Pinterest="pinterest",e.TikTok="tikTok"}(S||(S={})),function(e){e.Undefined="undefined",e.PurchaseMade="purchaseMade",e.ActivityTracked="activityTracked"}(w||(w={})),function(e){e.Undefined="undefined",e.And="and",e.Or="or"}(b||(b={})),function(e){e.Undefined="undefined",e.Domain="domain",e.Pipeline="pipeline",e.Wildcard="wildcard",e.Url="url",e.PagePath="pagePath"}(x||(x={})),function(e){e.Undefined="undefined",e.Equals="equals",e.NotEquals="notEquals",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.EndsWith="endsWith",e.IsNull="isNull",e.NotNull="notNull",e.IsTrue="isTrue",e.IsFalse="isFalse",e.GreaterThanOrEquals="greaterThanOrEquals",e.LessThanOrEquals="lessThanOrEquals",e.GreaterThan="greaterThan",e.LessThan="lessThan",e.Before="before",e.After="after",e.Between="between",e.In="in",e.NotIn="notIn",e.Regex="regEx",e.Any="any"}(C||(C={})),function(e){e.Undefined="undefined",e.Seeka="seeka",e.DynamicYield="dynamicYield",e.Segment="segment",e.FacebookPixel="facebookPixel",e.GoogleAnalytics="googleAnalytics",e.Braze="braze",e.SnapchatPixel="snapchatPixel",e.Pinterest="pinterest",e.TikTokPixel="tikTokPixel",e.GoogleAds="googleAds"}(U||(U={})),function(e){e.Default="default",e.Sku="sku",e.ProductId="productId",e.VariantId="variantId",e.ProductIdAndVariantIdUnderscore="productIdAndVariantIdUnderscore",e.VariantIdOrProductId="variantIdOrProductId"}(E||(E={})),function(e){e.DeliverAllTraitsAndDeliverAllEvents="deliverAllTraitsAndDeliverAllEvents",e.DeliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e.DeliverMaxWeightedTraitsOnlyAndDeliverAllEvents="deliverMaxWeightedTraitsOnlyAndDeliverAllEvents",e.DeliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent"}(_||(_={})),function(e){e.None="none",e.SessionPassthrough="sessionPassthrough",e.UrlPassthrough="urlPassthrough"}(O||(O={})),function(e){e.Unset="unset",e.Granted="granted",e.Denied="denied"}(N||(N={})),function(e){e.Undefined="undefined",e.MeasureAdvertisingPerformance="measureAdvertisingPerformance"}(T||(T={})),function(e){e.Undefined="undefined",e.AllOf="allOf",e.AnyOf="anyOf"}(M||(M={})),function(e){e.Disabled="disabled",e.Explicit="explicit",e.Implicit="implicit"}(B||(B={}));class $ extends Error{constructor(e,t,i,r,s){super(),this.message=void 0,this.status=void 0,this.response=void 0,this.headers=void 0,this.result=void 0,this.isApiException=!0,this.message=e,this.status=t,this.response=i,this.headers=r,this.result=s}static isApiException(e){return!0===e.isApiException}}function F(e,t,i,r,s){throw null!=s?s:new $(e,t,i,r,null)}function D(e){return e&&!0===e.isAxiosError}const L=()=>`${W(new Date)}.${q()}`,R=e=>{const t=Object.keys(f),i=e.toLowerCase(),r=t.find(e=>e.toLowerCase()===i);return r?f[r]:f.Custom},q=()=>Math.floor(8999999999*Math.random()+1e9).toString(),W=e=>{let t=(e.getUTCMonth()+1).toString();t.length<2&&(t="0"+t);let i=e.getUTCDate().toString();i.length<2&&(i="0"+i);let r=e.getUTCHours().toString();r.length<2&&(r="0"+r);let s=e.getUTCMinutes().toString();s.length<2&&(s="0"+s);let n=e.getUTCSeconds().toString();return n.length<2&&(n="0"+n),`${e.getUTCFullYear()}${t}${i}.${r}${s}${n}`},G=e=>{if(!e)return{firstName:null,lastName:null};const t=e.trim().split(" ");return 1===t.length?{firstName:e,lastName:null}:2===t.length?{firstName:t[0],lastName:t[1]}:{firstName:t[0],lastName:t.slice(1).join(" ")}},V=(e,t)=>e.reduce((e,i,r)=>{const s=Math.floor(r/t);return e[s]||(e[s]=[]),e[s].push(i),e},[]),z={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},j="seeka:sdk";class J{constructor(e,t){this.appId=void 0,this.appInstallationId=void 0,this.set=async(e,t,i)=>{const r=this.getKey(e);n.put(r,JSON.stringify(t),i)},this.getOrSet=async(e,t,i)=>{const r=this.getKey(e),s=n.get(r);if(s){const e=JSON.parse(s);return i&&await i(e),e}const a=await t();return a?(n.put(r,JSON.stringify(a.value),a.expiryAbsoluteMilliseconds),a.value):null},this.getKey=e=>this.appInstallationId?`${j}:${this.appId}:${this.appInstallationId}:${e}`:`${j}:${this.appId}:${e}`,this.appId=e,this.appInstallationId=t}}const K=async t=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}};t.logger?t.logger.debug("Seeka auth: getting issuer",{...i}):console.debug("Seeka auth: getting issuer",{...i});const n=new J(t.appId,t.applicationInstallId),a=(o=t.issuerUrl+"_"+t.appId,e.createHash("md5").update(o).digest("hex"));var o;const c=await n.getOrSet(a,async()=>{try{const e=await H(t);return e&&e.meta&&e.raw?(t.logger?t.logger.verbose("Seeka auth: got issuer from remote",{...i}):console.debug("Seeka auth: got issuer from remote",{...i}),{value:e.meta,expiryAbsoluteMilliseconds:36e5}):null}catch(e){return t.logger?t.logger.error("Seeka auth: failed getting issuer",{...i,ex:s.exceptions.getAllInfo(e)}):console.error("Seeka auth: failed getting issuer",{...i}),null}},async()=>{t.logger?t.logger.verbose("Seeka auth: got issuer from cache",{...i}):console.debug("Seeka auth: got issuer from cache",{...i})});return null===c?null:new r.Configuration(c.serverMetadata,c.clientId,t.appSecret)},H=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.verbose("Seeka auth: discovering issuer from remote",{...t}):console.info("Seeka auth: discovering issuer from remote",{...t});try{const i=e.appId.replace(/-/g,""),s=await r.discovery(new URL(e.issuerUrl),i,void 0,r.None(),{timeout:1e4});return e.logger?e.logger.verbose("Seeka auth: discovered issuer from remote",{...t,client_id:s.clientMetadata().client_id}):console.info("Seeka auth: discovered issuer from remote",{...t,client_id:s.clientMetadata().client_id}),{meta:{serverMetadata:s.serverMetadata(),clientMetadata:s.clientMetadata(),timeout:s.timeout,clientId:i},raw:s}}catch(i){return e.logger?e.logger.error("Seeka auth: failed discovering issuer from remote",{...t,ex:s.exceptions.getAllInfo(i)}):console.error("Seeka auth: failed discovering issuer from remote",{...t}),null}},Y=async e=>{const t=new J(e.appId,e.applicationInstallId),i={applicationId:e.appId,issuer:{url:e.issuerUrl}};return await t.getOrSet("auth:token:appinstall",async()=>{const t=await(async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}},i=await K(e);if(!i)return null;try{let s=await r.clientCredentialsGrant(i,{resource:i.clientMetadata().client_id});const n={...t,token:{expires_at:s.expires_at,token_type:s.token_type,scope:s.scope}};return e.logger?e.logger.verbose("Seeka auth: got client access token from server",{...n}):console.info("Seeka auth: got app client token from server",{...n}),{token_type:s.token_type,access_token:s.access_token,expires_in:s.expires_in,id_token:s.id_token,refresh_token:s.refresh_token,scope:s.scope,authorization_details:s.authorization_details}}catch(i){const r={...t,error:i};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...r}):console.debug("Seeka auth: failed to get client access token from server",{...r}),null}})(e);if(!t||!t.access_token)return null;const i=await(async(e,t)=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}},s=await K(t);if(!s||!s)return null;try{const n=await r.genericGrantRequest(s,"app_install_token",{applicationInstallId:t.applicationInstallId,access_token:e,scope:"Seeka.API.Ingest"}),a={...i,token:{expires_at:n.expires_at,token_type:n.token_type,scope:n.scope}};return t.logger?t.logger.verbose("Seeka auth: got app access token from server",{...a}):console.info("Seeka auth: got app access token from server",{...a}),{token_type:n.token_type,access_token:n.access_token,expires_in:n.expires_in,id_token:n.id_token,refresh_token:n.refresh_token,scope:n.scope,authorization_details:n.authorization_details}}catch(e){const r={...i,error:e};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...r}):console.debug("Seeka auth: failed to get app access token from server",{...r}),null}})(t.access_token,e);return i?{value:i,expiryAbsoluteMilliseconds:((i.expires_in>t.expires_in?t.expires_in:i.expires_in)||9e5)-6e4}:null},async()=>{e.logger?e.logger.verbose("Seeka auth: got app token from cache",{...i}):console.debug("Seeka auth: got app token from cache",{...i})})},X=new a.Agent({keepAlive:!0,scheduling:"fifo"}),Q=new o.Agent({keepAlive:!0,scheduling:"fifo"}),Z=e=>{const t=i.create({httpAgent:X,httpsAgent:Q});return t.interceptors.request.use(function(t){let i={url:t.url,method:t.method};return"silly"===process.env.LOGGING_LEVEL&&(i={...i,body:t.data,params:t.params}),e.logger?e.logger.debug(`Seeka API: making call to ${i.url}`,{...i}):console.debug(`Seeka API: making call to ${i.url}`,{...i}),t},function(t){const i={error:t};return e.logger?e.logger.http("Seeka API: failed to send request",{...i}):console.debug("Seeka API: failed to send request",{...i}),Promise.reject(t)}),t.interceptors.response.use(function(t){var i,r;const s={url:(null==(i=t.request)?void 0:i.url)||t.config.url,method:(null==(r=t.request)?void 0:r.method)||t.config.method,response:{status:t.status}};return e.logger?e.logger.http(`Seeka API: call to ${s.url} succeeded`,{...s}):console.debug(`Seeka API: call to ${s.url} succeeded`,{...s}),t},function(t){var i;const{code:r,status:s,message:n}=t,{headers:a,url:o,method:c}=null==t?void 0:t.config,l={code:r,status:s,message:n,headers:a,url:o,method:c,content:null==t||null==(i=t.response)?void 0:i.data};return e.logger?e.logger.error(`Seeka API: call to ${l.url} failed`,{...l}):console.error(`Seeka API: call to ${l.url} failed`,{...l}),Promise.reject(t)}),t};class ee{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await Y(this.config)},this.ingestionService=void 0,this.identityService=void 0,this.checkPermission=(e,t)=>{if(!this.config.hasPermission(e))throw new Error("Cannot perform operation "+t+" on installationId "+this.config.applicationInstallId+" without permission "+e+". Currently granted permissions: "+(this.config.grantedPermissions?this.config.grantedPermissions.join(", "):"none"));return!0},this.mergeIdentity=async(e,t)=>{var i;this.checkPermission(z.identity.send,"mergeIdentity");const r=L();return null==(i=(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:r,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?r:void 0,runtime:this.config.runtime}})).result)?void 0:i.personId},this.mergeIdentityBatch=async(e,t)=>{this.checkPermission(z.identity.send,"mergeIdentityBatch");const i=L();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.debug("No identities in batch"));const s={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:i,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?i:void 0,runtime:this.config.runtime},n=V(e,this.maxBatchSize);if(n.length>1&&this.config.logger&&this.config.logger.debug(`Identity batch size ${e} is greater than ${this.maxBatchSize}, splitting into ${n.length} batches`),await this.trackActivityBatchRaw({data:n[0].map(e=>({id:{id:e||{},src:{...s}}}))}),n.length>1){const e=n.map((e,t)=>{var i;return 0===t?Promise.resolve():(null==(i=this.config.logger)||i.verbose(`Processing identity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({id:{id:e||{},src:{...s}}}))}))});await Promise.all(e)}},this.trackActivityBatch=async(e,t)=>{this.checkPermission(z.activity.send,"trackActivityBatch");const i=L();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.debug("No activities in batch"));const s={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:i,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?i:void 0,runtime:this.config.runtime},n=V(e,this.maxBatchSize);if(n.length>1&&this.config.logger&&this.config.logger.debug(`Activity batch size ${e.length} is greater than ${this.maxBatchSize}, splitting into ${n.length} batches`),await this.trackActivityBatchRaw({data:n[0].map(e=>({ev:{id:e.profile||{},src:{...s},payload:e.activity}}))}),n.length>1){const e=n.map((e,t)=>{var i;return 0===t?Promise.resolve():(null==(i=this.config.logger)||i.verbose(`Processing activity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({ev:{id:e.profile||{},src:{...s},payload:e.activity}}))}))});await Promise.all(e)}},this.trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)},this.trackActivityForProfileId=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,i)},this.trackActivityForProfileIdBatch=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfileIdBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t?{seekaPId:t}:void 0})),i)},this.trackActivityForProfile=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,i)},this.trackActivityForProfileBatch=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t})),i)},this.config=e,this.ingestionService=(e=>new u(e,e.ingestUrl,Z(e)))(e),this.identityService=(e=>new d(e,e.ingestUrl,Z(e)))(e)}}const te="x-seeka-signature-sha256",ie=(e,t,i)=>{if(!t)return!1;let r=null;if(t.get&&"function"==typeof t.get)r=t.get(te);else{const e=t[te];e&&(Array.isArray(e)&&e.length>0?r=e[0]:("string"==typeof e||e instanceof String)&&(r=e))}if(!r)return!1;const s=re(e,i)===r;return s||console.warn("Invalid webhook signature"),s},re=(t,i)=>e.createHmac("sha256",t).update(i).digest("hex"),se=(e,t,i)=>{if(!ie(e,t,i))throw new Error("Invalid webhook signature")},ne=(e,t,i,r,s)=>{const n=new c;return n.appId=e.applicationId,n.appSecret=t,n.ingestUrl=process.env.SEEKA_INGEST_URL||"https://router.seeka.services",n.issuerUrl=process.env.SEEKA_ISSUER_URL||"https://account.seeka.app",n.organisationId=e.organisationId,n.applicationInstallId=e.applicationInstallId,n.runtime={type:"sdk/js/apps-server",ver:"2.0.19-alpha.0".split("-")[0],client:i},n.logger=s,n.grantedPermissions=r,n.transformApiRequest=e=>ae(n,e),n.transformApiResponse=async(e,t,i)=>oe(n,e,t,i),n.hasAnyPermissions=e=>!(!n.grantedPermissions||0===n.grantedPermissions.length)&&(!e||0===e.length||e.some(e=>n.grantedPermissions.includes(e))),n.hasAllPermissions=e=>!(!n.grantedPermissions||0===n.grantedPermissions.length)&&(!e||0===e.length||e.every(e=>n.grantedPermissions.includes(e))),n.hasPermission=e=>!(!n.grantedPermissions||0===n.grantedPermissions.length)&&(!e||n.grantedPermissions.includes(e)),n},ae=async(e,t)=>{const i=await Y(e);if(!i||!i.access_token)throw new Error("Could not get access token for API request");return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},oe=async(e,t,i,r)=>(i.data=JSON.stringify(i.data),r(i)),ce="aes-192-cbc",le=(e,i)=>{if(!e)return"";if(!i)throw new Error("Secret is required to encrypt data");const r=t.scryptSync(i,"salt",24),s=t.randomBytes(16),n=t.createCipheriv(ce,r,s);return[n.update(e,"utf8","hex")+n.final("hex"),Buffer.from(s).toString("hex")].join("|")},de=(e,i)=>{if(!e)return"";if(!i)throw new Error("Secret is required to decrypt data");const[r,s]=e.split("|");if(!s)throw new Error("IV not found");const n=t.scryptSync(i,"salt",24),a=t.createDecipheriv(ce,n,Buffer.from(s,"hex"));return a.update(r,"hex","utf8")+a.final("utf8")};class ue{constructor(e){this.appSecret=void 0,this.encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return le(e,this.appSecret)},this.decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return de(e,this.appSecret)},this.appSecret=e}}var he;class pe{constructor(e,t){this.context=void 0,this.appCache=void 0,this.appInstallCache=void 0,this.api=void 0,this.logger=void 0,this.crypto=void 0,this.context=e,this.api=new ee(e.config),this.appCache=new J(e.config.appId),this.appInstallCache=new J(e.config.appId,e.config.applicationInstallId),this.crypto=new ue(e.config.appSecret),this.logger=t}}he=pe,pe.create=(e,t,i,r,s)=>new he({config:ne({...t},e,{type:i.name,ver:i.version.split("-")[0]},r,s)},s);const ge=[f.Order,f.SubscriptionItemPurchase,f.OneTimeItemPurchase],fe=(e,t,i)=>{if(!e.activity)return[];const r=e.activity,s=r.activityName===f.Custom?r.activityNameCustom:r.activityName;if(!s)return[];const n=s.toLowerCase(),a=[];return t.forEach(t=>{var o;if(!t)return;switch(t.type){case w.ActivityTracked:if(!t.activityNames)return;if(!t.activityNames.find(e=>e.toLowerCase()===n))return;i.verbose("Matched activity tracked filter",{filter:t,activityName:s});break;case w.PurchaseMade:if(!r.activityName||!ge.includes(r.activityName))return;i.verbose("Matched purchase made activity filter",{filter:t,activityName:s});break;default:return void i.warn("Unknown activity filter type",{filter:t})}const c=t.sourceFilter;if(!c)return;const l=e.source,d=null!=l&&l.loc?new URL(l.loc).hostname.toLowerCase():null,u=null==l?void 0:l.pipeline,h=null==u||null==(o=u.convergePipelineIntegrationInstanceId)?void 0:o.toLowerCase(),p=c.filters?c.filters.map(e=>{switch(e.type){case x.Wildcard:return i.verbose("Matched wildcard source filter",{sourceFilter:e}),!0;case x.Domain:return!(!d||!e.key||d!==e.key.toLowerCase()||(i.verbose("Matched domain source filter",{sourceFilter:e,activityHostname:d}),0));case x.Pipeline:return!(!h||!e.key||h!==e.key.toLowerCase()||(i.verbose("Matched pipeline source filter",{sourceFilter:e,sourceConvergePipelineIntegrationInstanceId:h}),0))}}):[];switch(c.comparer){case b.And:p.every(e=>!0===e)||a.push(t);break;case b.Or:p.some(e=>!0===e)&&a.push(t);break;default:i.warn("Unknown source filter comparer",{sourceFilters:c})}}),a};function ve(e){if(!e||0===e.trim().length)return!1;const t=e.split(".").filter(e=>e.trim().length>0);return 4===t.length&&t[0].toLowerCase()==="sk".toLowerCase()&&t[1].toLowerCase()==="1".toLowerCase()&&!isNaN(parseInt(t[2],10))&&!isNaN(parseInt(t[3],10))}const me={[T.MeasureAdvertisingPerformance]:7};export{x as ActivityPipelineActivityFilterSourceItemType,w as ActivityPipelineActivityFilterType,U as AnalyticsLibrary,$ as ApiException,l as ApiServiceProxyBase,z as AppPermissionKeys,S as ClickAttributionSourcePlatform,b as ConditionComparer,C as ConditionOperator,M as ConsentMappingMatchType,E as ContentIdentificationBehavior,I as ConvergePipelineLoggableActivityType,_ as ConvergeVendorDestinationPublishStrategy,O as CrossDomainTrackingUtmBehavior,v as ECommerceContentType,k as ECommerceFinancialStatus,y as ECommerceFulfillmentStatus,m as ECommercePlatform,T as IabPrivacyConsentPurposeId,me as IabPrivacyConsentPurposeIdMap,d as IdentityServiceProxy,u as IngestServiceProxy,p as PrivacyConsentType,B as PrivacyDataControlMode,N as RegionalConsentGrantOption,h as ResponseResultType,A as SdkLogEventLevel,ee as SeekaApiHelper,J as SeekaAppCacheManager,c as SeekaAppConfig,pe as SeekaAppHelper,P as SeekaWebhookCallType,f as TrackingActivityNames,g as TrackingEventSourceOriginType,V as chunk,de as decryptText,le as encryptText,R as getActivityName,ve as isValidSeekaProfileId,fe as matchActivityPipelineFilters,G as separatePersonFullName,se as throwOnInvalidWebhookSignature,ie as validateWebhookSignature,te as webhookSignatureHeaderName};
|
|
1
|
+
import*as e from"crypto";import t from"crypto";import i from"axios";import*as r from"openid-client";import s from"winston";import*as n from"memory-cache";import a from"http";import o from"https";class c{constructor(){this.appId=void 0,this.appSecret=void 0,this.ingestUrl=void 0,this.issuerUrl=void 0,this.organisationId=void 0,this.applicationInstallId=void 0,this.runtime=void 0,this.logger=void 0,this.grantedPermissions=void 0,this.transformApiRequest=void 0,this.transformApiResponse=void 0,this.hasAnyPermissions=void 0,this.hasAllPermissions=void 0,this.hasPermission=void 0}}class l{constructor(e){this.config=void 0,this.transformOptions=async e=>await this.config.transformApiRequest(e),this.transformResult=async(e,t,i)=>await this.config.transformApiResponse(e,t,i),this.config=e}}class d extends l{constructor(e,t,r){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=r||i.create(),this.baseUrl=null!=t?t:"https://api-localdev-env0-seeka.au.ngrok.io"}merge(e,t){let i=this.baseUrl+"/api/identity";i=i.replace(/[?&]$/,"");const r=JSON.stringify(e);return this.transformOptions({data:r,method:"POST",url:i,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(L(e)&&e.response)return e.response;throw e}).then(e=>this.transformResult(i,e,e=>this.processMerge(e)))}processMerge(e){const t=e.status;let i={};if(e.headers&&"object"==typeof e.headers)for(const t in e.headers)e.headers.hasOwnProperty(t)&&(i[t]=e.headers[t]);if(200===t){let t=null;return t=JSON.parse(e.data),Promise.resolve(t)}if(401===t){const r=e.data;let s=null;return s=JSON.parse(r),$("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),$("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),$("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?$("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}class u extends l{constructor(e,t,r){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=r||i.create(),this.baseUrl=null!=t?t:"https://api-localdev-env0-seeka.au.ngrok.io"}batch(e,t){let i=this.baseUrl+"/api/ingest";i=i.replace(/[?&]$/,"");const r=JSON.stringify(e);return this.transformOptions({data:r,method:"POST",url:i,headers:{"Content-Type":"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(L(e)&&e.response)return e.response;throw e}).then(e=>this.transformResult(i,e,e=>this.processBatch(e)))}processBatch(e){const t=e.status;let i={};if(e.headers&&"object"==typeof e.headers)for(const t in e.headers)e.headers.hasOwnProperty(t)&&(i[t]=e.headers[t]);if(202===t)return Promise.resolve(null);if(401===t){const r=e.data;let s=null;return s=JSON.parse(r),$("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),$("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),$("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?$("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}var h,p,g,f,v,m,y,k,I,A,P,S,w,b,x,U,C,E,_,O,N,T,M,B;!function(e){e.Undefined="undefined",e.Success="success",e.Failed="failed"}(h||(h={})),function(e){e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive"}(p||(p={})),function(e){e.Browser="browser",e.Server="server",e.Mobile="mobile",e.Desktop="desktop",e.PhysicalStore="physicalStore",e.Email="email",e.Phone="phone",e.Chat="chat",e.Automatic="automatic"}(g||(g={})),function(e){e.Undefined="undefined",e.PageViewOrganic="pageViewOrganic",e.PageViewUtmAttributed="pageViewUtmAttributed",e.AddPaymentMethod="addPaymentMethod",e.AddToWishlist="addToWishlist",e.ContactMessage="contactMessage",e.Custom="custom",e.SyncCart="syncCart",e.Order="order",e.InitiateCheckout="initiateCheckout",e.AddToCart="addToCart",e.RemoveFromCart="removeFromCart",e.OneTimeItemPurchase="oneTimeItemPurchase",e.SubscriptionItemPurchase="subscriptionItemPurchase",e.ViewProduct="viewProduct",e.ViewPage="viewPage",e.ApplyPromotionalCode="applyPromotionalCode",e.KeywordSearch="keywordSearch",e.UserLoginSignup="userLoginSignup",e.UserLogin="userLogin",e.NewsletterSignup="newsletterSignup",e.Lead="lead",e.ChangeProductAttribute="changeProductAttribute",e.FilterItemsByAttribute="filterItemsByAttribute",e.Schedule="schedule",e.ViewContentItem="viewContentItem",e.StartTrial="startTrial"}(f||(f={})),function(e){e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection"}(v||(v={})),function(e){e.None="none",e.BigCommerce="bigCommerce",e.Shopify="shopify",e.OrderGroove="orderGroove",e.Magento="magento",e.Generic="generic",e.WooCommerce="wooCommerce",e.Demandware="demandware"}(m||(m={})),function(e){e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled",e.Pending="pending"}(y||(y={})),function(e){e.Undefined="undefined",e.Pending="pending",e.Authorized="authorized",e.PartiallyPaid="partiallyPaid",e.Paid="paid",e.PartiallyRefunded="partiallyRefunded",e.Refunded="refunded",e.Voided="voided"}(k||(k={})),function(e){e.Generic="generic",e.ActivityIngress="activityIngress",e.ActivityEgress="activityEgress",e.UserProfile="userProfile",e.SdkLog="sdkLog",e.Detections="detections",e.ActivityEgressFilter="activityEgressFilter",e.Diagnosis="diagnosis",e.PipelineIntegrationOutput="pipelineIntegrationOutput"}(I||(I={})),function(e){e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose"}(A||(A={})),function(e){e.None="none",e.Probe="probe",e.AppInstalled="appInstalled",e.IdentityChanged="identityChanged",e.ActivityAccepted="activityAccepted",e.AppInstallSettingsUpdated="appInstallSettingsUpdated",e.AppUninstalled="appUninstalled",e.BrowserSdkPlugin="browserSdkPlugin"}(P||(P={})),function(e){e.Unknown="unknown",e.Google="google",e.Meta="meta",e.Snapchat="snapchat",e.Pinterest="pinterest",e.TikTok="tikTok"}(S||(S={})),function(e){e.Undefined="undefined",e.PurchaseMade="purchaseMade",e.ActivityTracked="activityTracked"}(w||(w={})),function(e){e.Undefined="undefined",e.And="and",e.Or="or"}(b||(b={})),function(e){e.Undefined="undefined",e.Domain="domain",e.Pipeline="pipeline",e.Wildcard="wildcard",e.Url="url",e.PagePath="pagePath"}(x||(x={})),function(e){e.Undefined="undefined",e.Equals="equals",e.NotEquals="notEquals",e.Contains="contains",e.NotContains="notContains",e.StartsWith="startsWith",e.EndsWith="endsWith",e.IsNull="isNull",e.NotNull="notNull",e.IsTrue="isTrue",e.IsFalse="isFalse",e.GreaterThanOrEquals="greaterThanOrEquals",e.LessThanOrEquals="lessThanOrEquals",e.GreaterThan="greaterThan",e.LessThan="lessThan",e.Before="before",e.After="after",e.Between="between",e.In="in",e.NotIn="notIn",e.Regex="regEx",e.Any="any"}(U||(U={})),function(e){e.Undefined="undefined",e.Seeka="seeka",e.DynamicYield="dynamicYield",e.Segment="segment",e.FacebookPixel="facebookPixel",e.GoogleAnalytics="googleAnalytics",e.Braze="braze",e.SnapchatPixel="snapchatPixel",e.Pinterest="pinterest",e.TikTokPixel="tikTokPixel",e.GoogleAds="googleAds"}(C||(C={})),function(e){e.Default="default",e.Sku="sku",e.ProductId="productId",e.VariantId="variantId",e.ProductIdAndVariantIdUnderscore="productIdAndVariantIdUnderscore",e.VariantIdOrProductId="variantIdOrProductId"}(E||(E={})),function(e){e.DeliverAllTraitsAndDeliverAllEvents="deliverAllTraitsAndDeliverAllEvents",e.DeliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverAllTraitsAndDeliverEventsOnlyIfMaxWeightedTraitsPresent",e.DeliverMaxWeightedTraitsOnlyAndDeliverAllEvents="deliverMaxWeightedTraitsOnlyAndDeliverAllEvents",e.DeliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent="deliverMaxWeightedTraitsOnlyAndDeliverEventsOnlyIfMaxWeightedTraitsPresent"}(_||(_={})),function(e){e.None="none",e.SessionPassthrough="sessionPassthrough",e.UrlPassthrough="urlPassthrough"}(O||(O={})),function(e){e.Unset="unset",e.Granted="granted",e.Denied="denied"}(N||(N={})),function(e){e.Undefined="undefined",e.MeasureAdvertisingPerformance="measureAdvertisingPerformance"}(T||(T={})),function(e){e.Undefined="undefined",e.AllOf="allOf",e.AnyOf="anyOf"}(M||(M={})),function(e){e.Disabled="disabled",e.Explicit="explicit",e.Implicit="implicit"}(B||(B={}));class F extends Error{constructor(e,t,i,r,s){super(),this.message=void 0,this.status=void 0,this.response=void 0,this.headers=void 0,this.result=void 0,this.isApiException=!0,this.message=e,this.status=t,this.response=i,this.headers=r,this.result=s}static isApiException(e){return!0===e.isApiException}}function $(e,t,i,r,s){throw null!=s?s:new F(e,t,i,r,null)}function L(e){return e&&!0===e.isAxiosError}const R=()=>`${W(new Date)}.${q()}`,D=e=>{const t=Object.keys(f),i=e.toLowerCase(),r=t.find(e=>e.toLowerCase()===i);return r?f[r]:f.Custom},q=()=>Math.floor(8999999999*Math.random()+1e9).toString(),W=e=>{let t=(e.getUTCMonth()+1).toString();t.length<2&&(t="0"+t);let i=e.getUTCDate().toString();i.length<2&&(i="0"+i);let r=e.getUTCHours().toString();r.length<2&&(r="0"+r);let s=e.getUTCMinutes().toString();s.length<2&&(s="0"+s);let n=e.getUTCSeconds().toString();return n.length<2&&(n="0"+n),`${e.getUTCFullYear()}${t}${i}.${r}${s}${n}`},G=e=>{if(!e)return{firstName:null,lastName:null};const t=e.trim().split(" ");return 1===t.length?{firstName:e,lastName:null}:2===t.length?{firstName:t[0],lastName:t[1]}:{firstName:t[0],lastName:t.slice(1).join(" ")}},V=(e,t)=>e.reduce((e,i,r)=>{const s=Math.floor(r/t);return e[s]||(e[s]=[]),e[s].push(i),e},[]),z={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},j="seeka:sdk";class J{constructor(e,t){this.appId=void 0,this.appInstallationId=void 0,this.set=async(e,t,i)=>{const r=this.getKey(e);n.put(r,JSON.stringify(t),i)},this.getOrSet=async(e,t,i)=>{const r=this.getKey(e),s=n.get(r);if(s){const e=JSON.parse(s);return i&&await i(e),e}const a=await t();return a?(n.put(r,JSON.stringify(a.value),a.expiryAbsoluteMilliseconds),a.value):null},this.getKey=e=>this.appInstallationId?`${j}:${this.appId}:${this.appInstallationId}:${e}`:`${j}:${this.appId}:${e}`,this.appId=e,this.appInstallationId=t}}const K=async t=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}};t.logger?t.logger.debug("Seeka auth: getting issuer",{...i}):console.debug("Seeka auth: getting issuer",{...i});const n=new J(t.appId,t.applicationInstallId),a=(o=t.issuerUrl+"_"+t.appId,e.createHash("md5").update(o).digest("hex"));var o;const c=await n.getOrSet(a,async()=>{try{const e=await H(t);return e&&e.meta&&e.raw?(t.logger?t.logger.verbose("Seeka auth: got issuer from remote",{...i}):console.debug("Seeka auth: got issuer from remote",{...i}),{value:e.meta,expiryAbsoluteMilliseconds:36e5}):null}catch(e){return t.logger?t.logger.error("Seeka auth: failed getting issuer",{...i,ex:s.exceptions.getAllInfo(e)}):console.error("Seeka auth: failed getting issuer",{...i}),null}},async()=>{t.logger?t.logger.verbose("Seeka auth: got issuer from cache",{...i}):console.debug("Seeka auth: got issuer from cache",{...i})});return null===c?null:new r.Configuration(c.serverMetadata,c.clientId,t.appSecret)},H=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.verbose("Seeka auth: discovering issuer from remote",{...t}):console.info("Seeka auth: discovering issuer from remote",{...t});try{const i=e.appId.replace(/-/g,""),s=await r.discovery(new URL(e.issuerUrl),i,void 0,r.None(),{timeout:1e4});return e.logger?e.logger.verbose("Seeka auth: discovered issuer from remote",{...t,client_id:s.clientMetadata().client_id}):console.info("Seeka auth: discovered issuer from remote",{...t,client_id:s.clientMetadata().client_id}),{meta:{serverMetadata:s.serverMetadata(),clientMetadata:s.clientMetadata(),timeout:s.timeout,clientId:i},raw:s}}catch(i){return e.logger?e.logger.error("Seeka auth: failed discovering issuer from remote",{...t,ex:s.exceptions.getAllInfo(i)}):console.error("Seeka auth: failed discovering issuer from remote",{...t}),null}},Y=async e=>{const t=new J(e.appId,e.applicationInstallId),i={applicationId:e.appId,issuer:{url:e.issuerUrl}};return await t.getOrSet("auth:token:appinstall",async()=>{const t=await(async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}},i=await K(e);if(!i)return null;try{let s=await r.clientCredentialsGrant(i,{resource:i.clientMetadata().client_id});const n={...t,token:{expires_at:s.expires_at,token_type:s.token_type,scope:s.scope}};return e.logger?e.logger.verbose("Seeka auth: got client access token from server",{...n}):console.info("Seeka auth: got app client token from server",{...n}),{token_type:s.token_type,access_token:s.access_token,expires_in:s.expires_in,id_token:s.id_token,refresh_token:s.refresh_token,scope:s.scope,authorization_details:s.authorization_details}}catch(i){const r={...t,error:i};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...r}):console.debug("Seeka auth: failed to get client access token from server",{...r}),null}})(e);if(!t||!t.access_token)return null;const i=await(async(e,t)=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}},s=await K(t);if(!s||!s)return null;try{const n=await r.genericGrantRequest(s,"app_install_token",{applicationInstallId:t.applicationInstallId,access_token:e,scope:"Seeka.API.Ingest"}),a={...i,token:{expires_at:n.expires_at,token_type:n.token_type,scope:n.scope}};return t.logger?t.logger.verbose("Seeka auth: got app access token from server",{...a}):console.info("Seeka auth: got app access token from server",{...a}),{token_type:n.token_type,access_token:n.access_token,expires_in:n.expires_in,id_token:n.id_token,refresh_token:n.refresh_token,scope:n.scope,authorization_details:n.authorization_details}}catch(e){const r={...i,error:e};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...r}):console.debug("Seeka auth: failed to get app access token from server",{...r}),null}})(t.access_token,e);return i?{value:i,expiryAbsoluteMilliseconds:((i.expires_in>t.expires_in?t.expires_in:i.expires_in)||9e5)-6e4}:null},async()=>{e.logger?e.logger.verbose("Seeka auth: got app token from cache",{...i}):console.debug("Seeka auth: got app token from cache",{...i})})},X=new a.Agent({keepAlive:!0,scheduling:"fifo"}),Q=new o.Agent({keepAlive:!0,scheduling:"fifo"}),Z=e=>{const t=i.create({httpAgent:X,httpsAgent:Q});return t.interceptors.request.use(function(t){let i={url:t.url,method:t.method};return"silly"===process.env.LOGGING_LEVEL&&(i={...i,body:t.data,params:t.params}),e.logger?e.logger.debug(`Seeka API: making call to ${i.url}`,{...i}):console.debug(`Seeka API: making call to ${i.url}`,{...i}),t},function(t){const i={error:t};return e.logger?e.logger.http("Seeka API: failed to send request",{...i}):console.debug("Seeka API: failed to send request",{...i}),Promise.reject(t)}),t.interceptors.response.use(function(t){var i,r;const s={url:(null==(i=t.request)?void 0:i.url)||t.config.url,method:(null==(r=t.request)?void 0:r.method)||t.config.method,response:{status:t.status}};return e.logger?e.logger.http(`Seeka API: call to ${s.url} succeeded`,{...s}):console.debug(`Seeka API: call to ${s.url} succeeded`,{...s}),t},function(t){var i;const{code:r,status:s,message:n}=t,{headers:a,url:o,method:c}=null==t?void 0:t.config,l={code:r,status:s,message:n,headers:a,url:o,method:c,content:null==t||null==(i=t.response)?void 0:i.data};return e.logger?e.logger.error(`Seeka API: call to ${l.url} failed`,{...l}):console.error(`Seeka API: call to ${l.url} failed`,{...l}),Promise.reject(t)}),t};class ee{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await Y(this.config)},this.ingestionService=void 0,this.identityService=void 0,this.checkPermission=(e,t)=>{if(!this.config.hasPermission(e))throw new Error("Cannot perform operation "+t+" on installationId "+this.config.applicationInstallId+" without permission "+e+". Currently granted permissions: "+(this.config.grantedPermissions?this.config.grantedPermissions.join(", "):"none"));return!0},this.mergeIdentity=async(e,t)=>{var i;this.checkPermission(z.identity.send,"mergeIdentity");const r=R();return null==(i=(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:r,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?r:void 0,runtime:this.config.runtime}})).result)?void 0:i.personId},this.mergeIdentityBatch=async(e,t)=>{this.checkPermission(z.identity.send,"mergeIdentityBatch");const i=R();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.debug("No identities in batch"));const s={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:i,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?i:void 0,runtime:this.config.runtime},n=V(e,this.maxBatchSize);if(n.length>1&&this.config.logger&&this.config.logger.debug(`Identity batch size ${e} is greater than ${this.maxBatchSize}, splitting into ${n.length} batches`),await this.trackActivityBatchRaw({data:n[0].map(e=>({id:{id:e||{},src:{...s}}}))}),n.length>1){const e=n.map((e,t)=>{var i;return 0===t?Promise.resolve():(null==(i=this.config.logger)||i.verbose(`Processing identity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({id:{id:e||{},src:{...s}}}))}))});await Promise.all(e)}},this.trackActivityBatch=async(e,t)=>{this.checkPermission(z.activity.send,"trackActivityBatch");const i=R();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.debug("No activities in batch"));const s={method:"",origin:t.origin,time:void 0,loc:t.loc,sess:i,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?i:void 0,runtime:this.config.runtime},n=V(e,this.maxBatchSize);if(n.length>1&&this.config.logger&&this.config.logger.debug(`Activity batch size ${e.length} is greater than ${this.maxBatchSize}, splitting into ${n.length} batches`),await this.trackActivityBatchRaw({data:n[0].map(e=>({ev:{id:e.profile||{},src:{...s},payload:e.activity}}))}),n.length>1){const e=n.map((e,t)=>{var i;return 0===t?Promise.resolve():(null==(i=this.config.logger)||i.verbose(`Processing activity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({ev:{id:e.profile||{},src:{...s},payload:e.activity}}))}))});await Promise.all(e)}},this.trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)},this.trackActivityForProfileId=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,i)},this.trackActivityForProfileIdBatch=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfileIdBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t?{seekaPId:t}:void 0})),i)},this.trackActivityForProfile=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,i)},this.trackActivityForProfileBatch=async(e,t,i)=>{this.checkPermission(z.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t})),i)},this.config=e,this.ingestionService=(e=>new u(e,e.ingestUrl,Z(e)))(e),this.identityService=(e=>new d(e,e.ingestUrl,Z(e)))(e)}}const te="x-seeka-signature-sha256",ie=(e,t,i)=>{if(!t)return!1;let r=null;if(t.get&&"function"==typeof t.get)r=t.get(te);else{const e=t[te];e&&(Array.isArray(e)&&e.length>0?r=e[0]:("string"==typeof e||e instanceof String)&&(r=e))}if(!r)return!1;const s=re(e,i)===r;return s||console.warn("Invalid webhook signature"),s},re=(t,i)=>e.createHmac("sha256",t).update(i).digest("hex"),se=(e,t,i)=>{if(!ie(e,t,i))throw new Error("Invalid webhook signature")},ne=(e,t,i,r,s)=>{const n=new c;return n.appId=e.applicationId,n.appSecret=t,n.ingestUrl=process.env.SEEKA_INGEST_URL||"https://router.seeka.services",n.issuerUrl=process.env.SEEKA_ISSUER_URL||"https://account.seeka.app",n.organisationId=e.organisationId,n.applicationInstallId=e.applicationInstallId,n.runtime={type:"sdk/js/apps-server",ver:"2.0.21-alpha.0".split("-")[0],client:i},n.logger=s,n.grantedPermissions=r,n.transformApiRequest=e=>ae(n,e),n.transformApiResponse=async(e,t,i)=>oe(n,e,t,i),n.hasAnyPermissions=e=>!(!n.grantedPermissions||0===n.grantedPermissions.length)&&(!e||0===e.length||e.some(e=>n.grantedPermissions.includes(e))),n.hasAllPermissions=e=>!(!n.grantedPermissions||0===n.grantedPermissions.length)&&(!e||0===e.length||e.every(e=>n.grantedPermissions.includes(e))),n.hasPermission=e=>!(!n.grantedPermissions||0===n.grantedPermissions.length)&&(!e||n.grantedPermissions.includes(e)),n},ae=async(e,t)=>{const i=await Y(e);if(!i||!i.access_token)throw new Error("Could not get access token for API request");return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},oe=async(e,t,i,r)=>(i.data=JSON.stringify(i.data),r(i)),ce="aes-192-cbc",le=(e,i)=>{if(!e)return"";if(!i)throw new Error("Secret is required to encrypt data");const r=t.scryptSync(i,"salt",24),s=t.randomBytes(16),n=t.createCipheriv(ce,r,s);return[n.update(e,"utf8","hex")+n.final("hex"),Buffer.from(s).toString("hex")].join("|")},de=(e,i)=>{if(!e)return"";if(!i)throw new Error("Secret is required to decrypt data");const[r,s]=e.split("|");if(!s)throw new Error("IV not found");const n=t.scryptSync(i,"salt",24),a=t.createDecipheriv(ce,n,Buffer.from(s,"hex"));return a.update(r,"hex","utf8")+a.final("utf8")};class ue{constructor(e){this.appSecret=void 0,this.encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return le(e,this.appSecret)},this.decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return de(e,this.appSecret)},this.appSecret=e}}var he;class pe{constructor(e,t){this.context=void 0,this.appCache=void 0,this.appInstallCache=void 0,this.api=void 0,this.logger=void 0,this.crypto=void 0,this.context=e,this.api=new ee(e.config),this.appCache=new J(e.config.appId),this.appInstallCache=new J(e.config.appId,e.config.applicationInstallId),this.crypto=new ue(e.config.appSecret),this.logger=t}}he=pe,pe.create=(e,t,i,r,s)=>new he({config:ne({...t},e,{type:i.name,ver:i.version.split("-")[0]},r,s)},s);const ge=[f.Order,f.SubscriptionItemPurchase,f.OneTimeItemPurchase],fe=(e,t,i)=>{if(!e.activity)return[];const r=e.activity,n=r.activityName===f.Custom?r.activityNameCustom:r.activityName;if(!n)return[];const a=n.toLowerCase(),o=[];return t.forEach(t=>{var c;if(!t)return;switch(t.type){case w.ActivityTracked:if(!t.activityNames)return;if(!t.activityNames.find(e=>e.toLowerCase()===a))return;i.verbose("Matched activity tracked filter",{filter:t,activityName:n});break;case w.PurchaseMade:if(!r.activityName||!ge.includes(r.activityName))return;i.verbose("Matched purchase made activity filter",{filter:t,activityName:n});break;default:return void i.warn("Unknown activity filter type",{filter:t})}const l=t.sourceFilter;if(!l)return;const d=e.source;let u;try{u=null!=d&&d.loc?new URL(d.loc).hostname.toLowerCase():null}catch(e){i.error("Failed to parse activity source URL",{ex:s.exceptions.getAllInfo(e),activitySource:d}),u=null}const h=null==d?void 0:d.pipeline,p=null==h||null==(c=h.convergePipelineIntegrationInstanceId)?void 0:c.toLowerCase(),g=l.filters?l.filters.map(e=>{switch(e.type){case x.Wildcard:return i.verbose("Matched wildcard source filter",{sourceFilter:e}),!0;case x.Domain:return!(!u||!e.key||u!==e.key.toLowerCase()||(i.verbose("Matched domain source filter",{sourceFilter:e,activityHostname:u}),0));case x.Pipeline:return!(!p||!e.key||p!==e.key.toLowerCase()||(i.verbose("Matched pipeline source filter",{sourceFilter:e,sourceConvergePipelineIntegrationInstanceId:p}),0))}}):[];switch(l.comparer){case b.And:g.every(e=>!0===e)&&o.push(t);break;case b.Or:g.some(e=>!0===e)&&o.push(t);break;default:i.warn("Unknown source filter comparer",{sourceFilters:l})}}),o};function ve(e){if(!e||0===e.trim().length)return!1;const t=e.split(".").filter(e=>e.trim().length>0);return 4===t.length&&t[0].toLowerCase()==="sk".toLowerCase()&&t[1].toLowerCase()==="1".toLowerCase()&&!isNaN(parseInt(t[2],10))&&!isNaN(parseInt(t[3],10))}const me={[T.MeasureAdvertisingPerformance]:7};export{x as ActivityPipelineActivityFilterSourceItemType,w as ActivityPipelineActivityFilterType,C as AnalyticsLibrary,F as ApiException,l as ApiServiceProxyBase,z as AppPermissionKeys,S as ClickAttributionSourcePlatform,b as ConditionComparer,U as ConditionOperator,M as ConsentMappingMatchType,E as ContentIdentificationBehavior,I as ConvergePipelineLoggableActivityType,_ as ConvergeVendorDestinationPublishStrategy,O as CrossDomainTrackingUtmBehavior,v as ECommerceContentType,k as ECommerceFinancialStatus,y as ECommerceFulfillmentStatus,m as ECommercePlatform,T as IabPrivacyConsentPurposeId,me as IabPrivacyConsentPurposeIdMap,d as IdentityServiceProxy,u as IngestServiceProxy,p as PrivacyConsentType,B as PrivacyDataControlMode,N as RegionalConsentGrantOption,h as ResponseResultType,A as SdkLogEventLevel,ee as SeekaApiHelper,J as SeekaAppCacheManager,c as SeekaAppConfig,pe as SeekaAppHelper,P as SeekaWebhookCallType,f as TrackingActivityNames,g as TrackingEventSourceOriginType,V as chunk,de as decryptText,le as encryptText,D as getActivityName,ve as isValidSeekaProfileId,fe as matchActivityPipelineFilters,G as separatePersonFullName,se as throwOnInvalidWebhookSignature,ie as validateWebhookSignature,te as webhookSignatureHeaderName};
|
|
2
2
|
//# sourceMappingURL=sdk-apps-server.module.js.map
|