@seeka-labs/sdk-apps-server 1.1.24 → 1.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,19 +1,19 @@
1
- MIT License
2
-
3
- Permission is hereby granted, free of charge, to any person obtaining a copy
4
- of this software and associated documentation files (the "Software"), to deal
5
- in the Software without restriction, including without limitation the rights
6
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
- copies of the Software, and to permit persons to whom the Software is
8
- furnished to do so, subject to the following conditions:
9
-
10
- The above copyright notice and this permission notice shall be included in all
11
- copies or substantial portions of the Software.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
- SOFTWARE.
1
+ MIT License
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -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),p=/*#__PURE__*/o(t),d=/*#__PURE__*/o(i),u=/*#__PURE__*/o(s),h=/*#__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"}},v="seeka:sdk";class m{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?`${v}:${this.appId}:${this.appInstallationId}:${e}`:`${v}:${this.appId}:${e}`,this.appId=e,this.appInstallationId=t}}class y{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 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.seeka.services"}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(q(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 A 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.seeka.services"}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(q(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 S,P,I,x,w,C,b,T,E,N,O,U,F,B,_,L;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,(I=exports.TrackingEventSourceOriginType||(exports.TrackingEventSourceOriginType={})).Browser="browser",I.Server="server",I.Mobile="mobile",I.Desktop="desktop",I.PhysicalStore="physicalStore",I.Email="email",I.Phone="phone",I.Chat="chat",I.Automatic="automatic",exports.TrackingActivityNames=void 0,(x=exports.TrackingActivityNames||(exports.TrackingActivityNames={})).Undefined="undefined",x.PageViewOrganic="pageViewOrganic",x.PageViewUtmAttributed="pageViewUtmAttributed",x.AddPaymentMethod="addPaymentMethod",x.AddToWishlist="addToWishlist",x.ContactMessage="contactMessage",x.Custom="custom",x.SyncCart="syncCart",x.Order="order",x.InitiateCheckout="initiateCheckout",x.AddToCart="addToCart",x.RemoveFromCart="removeFromCart",x.OneTimeItemPurchase="oneTimeItemPurchase",x.SubscriptionItemPurchase="subscriptionItemPurchase",x.ViewProduct="viewProduct",x.ViewPage="viewPage",x.ApplyPromotionalCode="applyPromotionalCode",x.KeywordSearch="keywordSearch",x.UserLoginSignup="userLoginSignup",x.UserLogin="userLogin",x.NewsletterSignup="newsletterSignup",x.Lead="lead",x.ChangeProductAttribute="changeProductAttribute",x.FilterItemsByAttribute="filterItemsByAttribute",x.Schedule="schedule",x.ViewContentItem="viewContentItem",x.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,(C=exports.ECommercePlatform||(exports.ECommercePlatform={})).None="none",C.BigCommerce="bigCommerce",C.Shopify="shopify",C.OrderGroove="orderGroove",C.Magento="magento",C.Generic="generic",C.WooCommerce="wooCommerce",C.Demandware="demandware",exports.ECommerceFulfillmentStatus=void 0,(b=exports.ECommerceFulfillmentStatus||(exports.ECommerceFulfillmentStatus={})).Undefined="undefined",b.Fulfilled="fulfilled",b.NoneFulfilled="noneFulfilled",b.PartiallyFulfilled="partiallyFulfilled",b.RestockedOrCancelled="restockedOrCancelled",b.Pending="pending",exports.ECommerceFinancialStatus=void 0,(T=exports.ECommerceFinancialStatus||(exports.ECommerceFinancialStatus={})).Undefined="undefined",T.Pending="pending",T.Authorized="authorized",T.PartiallyPaid="partiallyPaid",T.Paid="paid",T.PartiallyRefunded="partiallyRefunded",T.Refunded="refunded",T.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,(N=exports.SdkLogEventLevel||(exports.SdkLogEventLevel={})).Information="information",N.Warning="warning",N.Error="error",N.Verbose="verbose",exports.SeekaWebhookCallType=void 0,(O=exports.SeekaWebhookCallType||(exports.SeekaWebhookCallType={})).None="none",O.Probe="probe",O.AppInstalled="appInstalled",O.IdentityChanged="identityChanged",O.ActivityAccepted="activityAccepted",O.AppInstallSettingsUpdated="appInstallSettingsUpdated",O.AppUninstalled="appUninstalled",O.BrowserSdkPlugin="browserSdkPlugin",exports.ClickAttributionSourcePlatform=void 0,(U=exports.ClickAttributionSourcePlatform||(exports.ClickAttributionSourcePlatform={})).Unknown="unknown",U.Google="google",U.Meta="meta",U.Snapchat="snapchat",U.Pinterest="pinterest",U.TikTok="tikTok",exports.ActivityPipelineActivityFilterType=void 0,(F=exports.ActivityPipelineActivityFilterType||(exports.ActivityPipelineActivityFilterType={})).Undefined="undefined",F.PurchaseMade="purchaseMade",F.ActivityTracked="activityTracked",exports.ConditionComparer=void 0,(B=exports.ConditionComparer||(exports.ConditionComparer={})).Undefined="undefined",B.And="and",B.Or="or",exports.ActivityPipelineActivityFilterSourceItemType=void 0,(_=exports.ActivityPipelineActivityFilterSourceItemType||(exports.ActivityPipelineActivityFilterSourceItemType={})).Undefined="undefined",_.Domain="domain",_.Pipeline="pipeline",_.Wildcard="wildcard",_.Url="url",_.PagePath="pagePath",exports.ConditionOperator=void 0,(L=exports.ConditionOperator||(exports.ConditionOperator={})).Undefined="undefined",L.Equals="equals",L.NotEquals="notEquals",L.Contains="contains",L.NotContains="notContains",L.StartsWith="startsWith",L.EndsWith="endsWith",L.IsNull="isNull",L.NotNull="notNull",L.IsTrue="isTrue",L.IsFalse="isFalse",L.GreaterThanOrEquals="greaterThanOrEquals",L.LessThanOrEquals="lessThanOrEquals",L.GreaterThan="greaterThan",L.LessThan="lessThan",L.Before="before",L.After="after",L.Between="between",L.In="in",L.NotIn="notIn",L.Regex="regEx",L.Any="any";class R 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 R(e,t,i,r,null)}function q(e){return e&&!0===e.isAxiosError}const M=()=>`${W(new Date)}.${j()}`,j=()=>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}`},D=(e,t)=>e.reduce((e,i,r)=>{const s=Math.floor(r/t);return e[s]||(e[s]=[]),e[s].push(i),e},[]),J=async e=>{const t=await V(e),i=new r.Issuer(t);return i[r.custom.http_options]=(e,t)=>({timeout:1e4}),i},V=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 m(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 G(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})})},G=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};return e.logger?e.logger.verbose("Seeka auth: discovering issuer from server",{...t}):console.info("Seeka auth: discovering issuer from server",{...t}),(await r.Issuer.discover(e.issuerUrl)).metadata},z=async e=>{const t=new m(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 J(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.verbose("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 J(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.verbose("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})})},K=new u.default.Agent({keepAlive:!0,scheduling:"fifo"}),H=new h.default.Agent({keepAlive:!0,scheduling:"fifo"}),X=e=>{const t=d.default.create({httpAgent:K,httpsAgent:H});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 Y{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await z(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=M();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=M();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=D(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(g.activity.send,"trackActivityBatch");const i=M();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=D(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(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 A(e,e.ingestUrl,X(e)))(e),this.identityService=(e=>new k(e,e.ingestUrl,X(e)))(e)}}const Q="x-seeka-signature-sha256",Z=(e,t,i)=>{if(!t)return!1;let r=null;if(t.get&&"function"==typeof t.get)r=t.get(Q);else{const e=t[Q];e&&(Array.isArray(e)&&e.length>0?r=e[0]:("string"==typeof e||e instanceof String)&&(r=e))}if(!r)return!1;const s=ee(e,i)===r;return s||console.warn("Invalid webhook signature"),s},ee=(e,t)=>l.createHmac("sha256",e).update(t).digest("hex"),te=(e,t,i,r,s)=>{const n=new y;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.24",client:i},n.logger=s,n.grantedPermissions=r,n.transformApiRequest=e=>ie(n,e),n.transformApiResponse=async(e,t,i)=>re(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},ie=async(e,t)=>{const i=await z(e);return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},re=async(e,t,i,r)=>(i.data=JSON.stringify(i.data),r(i)),se="aes-192-cbc",ne=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to encrypt data");const i=p.default.scryptSync(t,"salt",24),r=p.default.randomBytes(16),s=p.default.createCipheriv(se,i,r);return[s.update(e,"utf8","hex")+s.final("hex"),Buffer.from(r).toString("hex")].join("|")},oe=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to decrypt data");const[i,r]=e.split("|");if(!r)throw new Error("IV not found");const s=p.default.scryptSync(t,"salt",24),n=p.default.createDecipheriv(se,s,Buffer.from(r,"hex"));return n.update(i,"hex","utf8")+n.final("utf8")};class ae{constructor(e){this.appSecret=void 0,this.encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return ne(e,this.appSecret)},this.decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return oe(e,this.appSecret)},this.appSecret=e}}var ce;class le{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 Y(e.config),this.appCache=new m(e.config.appId),this.appInstallCache=new m(e.config.appId,e.config.applicationInstallId),this.crypto=new ae(e.config.appSecret),this.logger=t}}ce=le,le.create=(e,t,i,r,s)=>new ce({config:te({...t},e,{type:i.name,ver:i.version},r,s)},s);const pe=[exports.TrackingActivityNames.Order,exports.TrackingActivityNames.SubscriptionItemPurchase,exports.TrackingActivityNames.OneTimeItemPurchase];exports.ApiException=R,exports.ApiServiceProxyBase=f,exports.AppPermissionKeys=g,exports.IdentityServiceProxy=k,exports.IngestServiceProxy=A,exports.SeekaApiHelper=Y,exports.SeekaAppCacheManager=m,exports.SeekaAppConfig=y,exports.SeekaAppHelper=le,exports.chunk=D,exports.decryptText=oe,exports.encryptText=ne,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.isValidSeekaProfileId=function(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))},exports.matchActivityPipelineFilters=(e,t,i)=>{if(!e.activity)return[];const r=e.activity,s=r.activityName===exports.TrackingActivityNames.Custom?r.activityNameCustom:r.activityName;if(!s)return[];const n=s.toLowerCase(),o=[];return t.forEach(t=>{var a;if(!t)return;switch(t.type){case exports.ActivityPipelineActivityFilterType.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 exports.ActivityPipelineActivityFilterType.PurchaseMade:if(!r.activityName||!pe.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,p=null!=l&&l.loc?new URL(l.loc).hostname.toLowerCase():null,d=null==l?void 0:l.pipeline,u=null==d||null==(a=d.convergePipelineIntegrationInstanceId)?void 0:a.toLowerCase(),h=c.filters?c.filters.map(e=>{switch(e.type){case exports.ActivityPipelineActivityFilterSourceItemType.Wildcard:return i.verbose("Matched wildcard source filter",{sourceFilter:e}),!0;case exports.ActivityPipelineActivityFilterSourceItemType.Domain:return!(!p||!e.key||p!==e.key.toLowerCase()||(i.verbose("Matched domain source filter",{sourceFilter:e,activityHostname:p}),0));case exports.ActivityPipelineActivityFilterSourceItemType.Pipeline:return!(!u||!e.key||u!==e.key.toLowerCase()||(i.verbose("Matched pipeline source filter",{sourceFilter:e,sourceConvergePipelineIntegrationInstanceId:u}),0))}}):[];switch(c.comparer){case exports.ConditionComparer.And:h.every(e=>!0===e)||o.push(t);break;case exports.ConditionComparer.Or:h.some(e=>!0===e)&&o.push(t);break;default:i.warn("Unknown source filter comparer",{sourceFilters:c})}}),o},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(!Z(e,t,i))throw new Error("Invalid webhook signature")},exports.validateWebhookSignature=Z,exports.webhookSignatureHeaderName=Q;
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),p=/*#__PURE__*/o(t),d=/*#__PURE__*/o(i),u=/*#__PURE__*/o(s),h=/*#__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"}},v="seeka:sdk";class m{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?`${v}:${this.appId}:${this.appInstallationId}:${e}`:`${v}:${this.appId}:${e}`,this.appId=e,this.appInstallationId=t}}class y{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 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.seeka.services"}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(q(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 A 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.seeka.services"}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(q(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 S,P,I,x,w,C,b,T,E,N,O,U,F,B,_,L;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,(I=exports.TrackingEventSourceOriginType||(exports.TrackingEventSourceOriginType={})).Browser="browser",I.Server="server",I.Mobile="mobile",I.Desktop="desktop",I.PhysicalStore="physicalStore",I.Email="email",I.Phone="phone",I.Chat="chat",I.Automatic="automatic",exports.TrackingActivityNames=void 0,(x=exports.TrackingActivityNames||(exports.TrackingActivityNames={})).Undefined="undefined",x.PageViewOrganic="pageViewOrganic",x.PageViewUtmAttributed="pageViewUtmAttributed",x.AddPaymentMethod="addPaymentMethod",x.AddToWishlist="addToWishlist",x.ContactMessage="contactMessage",x.Custom="custom",x.SyncCart="syncCart",x.Order="order",x.InitiateCheckout="initiateCheckout",x.AddToCart="addToCart",x.RemoveFromCart="removeFromCart",x.OneTimeItemPurchase="oneTimeItemPurchase",x.SubscriptionItemPurchase="subscriptionItemPurchase",x.ViewProduct="viewProduct",x.ViewPage="viewPage",x.ApplyPromotionalCode="applyPromotionalCode",x.KeywordSearch="keywordSearch",x.UserLoginSignup="userLoginSignup",x.UserLogin="userLogin",x.NewsletterSignup="newsletterSignup",x.Lead="lead",x.ChangeProductAttribute="changeProductAttribute",x.FilterItemsByAttribute="filterItemsByAttribute",x.Schedule="schedule",x.ViewContentItem="viewContentItem",x.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,(C=exports.ECommercePlatform||(exports.ECommercePlatform={})).None="none",C.BigCommerce="bigCommerce",C.Shopify="shopify",C.OrderGroove="orderGroove",C.Magento="magento",C.Generic="generic",C.WooCommerce="wooCommerce",C.Demandware="demandware",exports.ECommerceFulfillmentStatus=void 0,(b=exports.ECommerceFulfillmentStatus||(exports.ECommerceFulfillmentStatus={})).Undefined="undefined",b.Fulfilled="fulfilled",b.NoneFulfilled="noneFulfilled",b.PartiallyFulfilled="partiallyFulfilled",b.RestockedOrCancelled="restockedOrCancelled",b.Pending="pending",exports.ECommerceFinancialStatus=void 0,(T=exports.ECommerceFinancialStatus||(exports.ECommerceFinancialStatus={})).Undefined="undefined",T.Pending="pending",T.Authorized="authorized",T.PartiallyPaid="partiallyPaid",T.Paid="paid",T.PartiallyRefunded="partiallyRefunded",T.Refunded="refunded",T.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,(N=exports.SdkLogEventLevel||(exports.SdkLogEventLevel={})).Information="information",N.Warning="warning",N.Error="error",N.Verbose="verbose",exports.SeekaWebhookCallType=void 0,(O=exports.SeekaWebhookCallType||(exports.SeekaWebhookCallType={})).None="none",O.Probe="probe",O.AppInstalled="appInstalled",O.IdentityChanged="identityChanged",O.ActivityAccepted="activityAccepted",O.AppInstallSettingsUpdated="appInstallSettingsUpdated",O.AppUninstalled="appUninstalled",O.BrowserSdkPlugin="browserSdkPlugin",exports.ClickAttributionSourcePlatform=void 0,(U=exports.ClickAttributionSourcePlatform||(exports.ClickAttributionSourcePlatform={})).Unknown="unknown",U.Google="google",U.Meta="meta",U.Snapchat="snapchat",U.Pinterest="pinterest",U.TikTok="tikTok",exports.ActivityPipelineActivityFilterType=void 0,(F=exports.ActivityPipelineActivityFilterType||(exports.ActivityPipelineActivityFilterType={})).Undefined="undefined",F.PurchaseMade="purchaseMade",F.ActivityTracked="activityTracked",exports.ConditionComparer=void 0,(B=exports.ConditionComparer||(exports.ConditionComparer={})).Undefined="undefined",B.And="and",B.Or="or",exports.ActivityPipelineActivityFilterSourceItemType=void 0,(_=exports.ActivityPipelineActivityFilterSourceItemType||(exports.ActivityPipelineActivityFilterSourceItemType={})).Undefined="undefined",_.Domain="domain",_.Pipeline="pipeline",_.Wildcard="wildcard",_.Url="url",_.PagePath="pagePath",exports.ConditionOperator=void 0,(L=exports.ConditionOperator||(exports.ConditionOperator={})).Undefined="undefined",L.Equals="equals",L.NotEquals="notEquals",L.Contains="contains",L.NotContains="notContains",L.StartsWith="startsWith",L.EndsWith="endsWith",L.IsNull="isNull",L.NotNull="notNull",L.IsTrue="isTrue",L.IsFalse="isFalse",L.GreaterThanOrEquals="greaterThanOrEquals",L.LessThanOrEquals="lessThanOrEquals",L.GreaterThan="greaterThan",L.LessThan="lessThan",L.Before="before",L.After="after",L.Between="between",L.In="in",L.NotIn="notIn",L.Regex="regEx",L.Any="any";class R 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 R(e,t,i,r,null)}function q(e){return e&&!0===e.isAxiosError}const M=()=>`${W(new Date)}.${j()}`,j=()=>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}`},D=(e,t)=>e.reduce((e,i,r)=>{const s=Math.floor(r/t);return e[s]||(e[s]=[]),e[s].push(i),e},[]),J=async e=>{const t=await V(e),i=new r.Issuer(t);return i[r.custom.http_options]=(e,t)=>({timeout:1e4}),i},V=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 m(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 G(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})})},G=async e=>{const t={applicationId:e.appId,issuer:{url:e.issuerUrl}};return e.logger?e.logger.verbose("Seeka auth: discovering issuer from server",{...t}):console.info("Seeka auth: discovering issuer from server",{...t}),(await r.Issuer.discover(e.issuerUrl)).metadata},z=async e=>{const t=new m(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 J(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.verbose("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 J(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.verbose("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})})},K=new u.default.Agent({keepAlive:!0,scheduling:"fifo"}),H=new h.default.Agent({keepAlive:!0,scheduling:"fifo"}),X=e=>{const t=d.default.create({httpAgent:K,httpsAgent:H});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 Y{constructor(e){this.config=void 0,this.maxBatchSize=50,this.refreshOrPrimeTokenCache=async()=>{await z(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=M();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=M();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=D(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(g.activity.send,"trackActivityBatch");const i=M();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=D(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(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 A(e,e.ingestUrl,X(e)))(e),this.identityService=(e=>new k(e,e.ingestUrl,X(e)))(e)}}const Q="x-seeka-signature-sha256",Z=(e,t,i)=>{if(!t)return!1;let r=null;if(t.get&&"function"==typeof t.get)r=t.get(Q);else{const e=t[Q];e&&(Array.isArray(e)&&e.length>0?r=e[0]:("string"==typeof e||e instanceof String)&&(r=e))}if(!r)return!1;const s=ee(e,i)===r;return s||console.warn("Invalid webhook signature"),s},ee=(e,t)=>l.createHmac("sha256",e).update(t).digest("hex"),te=(e,t,i,r,s)=>{const n=new y;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.25",client:i},n.logger=s,n.grantedPermissions=r,n.transformApiRequest=e=>ie(n,e),n.transformApiResponse=async(e,t,i)=>re(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},ie=async(e,t)=>{const i=await z(e);return t.headers={...t.headers,"X-OrgId":e.organisationId,Authorization:"Bearer "+(null==i?void 0:i.access_token)},t},re=async(e,t,i,r)=>(i.data=JSON.stringify(i.data),r(i)),se="aes-192-cbc",ne=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to encrypt data");const i=p.default.scryptSync(t,"salt",24),r=p.default.randomBytes(16),s=p.default.createCipheriv(se,i,r);return[s.update(e,"utf8","hex")+s.final("hex"),Buffer.from(r).toString("hex")].join("|")},oe=(e,t)=>{if(!e)return"";if(!t)throw new Error("Secret is required to decrypt data");const[i,r]=e.split("|");if(!r)throw new Error("IV not found");const s=p.default.scryptSync(t,"salt",24),n=p.default.createDecipheriv(se,s,Buffer.from(r,"hex"));return n.update(i,"hex","utf8")+n.final("utf8")};class ae{constructor(e){this.appSecret=void 0,this.encryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to encrypt data");return ne(e,this.appSecret)},this.decryptWithAppSecret=e=>{if(!this.appSecret)throw new Error("App secret is required to decrypt data");return oe(e,this.appSecret)},this.appSecret=e}}var ce;class le{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 Y(e.config),this.appCache=new m(e.config.appId),this.appInstallCache=new m(e.config.appId,e.config.applicationInstallId),this.crypto=new ae(e.config.appSecret),this.logger=t}}ce=le,le.create=(e,t,i,r,s)=>new ce({config:te({...t},e,{type:i.name,ver:i.version},r,s)},s);const pe=[exports.TrackingActivityNames.Order,exports.TrackingActivityNames.SubscriptionItemPurchase,exports.TrackingActivityNames.OneTimeItemPurchase];exports.ApiException=R,exports.ApiServiceProxyBase=f,exports.AppPermissionKeys=g,exports.IdentityServiceProxy=k,exports.IngestServiceProxy=A,exports.SeekaApiHelper=Y,exports.SeekaAppCacheManager=m,exports.SeekaAppConfig=y,exports.SeekaAppHelper=le,exports.chunk=D,exports.decryptText=oe,exports.encryptText=ne,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.isValidSeekaProfileId=function(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))},exports.matchActivityPipelineFilters=(e,t,i)=>{if(!e.activity)return[];const r=e.activity,s=r.activityName===exports.TrackingActivityNames.Custom?r.activityNameCustom:r.activityName;if(!s)return[];const n=s.toLowerCase(),o=[];return t.forEach(t=>{var a;if(!t)return;switch(t.type){case exports.ActivityPipelineActivityFilterType.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 exports.ActivityPipelineActivityFilterType.PurchaseMade:if(!r.activityName||!pe.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,p=null!=l&&l.loc?new URL(l.loc).hostname.toLowerCase():null,d=null==l?void 0:l.pipeline,u=null==d||null==(a=d.convergePipelineIntegrationInstanceId)?void 0:a.toLowerCase(),h=c.filters?c.filters.map(e=>{switch(e.type){case exports.ActivityPipelineActivityFilterSourceItemType.Wildcard:return i.verbose("Matched wildcard source filter",{sourceFilter:e}),!0;case exports.ActivityPipelineActivityFilterSourceItemType.Domain:return!(!p||!e.key||p!==e.key.toLowerCase()||(i.verbose("Matched domain source filter",{sourceFilter:e,activityHostname:p}),0));case exports.ActivityPipelineActivityFilterSourceItemType.Pipeline:return!(!u||!e.key||u!==e.key.toLowerCase()||(i.verbose("Matched pipeline source filter",{sourceFilter:e,sourceConvergePipelineIntegrationInstanceId:u}),0))}}):[];switch(c.comparer){case exports.ConditionComparer.And:h.every(e=>!0===e)||o.push(t);break;case exports.ConditionComparer.Or:h.some(e=>!0===e)&&o.push(t);break;default:i.warn("Unknown source filter comparer",{sourceFilters:c})}}),o},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(!Z(e,t,i))throw new Error("Invalid webhook signature")},exports.validateWebhookSignature=Z,exports.webhookSignatureHeaderName=Q;
2
2
  //# sourceMappingURL=sdk-apps-server.js.map