@seeka-labs/sdk-apps-server 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var e=require("memory-cache"),t=require("crypto"),i=require("axios"),r=require("openid-client"),s=require("http"),n=require("https");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(i){if("default"!==i){var r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return e[i]}})}}),t.default=e,t}var c=/*#__PURE__*/a(e),l=/*#__PURE__*/a(t),d=/*#__PURE__*/o(i),p=/*#__PURE__*/o(s),u=/*#__PURE__*/o(n);const g={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},h="seeka:sdk";class v{constructor(e,t){this.appId=void 0,this.appInstallationId=void 0,this.set=async(e,t,i)=>{const r=this.getKey(e);c.put(r,JSON.stringify(t),i)},this.getOrSet=async(e,t,i)=>{const r=this.getKey(e),s=c.get(r);if(s){const e=JSON.parse(s);return i&&await i(e),e}const n=await t();return n?(c.put(r,JSON.stringify(n.value),n.expiryAbsoluteMilliseconds),n.value):null},this.getKey=e=>this.appInstallationId?`${h}:${this.appId}:${this.appInstallationId}:${e}`:`${h}:${this.appId}:${e}`,this.appId=e,this.appInstallationId=t}}class m{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 f{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 y extends f{constructor(e,t,i){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=i||d.default.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(B(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),N("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?N("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}class k extends f{constructor(e,t,i){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=i||d.default.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(B(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),N("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?N("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}var S,P,A,I,w,x,C,b,E,T,U;exports.ResponseResultType=void 0,(S=exports.ResponseResultType||(exports.ResponseResultType={})).Undefined="undefined",S.Success="success",S.Failed="failed",exports.PrivacyConsentType=void 0,(P=exports.PrivacyConsentType||(exports.PrivacyConsentType={})).Unknown="unknown",P.Informed="informed",P.Implied="implied",P.Explicit="explicit",P.Active="active",P.Passive="passive",exports.TrackingEventSourceOriginType=void 0,(A=exports.TrackingEventSourceOriginType||(exports.TrackingEventSourceOriginType={})).Browser="browser",A.Server="server",A.Mobile="mobile",A.Desktop="desktop",A.PhysicalStore="physicalStore",A.Email="email",A.Phone="phone",A.Chat="chat",A.Automatic="automatic",exports.TrackingActivityNames=void 0,(I=exports.TrackingActivityNames||(exports.TrackingActivityNames={})).Undefined="undefined",I.PageViewOrganic="pageViewOrganic",I.PageViewUtmAttributed="pageViewUtmAttributed",I.AddPaymentMethod="addPaymentMethod",I.AddToWishlist="addToWishlist",I.ContactMessage="contactMessage",I.Custom="custom",I.SyncCart="syncCart",I.Order="order",I.InitiateCheckout="initiateCheckout",I.AddToCart="addToCart",I.RemoveFromCart="removeFromCart",I.OneTimeItemPurchase="oneTimeItemPurchase",I.SubscriptionItemPurchase="subscriptionItemPurchase",I.ViewProduct="viewProduct",I.ViewPage="viewPage",I.ApplyPromotionalCode="applyPromotionalCode",I.KeywordSearch="keywordSearch",I.UserLoginSignup="userLoginSignup",I.UserLogin="userLogin",I.NewsletterSignup="newsletterSignup",I.Lead="lead",I.ChangeProductAttribute="changeProductAttribute",I.FilterItemsByAttribute="filterItemsByAttribute",I.Schedule="schedule",I.ViewContentItem="viewContentItem",I.StartTrial="startTrial",exports.ECommerceContentType=void 0,(w=exports.ECommerceContentType||(exports.ECommerceContentType={})).Undefined="undefined",w.SingleProduct="singleProduct",w.SingleVariant="singleVariant",w.Collection="collection",exports.ECommercePlatform=void 0,(x=exports.ECommercePlatform||(exports.ECommercePlatform={})).None="none",x.BigCommerce="bigCommerce",x.Shopify="shopify",x.OrderGroove="orderGroove",x.Magento="magento",x.Generic="generic",x.WooCommerce="wooCommerce",x.Demandware="demandware",exports.ECommerceFulfillmentStatus=void 0,(C=exports.ECommerceFulfillmentStatus||(exports.ECommerceFulfillmentStatus={})).Undefined="undefined",C.Fulfilled="fulfilled",C.NoneFulfilled="noneFulfilled",C.PartiallyFulfilled="partiallyFulfilled",C.RestockedOrCancelled="restockedOrCancelled",exports.ECommerceFinancialStatus=void 0,(b=exports.ECommerceFinancialStatus||(exports.ECommerceFinancialStatus={})).Undefined="undefined",b.Pending="pending",b.Authorized="authorized",b.PartiallyPaid="partiallyPaid",b.Paid="paid",b.PartiallyRefunded="partiallyRefunded",b.Refunded="refunded",b.Voided="voided",exports.ConvergePipelineLoggableActivityType=void 0,(E=exports.ConvergePipelineLoggableActivityType||(exports.ConvergePipelineLoggableActivityType={})).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",exports.SdkLogEventLevel=void 0,(T=exports.SdkLogEventLevel||(exports.SdkLogEventLevel={})).Information="information",T.Warning="warning",T.Error="error",T.Verbose="verbose",exports.SeekaWebhookCallType=void 0,(U=exports.SeekaWebhookCallType||(exports.SeekaWebhookCallType={})).None="none",U.Probe="probe",U.AppInstalled="appInstalled",U.IdentityChanged="identityChanged",U.ActivityAccepted="activityAccepted",U.AppInstallSettingsUpdated="appInstallSettingsUpdated",U.AppUninstalled="appUninstalled",U.BrowserSdkPlugin="browserSdkPlugin";class O 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 N(e,t,i,r,s){throw null!=s?s:new O(e,t,i,r,null)}function B(e){return e&&!0===e.isAxiosError}const _=()=>`${$(new Date)}.${R()}`,R=()=>Math.floor(8999999999*Math.random()+1e9).toString(),$=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}`},F=(e,t)=>e.reduce((e,i,r)=>{const s=Math.floor(r/t);return e[s]||(e[s]=[]),e[s].push(i),e},[]),L=async e=>{const t=await j(e),i=new r.Issuer(t);return i[r.custom.http_options]=(e,t)=>({timeout:1e4}),i},j=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...t}):console.debug("Seeka auth: getting issuer",{...t});const i=new v(e.appId,e.applicationInstallId),r=(s=e.issuerUrl,l.createHash("md5").update(s).digest("hex"));var s;return await i.getOrSet(r,async()=>({value:await M(e),expiryAbsoluteMilliseconds:36e5}),async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...t}):console.debug("Seeka auth: got issuer from cache",{...t})})},M=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};return e.logger?e.logger.info("Seeka auth: discovering issuer from server",{...t}):console.info("Seeka auth: discovering issuer from server",{...t}),(await r.Issuer.discover(e.issuerUrl)).metadata},q=async e=>{const t=new v(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=new((await L(e)).Client)({client_id:e.appId.replace(/-/g,""),client_secret:e.appSecret});try{const r=await i.grant({grant_type:"client_credentials"}),s={...t,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return e.logger?e.logger.info("Seeka auth: got client access token from server",{...s}):console.info("Seeka auth: got app client token from server",{...s}),r}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)return null;const i=await(async(e,t)=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}},r=new((await L(t)).Client)({client_id:t.appId.replace(/-/g,""),client_secret:t.appSecret});try{const s=await r.grant({grant_type:"app_install_token",applicationInstallId:t.applicationInstallId,access_token:e}),n={...i,token:{expires_at:s.expires_at,token_type:s.token_type,scope:s.scope}};return t.logger?t.logger.info("Seeka auth: got app access token from server",{...n}):console.info("Seeka auth: got app access token from server",{...n}),s}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})})},D=new p.default.Agent({keepAlive:!0,scheduling:"fifo"}),J=new u.default.Agent({keepAlive:!0,scheduling:"fifo"}),V=e=>{const t=d.default.create({httpAgent:D,httpsAgent:J});return t.interceptors.request.use(function(t){const i={url:t.url,method:t.method};return 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:o,url:a,method:c}=null==t?void 0:t.config,l={code:r,status:s,message:n,headers:o,url:a,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 z{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await q(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(g.identity.send,"mergeIdentity");const 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(g.identity.send,"mergeIdentityBatch");const i=_();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.info("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=F(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.info(`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(g.activity.send,"trackActivityBatch");const i=_();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.info("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=F(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.info(`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(g.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,i)},this.trackActivityForProfileIdBatch=async(e,t,i)=>{this.checkPermission(g.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(g.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,i)},this.trackActivityForProfileBatch=async(e,t,i)=>{this.checkPermission(g.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t})),i)},this.config=e,this.ingestionService=(e=>new k(e,e.ingestUrl,V(e)))(e),this.identityService=(e=>new y(e,e.ingestUrl,V(e)))(e)}}const K="x-seeka-signature-sha256",W=(e,t,i)=>{if(!t)return!1;let r=null;if(t.get&&"function"==typeof t.get)r=t.get(K);else{const e=t[K];e&&(Array.isArray(e)&&e.length>0?r=e[0]:("string"==typeof e||e instanceof String)&&(r=e))}if(!r)return!1;const s=G(e,i)===r;return s||console.warn("Invalid webhook signature"),s},G=(e,t)=>l.createHmac("sha256",e).update(t).digest("hex"),H=(e,t,i,r,s)=>{const n=new m;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:"1.1.0",client:i},n.logger=s,n.grantedPermissions=r,n.transformApiRequest=e=>X(n,e),n.transformApiResponse=async(e,t,i)=>Y(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},X=async(e,t)=>{const i=await q(e);return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},Y=async(e,t,i,r)=>(i.data=JSON.stringify(i.data),r(i));var Q;class Z{constructor(e,t){this.context=void 0,this.appCache=void 0,this.appInstallCache=void 0,this.api=void 0,this.logger=void 0,this.context=e,this.api=new z(e.config),this.appCache=new v(e.config.appId),this.appInstallCache=new v(e.config.appId,e.config.applicationInstallId),this.logger=t}}Q=Z,Z.create=(e,t,i,r,s)=>new Q({config:H({...t},e,{type:i.name,ver:i.version},r,s)},s),exports.ApiException=O,exports.ApiServiceProxyBase=f,exports.AppPermissionKeys=g,exports.IdentityServiceProxy=y,exports.IngestServiceProxy=k,exports.SeekaApiHelper=z,exports.SeekaAppCacheManager=v,exports.SeekaAppConfig=m,exports.SeekaAppHelper=Z,exports.chunk=F,exports.getActivityName=e=>{const t=Object.keys(exports.TrackingActivityNames),i=e.toLowerCase(),r=t.find(e=>e.toLowerCase()===i);return r?exports.TrackingActivityNames[r]:exports.TrackingActivityNames.Custom},exports.separatePersonFullName=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(" ")}},exports.throwOnInvalidWebhookSignature=(e,t,i)=>{if(!W(e,t,i))throw new Error("Invalid webhook signature")},exports.validateWebhookSignature=W,exports.webhookSignatureHeaderName=K;
1
+ var e=require("memory-cache"),t=require("crypto"),i=require("axios"),r=require("openid-client"),s=require("http"),n=require("https");function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}function a(e){if(e&&e.__esModule)return e;var t=Object.create(null);return e&&Object.keys(e).forEach(function(i){if("default"!==i){var r=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return e[i]}})}}),t.default=e,t}var c=/*#__PURE__*/a(e),l=/*#__PURE__*/a(t),d=/*#__PURE__*/o(i),p=/*#__PURE__*/o(s),u=/*#__PURE__*/o(n);const g={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},h="seeka:sdk";class v{constructor(e,t){this.appId=void 0,this.appInstallationId=void 0,this.set=async(e,t,i)=>{const r=this.getKey(e);c.put(r,JSON.stringify(t),i)},this.getOrSet=async(e,t,i)=>{const r=this.getKey(e),s=c.get(r);if(s){const e=JSON.parse(s);return i&&await i(e),e}const n=await t();return n?(c.put(r,JSON.stringify(n.value),n.expiryAbsoluteMilliseconds),n.value):null},this.getKey=e=>this.appInstallationId?`${h}:${this.appId}:${this.appInstallationId}:${e}`:`${h}:${this.appId}:${e}`,this.appId=e,this.appInstallationId=t}}class m{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 f{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 y extends f{constructor(e,t,i){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=i||d.default.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(B(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),N("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?N("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}class k extends f{constructor(e,t,i){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=i||d.default.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(B(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),N("A server side error occurred.",t,r,i,s)}if(422===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}if(400===t){const r=e.data;let s=null;return s=JSON.parse(r),N("A server side error occurred.",t,r,i,s)}return 200!==t&&204!==t?N("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}var S,P,A,I,w,x,C,b,E,T,U;exports.ResponseResultType=void 0,(S=exports.ResponseResultType||(exports.ResponseResultType={})).Undefined="undefined",S.Success="success",S.Failed="failed",exports.PrivacyConsentType=void 0,(P=exports.PrivacyConsentType||(exports.PrivacyConsentType={})).Unknown="unknown",P.Informed="informed",P.Implied="implied",P.Explicit="explicit",P.Active="active",P.Passive="passive",exports.TrackingEventSourceOriginType=void 0,(A=exports.TrackingEventSourceOriginType||(exports.TrackingEventSourceOriginType={})).Browser="browser",A.Server="server",A.Mobile="mobile",A.Desktop="desktop",A.PhysicalStore="physicalStore",A.Email="email",A.Phone="phone",A.Chat="chat",A.Automatic="automatic",exports.TrackingActivityNames=void 0,(I=exports.TrackingActivityNames||(exports.TrackingActivityNames={})).Undefined="undefined",I.PageViewOrganic="pageViewOrganic",I.PageViewUtmAttributed="pageViewUtmAttributed",I.AddPaymentMethod="addPaymentMethod",I.AddToWishlist="addToWishlist",I.ContactMessage="contactMessage",I.Custom="custom",I.SyncCart="syncCart",I.Order="order",I.InitiateCheckout="initiateCheckout",I.AddToCart="addToCart",I.RemoveFromCart="removeFromCart",I.OneTimeItemPurchase="oneTimeItemPurchase",I.SubscriptionItemPurchase="subscriptionItemPurchase",I.ViewProduct="viewProduct",I.ViewPage="viewPage",I.ApplyPromotionalCode="applyPromotionalCode",I.KeywordSearch="keywordSearch",I.UserLoginSignup="userLoginSignup",I.UserLogin="userLogin",I.NewsletterSignup="newsletterSignup",I.Lead="lead",I.ChangeProductAttribute="changeProductAttribute",I.FilterItemsByAttribute="filterItemsByAttribute",I.Schedule="schedule",I.ViewContentItem="viewContentItem",I.StartTrial="startTrial",exports.ECommerceContentType=void 0,(w=exports.ECommerceContentType||(exports.ECommerceContentType={})).Undefined="undefined",w.SingleProduct="singleProduct",w.SingleVariant="singleVariant",w.Collection="collection",exports.ECommercePlatform=void 0,(x=exports.ECommercePlatform||(exports.ECommercePlatform={})).None="none",x.BigCommerce="bigCommerce",x.Shopify="shopify",x.OrderGroove="orderGroove",x.Magento="magento",x.Generic="generic",x.WooCommerce="wooCommerce",x.Demandware="demandware",exports.ECommerceFulfillmentStatus=void 0,(C=exports.ECommerceFulfillmentStatus||(exports.ECommerceFulfillmentStatus={})).Undefined="undefined",C.Fulfilled="fulfilled",C.NoneFulfilled="noneFulfilled",C.PartiallyFulfilled="partiallyFulfilled",C.RestockedOrCancelled="restockedOrCancelled",exports.ECommerceFinancialStatus=void 0,(b=exports.ECommerceFinancialStatus||(exports.ECommerceFinancialStatus={})).Undefined="undefined",b.Pending="pending",b.Authorized="authorized",b.PartiallyPaid="partiallyPaid",b.Paid="paid",b.PartiallyRefunded="partiallyRefunded",b.Refunded="refunded",b.Voided="voided",exports.ConvergePipelineLoggableActivityType=void 0,(E=exports.ConvergePipelineLoggableActivityType||(exports.ConvergePipelineLoggableActivityType={})).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",exports.SdkLogEventLevel=void 0,(T=exports.SdkLogEventLevel||(exports.SdkLogEventLevel={})).Information="information",T.Warning="warning",T.Error="error",T.Verbose="verbose",exports.SeekaWebhookCallType=void 0,(U=exports.SeekaWebhookCallType||(exports.SeekaWebhookCallType={})).None="none",U.Probe="probe",U.AppInstalled="appInstalled",U.IdentityChanged="identityChanged",U.ActivityAccepted="activityAccepted",U.AppInstallSettingsUpdated="appInstallSettingsUpdated",U.AppUninstalled="appUninstalled",U.BrowserSdkPlugin="browserSdkPlugin";class O 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 N(e,t,i,r,s){throw null!=s?s:new O(e,t,i,r,null)}function B(e){return e&&!0===e.isAxiosError}const _=()=>`${$(new Date)}.${R()}`,R=()=>Math.floor(8999999999*Math.random()+1e9).toString(),$=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}`},F=(e,t)=>e.reduce((e,i,r)=>{const s=Math.floor(r/t);return e[s]||(e[s]=[]),e[s].push(i),e},[]),L=async e=>{const t=await j(e),i=new r.Issuer(t);return i[r.custom.http_options]=(e,t)=>({timeout:1e4}),i},j=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...t}):console.debug("Seeka auth: getting issuer",{...t});const i=new v(e.appId,e.applicationInstallId),r=(s=e.issuerUrl,l.createHash("md5").update(s).digest("hex"));var s;return await i.getOrSet(r,async()=>({value:await M(e),expiryAbsoluteMilliseconds:36e5}),async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...t}):console.debug("Seeka auth: got issuer from cache",{...t})})},M=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};return e.logger?e.logger.info("Seeka auth: discovering issuer from server",{...t}):console.info("Seeka auth: discovering issuer from server",{...t}),(await r.Issuer.discover(e.issuerUrl)).metadata},q=async e=>{const t=new v(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=new((await L(e)).Client)({client_id:e.appId.replace(/-/g,""),client_secret:e.appSecret});try{const r=await i.grant({grant_type:"client_credentials"}),s={...t,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return e.logger?e.logger.info("Seeka auth: got client access token from server",{...s}):console.info("Seeka auth: got app client token from server",{...s}),r}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)return null;const i=await(async(e,t)=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}},r=new((await L(t)).Client)({client_id:t.appId.replace(/-/g,""),client_secret:t.appSecret});try{const s=await r.grant({grant_type:"app_install_token",applicationInstallId:t.applicationInstallId,access_token:e}),n={...i,token:{expires_at:s.expires_at,token_type:s.token_type,scope:s.scope}};return t.logger?t.logger.info("Seeka auth: got app access token from server",{...n}):console.info("Seeka auth: got app access token from server",{...n}),s}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})})},D=new p.default.Agent({keepAlive:!0,scheduling:"fifo"}),J=new u.default.Agent({keepAlive:!0,scheduling:"fifo"}),V=e=>{const t=d.default.create({httpAgent:D,httpsAgent:J});return t.interceptors.request.use(function(t){const i={url:t.url,method:t.method};return 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:o,url:a,method:c}=null==t?void 0:t.config,l={code:r,status:s,message:n,headers:o,url:a,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 z{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await q(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(g.identity.send,"mergeIdentity");const 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(g.identity.send,"mergeIdentityBatch");const i=_();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.info("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=F(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.info(`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(g.activity.send,"trackActivityBatch");const i=_();var r;if(0===e.length)return void(null==(r=this.config.logger)||r.info("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=F(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.info(`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(g.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,i)},this.trackActivityForProfileIdBatch=async(e,t,i)=>{this.checkPermission(g.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(g.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,i)},this.trackActivityForProfileBatch=async(e,t,i)=>{this.checkPermission(g.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t})),i)},this.config=e,this.ingestionService=(e=>new k(e,e.ingestUrl,V(e)))(e),this.identityService=(e=>new y(e,e.ingestUrl,V(e)))(e)}}const K="x-seeka-signature-sha256",W=(e,t,i)=>{if(!t)return!1;let r=null;if(t.get&&"function"==typeof t.get)r=t.get(K);else{const e=t[K];e&&(Array.isArray(e)&&e.length>0?r=e[0]:("string"==typeof e||e instanceof String)&&(r=e))}if(!r)return!1;const s=G(e,i)===r;return s||console.warn("Invalid webhook signature"),s},G=(e,t)=>l.createHmac("sha256",e).update(t).digest("hex"),H=(e,t,i,r,s)=>{const n=new m;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:"1.1.1",client:i},n.logger=s,n.grantedPermissions=r,n.transformApiRequest=e=>X(n,e),n.transformApiResponse=async(e,t,i)=>Y(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},X=async(e,t)=>{const i=await q(e);return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},Y=async(e,t,i,r)=>(i.data=JSON.stringify(i.data),r(i));var Q;class Z{constructor(e,t){this.context=void 0,this.appCache=void 0,this.appInstallCache=void 0,this.api=void 0,this.logger=void 0,this.context=e,this.api=new z(e.config),this.appCache=new v(e.config.appId),this.appInstallCache=new v(e.config.appId,e.config.applicationInstallId),this.logger=t}}Q=Z,Z.create=(e,t,i,r,s)=>new Q({config:H({...t},e,{type:i.name,ver:i.version},r,s)},s),exports.ApiException=O,exports.ApiServiceProxyBase=f,exports.AppPermissionKeys=g,exports.IdentityServiceProxy=y,exports.IngestServiceProxy=k,exports.SeekaApiHelper=z,exports.SeekaAppCacheManager=v,exports.SeekaAppConfig=m,exports.SeekaAppHelper=Z,exports.chunk=F,exports.getActivityName=e=>{const t=Object.keys(exports.TrackingActivityNames),i=e.toLowerCase(),r=t.find(e=>e.toLowerCase()===i);return r?exports.TrackingActivityNames[r]:exports.TrackingActivityNames.Custom},exports.separatePersonFullName=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(" ")}},exports.throwOnInvalidWebhookSignature=(e,t,i)=>{if(!W(e,t,i))throw new Error("Invalid webhook signature")},exports.validateWebhookSignature=W,exports.webhookSignatureHeaderName=K;
2
2
  //# sourceMappingURL=sdk-apps-server.js.map
@@ -1,2 +1,2 @@
1
- import*as e from"memory-cache";import*as t from"crypto";import i from"axios";import{Issuer as s,custom as r}from"openid-client";import n from"http";import o from"https";const a={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},c="seeka:sdk";class l{constructor(t,i){this.appId=void 0,this.appInstallationId=void 0,this.set=async(t,i,s)=>{const r=this.getKey(t);e.put(r,JSON.stringify(i),s)},this.getOrSet=async(t,i,s)=>{const r=this.getKey(t),n=e.get(r);if(n){const e=JSON.parse(n);return s&&await s(e),e}const o=await i();return o?(e.put(r,JSON.stringify(o.value),o.expiryAbsoluteMilliseconds),o.value):null},this.getKey=e=>this.appInstallationId?`${c}:${this.appId}:${this.appInstallationId}:${e}`:`${c}:${this.appId}:${e}`,this.appId=t,this.appInstallationId=i}}class d{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 h{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 u extends h{constructor(e,t,s){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=s||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 s=JSON.stringify(e);return this.transformOptions({data:s,method:"POST",url:i,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(C(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 s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(422===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(400===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}return 200!==t&&204!==t?U("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}class g extends h{constructor(e,t,s){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=s||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 s=JSON.stringify(e);return this.transformOptions({data:s,method:"POST",url:i,headers:{"Content-Type":"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(C(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 s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(422===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(400===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}return 200!==t&&204!==t?U("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}var p,f,m,v,y,k,I,P,A,S,w;!function(e){e.Undefined="undefined",e.Success="success",e.Failed="failed"}(p||(p={})),function(e){e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive"}(f||(f={})),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"}(m||(m={})),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"}(v||(v={})),function(e){e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection"}(y||(y={})),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"}(k||(k={})),function(e){e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled"}(I||(I={})),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"}(P||(P={})),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"}(A||(A={})),function(e){e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose"}(S||(S={})),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"}(w||(w={}));class b extends Error{constructor(e,t,i,s,r){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=s,this.result=r}static isApiException(e){return!0===e.isApiException}}function U(e,t,i,s,r){throw null!=r?r:new b(e,t,i,s,null)}function C(e){return e&&!0===e.isAxiosError}const B=()=>`${_(new Date)}.${O()}`,E=e=>{const t=Object.keys(v),i=e.toLowerCase(),s=t.find(e=>e.toLowerCase()===i);return s?v[s]:v.Custom},O=()=>Math.floor(8999999999*Math.random()+1e9).toString(),_=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 s=e.getUTCHours().toString();s.length<2&&(s="0"+s);let r=e.getUTCMinutes().toString();r.length<2&&(r="0"+r);let n=e.getUTCSeconds().toString();return n.length<2&&(n="0"+n),`${e.getUTCFullYear()}${t}${i}.${s}${r}${n}`},x=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(" ")}},$=(e,t)=>e.reduce((e,i,s)=>{const r=Math.floor(s/t);return e[r]||(e[r]=[]),e[r].push(i),e},[]),N=async e=>{const t=await R(e),i=new s(t);return i[r.http_options]=(e,t)=>({timeout:1e4}),i},R=async e=>{const i={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...i}):console.debug("Seeka auth: getting issuer",{...i});const s=new l(e.appId,e.applicationInstallId),r=(n=e.issuerUrl,t.createHash("md5").update(n).digest("hex"));var n;return await s.getOrSet(r,async()=>({value:await F(e),expiryAbsoluteMilliseconds:36e5}),async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...i}):console.debug("Seeka auth: got issuer from cache",{...i})})},F=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};return e.logger?e.logger.info("Seeka auth: discovering issuer from server",{...t}):console.info("Seeka auth: discovering issuer from server",{...t}),(await s.discover(e.issuerUrl)).metadata},T=async e=>{const t=new l(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=new((await N(e)).Client)({client_id:e.appId.replace(/-/g,""),client_secret:e.appSecret});try{const s=await i.grant({grant_type:"client_credentials"}),r={...t,token:{expires_at:s.expires_at,token_type:s.token_type,scope:s.scope}};return e.logger?e.logger.info("Seeka auth: got client access token from server",{...r}):console.info("Seeka auth: got app client token from server",{...r}),s}catch(i){const s={...t,error:i};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...s}):console.debug("Seeka auth: failed to get client access token from server",{...s}),null}})(e);if(!t)return null;const i=await(async(e,t)=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}},s=new((await N(t)).Client)({client_id:t.appId.replace(/-/g,""),client_secret:t.appSecret});try{const r=await s.grant({grant_type:"app_install_token",applicationInstallId:t.applicationInstallId,access_token:e}),n={...i,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return t.logger?t.logger.info("Seeka auth: got app access token from server",{...n}):console.info("Seeka auth: got app access token from server",{...n}),r}catch(e){const s={...i,error:e};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...s}):console.debug("Seeka auth: failed to get app access token from server",{...s}),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})})},M=new n.Agent({keepAlive:!0,scheduling:"fifo"}),L=new o.Agent({keepAlive:!0,scheduling:"fifo"}),j=e=>{const t=i.create({httpAgent:M,httpsAgent:L});return t.interceptors.request.use(function(t){const i={url:t.url,method:t.method};return 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,s;const r={url:(null==(i=t.request)?void 0:i.url)||t.config.url,method:(null==(s=t.request)?void 0:s.method)||t.config.method,response:{status:t.status}};return e.logger?e.logger.http(`Seeka API: call to ${r.url} succeeded`,{...r}):console.debug(`Seeka API: call to ${r.url} succeeded`,{...r}),t},function(t){var i;const{code:s,status:r,message:n}=t,{headers:o,url:a,method:c}=null==t?void 0:t.config,l={code:s,status:r,message:n,headers:o,url:a,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 J{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await T(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(a.identity.send,"mergeIdentity");const s=B();return null==(i=(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:s,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?s:void 0,runtime:this.config.runtime}})).result)?void 0:i.personId},this.mergeIdentityBatch=async(e,t)=>{this.checkPermission(a.identity.send,"mergeIdentityBatch");const i=B();var s;if(0===e.length)return void(null==(s=this.config.logger)||s.info("No identities in batch"));const r={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=$(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:{...r}}}))}),n.length>1){const e=n.map((e,t)=>{var i;return 0===t?Promise.resolve():(null==(i=this.config.logger)||i.info(`Processing identity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({id:{id:e||{},src:{...r}}}))}))});await Promise.all(e)}},this.trackActivityBatch=async(e,t)=>{this.checkPermission(a.activity.send,"trackActivityBatch");const i=B();var s;if(0===e.length)return void(null==(s=this.config.logger)||s.info("No activities in batch"));const r={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=$(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:{...r},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.info(`Processing activity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({ev:{id:e.profile||{},src:{...r},payload:e.activity}}))}))});await Promise.all(e)}},this.trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)},this.trackActivityForProfileId=async(e,t,i)=>{this.checkPermission(a.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,i)},this.trackActivityForProfileIdBatch=async(e,t,i)=>{this.checkPermission(a.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(a.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,i)},this.trackActivityForProfileBatch=async(e,t,i)=>{this.checkPermission(a.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t})),i)},this.config=e,this.ingestionService=(e=>new g(e,e.ingestUrl,j(e)))(e),this.identityService=(e=>new u(e,e.ingestUrl,j(e)))(e)}}const D="x-seeka-signature-sha256",V=(e,t,i)=>{if(!t)return!1;let s=null;if(t.get&&"function"==typeof t.get)s=t.get(D);else{const e=t[D];e&&(Array.isArray(e)&&e.length>0?s=e[0]:("string"==typeof e||e instanceof String)&&(s=e))}if(!s)return!1;const r=q(e,i)===s;return r||console.warn("Invalid webhook signature"),r},q=(e,i)=>t.createHmac("sha256",e).update(i).digest("hex"),z=(e,t,i)=>{if(!V(e,t,i))throw new Error("Invalid webhook signature")},K=(e,t,i,s,r)=>{const n=new d;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:"1.1.0",client:i},n.logger=r,n.grantedPermissions=s,n.transformApiRequest=e=>G(n,e),n.transformApiResponse=async(e,t,i)=>W(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},G=async(e,t)=>{const i=await T(e);return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},W=async(e,t,i,s)=>(i.data=JSON.stringify(i.data),s(i));var H;class X{constructor(e,t){this.context=void 0,this.appCache=void 0,this.appInstallCache=void 0,this.api=void 0,this.logger=void 0,this.context=e,this.api=new J(e.config),this.appCache=new l(e.config.appId),this.appInstallCache=new l(e.config.appId,e.config.applicationInstallId),this.logger=t}}H=X,X.create=(e,t,i,s,r)=>new H({config:K({...t},e,{type:i.name,ver:i.version},s,r)},r);export{b as ApiException,h as ApiServiceProxyBase,a as AppPermissionKeys,A as ConvergePipelineLoggableActivityType,y as ECommerceContentType,P as ECommerceFinancialStatus,I as ECommerceFulfillmentStatus,k as ECommercePlatform,u as IdentityServiceProxy,g as IngestServiceProxy,f as PrivacyConsentType,p as ResponseResultType,S as SdkLogEventLevel,J as SeekaApiHelper,l as SeekaAppCacheManager,d as SeekaAppConfig,X as SeekaAppHelper,w as SeekaWebhookCallType,v as TrackingActivityNames,m as TrackingEventSourceOriginType,$ as chunk,E as getActivityName,x as separatePersonFullName,z as throwOnInvalidWebhookSignature,V as validateWebhookSignature,D as webhookSignatureHeaderName};
1
+ import*as e from"memory-cache";import*as t from"crypto";import i from"axios";import{Issuer as s,custom as r}from"openid-client";import n from"http";import o from"https";const a={identity:{receiveFull:"Identity.Receive.Pii",send:"Identity.Send"},activity:{receiveAnon:"Activity.Receive.Anon",receiveFull:"Activity.Receive.Pii",send:"Activity.Send"}},c="seeka:sdk";class l{constructor(t,i){this.appId=void 0,this.appInstallationId=void 0,this.set=async(t,i,s)=>{const r=this.getKey(t);e.put(r,JSON.stringify(i),s)},this.getOrSet=async(t,i,s)=>{const r=this.getKey(t),n=e.get(r);if(n){const e=JSON.parse(n);return s&&await s(e),e}const o=await i();return o?(e.put(r,JSON.stringify(o.value),o.expiryAbsoluteMilliseconds),o.value):null},this.getKey=e=>this.appInstallationId?`${c}:${this.appId}:${this.appInstallationId}:${e}`:`${c}:${this.appId}:${e}`,this.appId=t,this.appInstallationId=i}}class d{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 h{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 u extends h{constructor(e,t,s){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=s||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 s=JSON.stringify(e);return this.transformOptions({data:s,method:"POST",url:i,headers:{"Content-Type":"application/json",Accept:"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(C(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 s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(422===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(400===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}return 200!==t&&204!==t?U("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}class g extends h{constructor(e,t,s){super(e),this.instance=void 0,this.baseUrl=void 0,this.jsonParseReviver=void 0,this.instance=s||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 s=JSON.stringify(e);return this.transformOptions({data:s,method:"POST",url:i,headers:{"Content-Type":"application/json"},cancelToken:t}).then(e=>this.instance.request(e)).catch(e=>{if(C(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 s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(422===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}if(400===t){const s=e.data;let r=null;return r=JSON.parse(s),U("A server side error occurred.",t,s,i,r)}return 200!==t&&204!==t?U("An unexpected server error occurred.",t,e.data,i):Promise.resolve(null)}}var p,f,m,v,y,k,I,P,A,S,w;!function(e){e.Undefined="undefined",e.Success="success",e.Failed="failed"}(p||(p={})),function(e){e.Unknown="unknown",e.Informed="informed",e.Implied="implied",e.Explicit="explicit",e.Active="active",e.Passive="passive"}(f||(f={})),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"}(m||(m={})),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"}(v||(v={})),function(e){e.Undefined="undefined",e.SingleProduct="singleProduct",e.SingleVariant="singleVariant",e.Collection="collection"}(y||(y={})),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"}(k||(k={})),function(e){e.Undefined="undefined",e.Fulfilled="fulfilled",e.NoneFulfilled="noneFulfilled",e.PartiallyFulfilled="partiallyFulfilled",e.RestockedOrCancelled="restockedOrCancelled"}(I||(I={})),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"}(P||(P={})),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"}(A||(A={})),function(e){e.Information="information",e.Warning="warning",e.Error="error",e.Verbose="verbose"}(S||(S={})),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"}(w||(w={}));class b extends Error{constructor(e,t,i,s,r){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=s,this.result=r}static isApiException(e){return!0===e.isApiException}}function U(e,t,i,s,r){throw null!=r?r:new b(e,t,i,s,null)}function C(e){return e&&!0===e.isAxiosError}const B=()=>`${_(new Date)}.${O()}`,E=e=>{const t=Object.keys(v),i=e.toLowerCase(),s=t.find(e=>e.toLowerCase()===i);return s?v[s]:v.Custom},O=()=>Math.floor(8999999999*Math.random()+1e9).toString(),_=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 s=e.getUTCHours().toString();s.length<2&&(s="0"+s);let r=e.getUTCMinutes().toString();r.length<2&&(r="0"+r);let n=e.getUTCSeconds().toString();return n.length<2&&(n="0"+n),`${e.getUTCFullYear()}${t}${i}.${s}${r}${n}`},x=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(" ")}},$=(e,t)=>e.reduce((e,i,s)=>{const r=Math.floor(s/t);return e[r]||(e[r]=[]),e[r].push(i),e},[]),N=async e=>{const t=await R(e),i=new s(t);return i[r.http_options]=(e,t)=>({timeout:1e4}),i},R=async e=>{const i={applicationId:e.appId,issuer:{url:e.issuerUrl}};e.logger?e.logger.debug("Seeka auth: getting issuer",{...i}):console.debug("Seeka auth: getting issuer",{...i});const s=new l(e.appId,e.applicationInstallId),r=(n=e.issuerUrl,t.createHash("md5").update(n).digest("hex"));var n;return await s.getOrSet(r,async()=>({value:await F(e),expiryAbsoluteMilliseconds:36e5}),async()=>{e.logger?e.logger.verbose("Seeka auth: got issuer from cache",{...i}):console.debug("Seeka auth: got issuer from cache",{...i})})},F=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};return e.logger?e.logger.info("Seeka auth: discovering issuer from server",{...t}):console.info("Seeka auth: discovering issuer from server",{...t}),(await s.discover(e.issuerUrl)).metadata},T=async e=>{const t=new l(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=new((await N(e)).Client)({client_id:e.appId.replace(/-/g,""),client_secret:e.appSecret});try{const s=await i.grant({grant_type:"client_credentials"}),r={...t,token:{expires_at:s.expires_at,token_type:s.token_type,scope:s.scope}};return e.logger?e.logger.info("Seeka auth: got client access token from server",{...r}):console.info("Seeka auth: got app client token from server",{...r}),s}catch(i){const s={...t,error:i};return e.logger?e.logger.error("Seeka auth: failed to get client access token from server",{...s}):console.debug("Seeka auth: failed to get client access token from server",{...s}),null}})(e);if(!t)return null;const i=await(async(e,t)=>{const i={applicationId:t.appId,issuer:{url:t.issuerUrl}},s=new((await N(t)).Client)({client_id:t.appId.replace(/-/g,""),client_secret:t.appSecret});try{const r=await s.grant({grant_type:"app_install_token",applicationInstallId:t.applicationInstallId,access_token:e}),n={...i,token:{expires_at:r.expires_at,token_type:r.token_type,scope:r.scope}};return t.logger?t.logger.info("Seeka auth: got app access token from server",{...n}):console.info("Seeka auth: got app access token from server",{...n}),r}catch(e){const s={...i,error:e};return t.logger?t.logger.error("Seeka auth: failed to get app access token from server",{...s}):console.debug("Seeka auth: failed to get app access token from server",{...s}),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})})},M=new n.Agent({keepAlive:!0,scheduling:"fifo"}),L=new o.Agent({keepAlive:!0,scheduling:"fifo"}),j=e=>{const t=i.create({httpAgent:M,httpsAgent:L});return t.interceptors.request.use(function(t){const i={url:t.url,method:t.method};return 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,s;const r={url:(null==(i=t.request)?void 0:i.url)||t.config.url,method:(null==(s=t.request)?void 0:s.method)||t.config.method,response:{status:t.status}};return e.logger?e.logger.http(`Seeka API: call to ${r.url} succeeded`,{...r}):console.debug(`Seeka API: call to ${r.url} succeeded`,{...r}),t},function(t){var i;const{code:s,status:r,message:n}=t,{headers:o,url:a,method:c}=null==t?void 0:t.config,l={code:s,status:r,message:n,headers:o,url:a,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 J{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await T(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(a.identity.send,"mergeIdentity");const s=B();return null==(i=(await this.identityService.merge({id:e,src:{method:"",origin:t.origin,time:void 0,loc:t.loc,sess:s,diag:"true"===process.env.SEEKA_DEBUG_ENABLED?s:void 0,runtime:this.config.runtime}})).result)?void 0:i.personId},this.mergeIdentityBatch=async(e,t)=>{this.checkPermission(a.identity.send,"mergeIdentityBatch");const i=B();var s;if(0===e.length)return void(null==(s=this.config.logger)||s.info("No identities in batch"));const r={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=$(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:{...r}}}))}),n.length>1){const e=n.map((e,t)=>{var i;return 0===t?Promise.resolve():(null==(i=this.config.logger)||i.info(`Processing identity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({id:{id:e||{},src:{...r}}}))}))});await Promise.all(e)}},this.trackActivityBatch=async(e,t)=>{this.checkPermission(a.activity.send,"trackActivityBatch");const i=B();var s;if(0===e.length)return void(null==(s=this.config.logger)||s.info("No activities in batch"));const r={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=$(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:{...r},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.info(`Processing activity batch ${t+1} of ${n.length}`),this.trackActivityBatchRaw({data:e.map(e=>({ev:{id:e.profile||{},src:{...r},payload:e.activity}}))}))});await Promise.all(e)}},this.trackActivityBatchRaw=async e=>{await this.ingestionService.batch(e)},this.trackActivityForProfileId=async(e,t,i)=>{this.checkPermission(a.activity.send,"trackActivityForProfileId"),await this.trackActivityForProfileIdBatch([e],t,i)},this.trackActivityForProfileIdBatch=async(e,t,i)=>{this.checkPermission(a.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(a.activity.send,"trackActivityForProfile"),await this.trackActivityForProfileBatch([e],t,i)},this.trackActivityForProfileBatch=async(e,t,i)=>{this.checkPermission(a.activity.send,"trackActivityForProfileBatch"),await this.trackActivityBatch(e.map(e=>({activity:e,profile:t})),i)},this.config=e,this.ingestionService=(e=>new g(e,e.ingestUrl,j(e)))(e),this.identityService=(e=>new u(e,e.ingestUrl,j(e)))(e)}}const D="x-seeka-signature-sha256",V=(e,t,i)=>{if(!t)return!1;let s=null;if(t.get&&"function"==typeof t.get)s=t.get(D);else{const e=t[D];e&&(Array.isArray(e)&&e.length>0?s=e[0]:("string"==typeof e||e instanceof String)&&(s=e))}if(!s)return!1;const r=q(e,i)===s;return r||console.warn("Invalid webhook signature"),r},q=(e,i)=>t.createHmac("sha256",e).update(i).digest("hex"),z=(e,t,i)=>{if(!V(e,t,i))throw new Error("Invalid webhook signature")},K=(e,t,i,s,r)=>{const n=new d;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:"1.1.1",client:i},n.logger=r,n.grantedPermissions=s,n.transformApiRequest=e=>G(n,e),n.transformApiResponse=async(e,t,i)=>W(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},G=async(e,t)=>{const i=await T(e);return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},W=async(e,t,i,s)=>(i.data=JSON.stringify(i.data),s(i));var H;class X{constructor(e,t){this.context=void 0,this.appCache=void 0,this.appInstallCache=void 0,this.api=void 0,this.logger=void 0,this.context=e,this.api=new J(e.config),this.appCache=new l(e.config.appId),this.appInstallCache=new l(e.config.appId,e.config.applicationInstallId),this.logger=t}}H=X,X.create=(e,t,i,s,r)=>new H({config:K({...t},e,{type:i.name,ver:i.version},s,r)},r);export{b as ApiException,h as ApiServiceProxyBase,a as AppPermissionKeys,A as ConvergePipelineLoggableActivityType,y as ECommerceContentType,P as ECommerceFinancialStatus,I as ECommerceFulfillmentStatus,k as ECommercePlatform,u as IdentityServiceProxy,g as IngestServiceProxy,f as PrivacyConsentType,p as ResponseResultType,S as SdkLogEventLevel,J as SeekaApiHelper,l as SeekaAppCacheManager,d as SeekaAppConfig,X as SeekaAppHelper,w as SeekaWebhookCallType,v as TrackingActivityNames,m as TrackingEventSourceOriginType,$ as chunk,E as getActivityName,x as separatePersonFullName,z as throwOnInvalidWebhookSignature,V as validateWebhookSignature,D as webhookSignatureHeaderName};
2
2
  //# sourceMappingURL=sdk-apps-server.module.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seeka-labs/sdk-apps-server",
3
- "version": "1.1.0",
3
+ "version": "1.1.1",
4
4
  "description": "Seeka - Apps SDK - Node.js",
5
5
  "author": "SEEKA <platform@seeka.co>",
6
6
  "license": "MIT",