@knocklabs/client 0.19.4 → 0.20.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.20.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 01d07af: Fix TypeScript type mismatch in SetPreferencesProperties. All fields (workflows, categories, channel_types, channels) are now optional to match the nullable nature of PreferenceSet returned by getPreferences(). This allows users to pass preference data without type errors and properly supports partial updates.
8
+
9
+ ## 0.20.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 2d29ebf: [guides] update selectGuides and useGuides to be subject to throttling by default
14
+
3
15
  ## 0.19.4
4
16
 
5
17
  ### Patch Changes
package/dist/cjs/api.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var i=Object.defineProperty;var o=(t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var r=(t,e,s)=>o(t,typeof e!="symbol"?e+"":e,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("axios"),c=require("axios-retry"),l=require("phoenix"),n=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},h=n(u),a=n(c);class d{constructor(e){r(this,"host");r(this,"apiKey");r(this,"userToken");r(this,"branch");r(this,"axiosClient");r(this,"socket");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.branch=e.branch||null,this.axiosClient=h.default.create({baseURL:this.host,headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-Knock-User-Token":this.userToken,"X-Knock-Client":this.getKnockClientHeader(),"X-Knock-Branch":this.branch}}),typeof window<"u"&&(this.socket=new l.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey,branch_slug:this.branch}})),a.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:a.default.exponentialDelay})}async makeRequest(e){try{const s=await this.axiosClient(e);return{statusCode:s.status<300?"ok":"error",body:s.data,error:void 0,status:s.status}}catch(s){return console.error(s),{statusCode:"error",status:500,body:void 0,error:s}}}canRetryRequest(e){return a.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.19.4"}}exports.default=d;
1
+ "use strict";var i=Object.defineProperty;var o=(t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var r=(t,e,s)=>o(t,typeof e!="symbol"?e+"":e,s);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const u=require("axios"),c=require("axios-retry"),l=require("phoenix"),n=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},h=n(u),a=n(c);class d{constructor(e){r(this,"host");r(this,"apiKey");r(this,"userToken");r(this,"branch");r(this,"axiosClient");r(this,"socket");this.host=e.host,this.apiKey=e.apiKey,this.userToken=e.userToken||null,this.branch=e.branch||null,this.axiosClient=h.default.create({baseURL:this.host,headers:{Accept:"application/json","Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,"X-Knock-User-Token":this.userToken,"X-Knock-Client":this.getKnockClientHeader(),"X-Knock-Branch":this.branch}}),typeof window<"u"&&(this.socket=new l.Socket(`${this.host.replace("http","ws")}/ws/v1`,{params:{user_token:this.userToken,api_key:this.apiKey,branch_slug:this.branch}})),a.default(this.axiosClient,{retries:3,retryCondition:this.canRetryRequest,retryDelay:a.default.exponentialDelay})}async makeRequest(e){try{const s=await this.axiosClient(e);return{statusCode:s.status<300?"ok":"error",body:s.data,error:void 0,status:s.status}}catch(s){return console.error(s),{statusCode:"error",status:500,body:void 0,error:s}}}canRetryRequest(e){return a.default.isNetworkError(e)?!0:e.response?e.response.status>=500&&e.response.status<=599||e.response.status===429:!1}getKnockClientHeader(){return"Knock/ClientJS 0.20.1"}}exports.default=d;
2
2
  //# sourceMappingURL=api.js.map
@@ -1,2 +1,2 @@
1
- "use strict";var m=Object.defineProperty;var v=(u,e,t)=>e in u?m(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var c=(u,e,t)=>v(u,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("@tanstack/store"),b=require("urlpattern-polyfill"),d=require("./helpers.js"),I=50,C=30*1e3,E=3,g={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},k="knock_guide_debug",p=()=>{if(typeof window<"u")return window},G=u=>`/v1/users/${u}/guides`,f=()=>{const u=p();if(!u)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(u.location.search),t=e.get(g.GUIDE_KEY),s=e.get(g.PREVIEW_SESSION_ID);if(t||s){if(u.localStorage)try{const r={forcedGuideKey:t,previewSessionId:s};u.localStorage.setItem(k,JSON.stringify(r))}catch{}return{forcedGuideKey:t,previewSessionId:s}}let i=null,n=null;if(u.localStorage)try{const r=u.localStorage.getItem(k);if(r){const o=w(r);i=o.forcedGuideKey,n=o.previewSessionId}}catch{}return{forcedGuideKey:i,previewSessionId:n}},w=u=>{try{const e=JSON.parse(u);return{forcedGuideKey:(e==null?void 0:e.forcedGuideKey)??null,previewSessionId:(e==null?void 0:e.previewSessionId)??null}}catch{return{forcedGuideKey:null,previewSessionId:null}}},S=(u,e={})=>{const t=new d.SelectionResult,s=d.findDefaultGroup(u.guideGroups);if(!s)return t;const i=[...s.display_sequence],n=u.location;if(u.debug.forcedGuideKey){const r=i.indexOf(u.debug.forcedGuideKey);r>-1&&i.splice(r,1),i.unshift(u.debug.forcedGuideKey)}for(const[r,o]of i.entries()){let a=u.guides[o];u.debug.forcedGuideKey===o&&u.previewGuides[o]&&(a=u.previewGuides[o]),!(!a||!R(a,{location:n,filters:e,debug:u.debug}))&&t.set(r,a)}return t.metadata={guideGroup:s},t},R=(u,{location:e,filters:t={},debug:s={}})=>{if(t.type&&t.type!==u.type||t.key&&t.key!==u.key)return!1;if(s.forcedGuideKey===u.key)return!0;if(!u.active||u.steps.every(o=>!!o.message.archived_at))return!1;const i=e?d.newUrl(e):void 0,n=u.activation_url_rules||[],r=u.activation_url_patterns||[];if(i&&n.length>0){if(!d.predicateUrlRules(i,n))return!1}else if(i&&r.length>0&&!d.predicateUrlPatterns(i,r))return!1;return!0};class P{constructor(e,t,s={},i={}){c(this,"store");c(this,"socket");c(this,"socketChannel");c(this,"socketChannelTopic");c(this,"socketEventTypes",["guide.added","guide.updated","guide.removed","guide_group.added","guide_group.updated","guide.live_preview_updated"]);c(this,"subscribeRetryCount",0);c(this,"pushStateFn");c(this,"replaceStateFn");c(this,"stage");c(this,"counterIntervalId");c(this,"handleLocationChange",()=>{this.knock.log("[Guide] .handleLocationChange");const e=p();if(!(e!=null&&e.location))return;const t=e.location.href;if(this.store.state.location===t)return;this.knock.log(`[Guide] Detected a location change: ${t}`);const s=this.store.state.debug,i=f();this.setLocation(t,{debug:i}),this.checkDebugStateChanged(s,i)&&(this.knock.log("[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())});this.knock=e,this.channelId=t,this.targetParams=s,this.options=i;const{trackLocationFromWindow:n=!0,throttleCheckInterval:r=C}=i,o=p(),a=n?o==null?void 0:o.location.href:void 0,l=f();this.store=new _.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},previewGuides:{},queries:{},location:a,counter:0,debug:l});const{socket:h}=this.knock.client();this.socket=h,this.socketChannelTopic=`guides:${t}`,n&&this.listenForLocationChangesFromWindow(),r&&this.startCounterInterval(r),this.knock.log("[Guide] Initialized a guide client")}incrementCounter(){this.knock.log("[Guide] Incrementing the counter"),this.store.setState(e=>({...e,counter:e.counter+1}))}startCounterInterval(e){this.counterIntervalId=setInterval(()=>{this.knock.log("[Guide] Counter interval tick"),!(this.stage&&this.stage.status!=="closed")&&this.incrementCounter()},e)}clearCounterInterval(){this.counterIntervalId&&(clearInterval(this.counterIntervalId),this.counterIntervalId=void 0)}cleanup(){this.unsubscribe(),this.removeLocationChangeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}async fetch(e){this.knock.log("[Guide] .fetch"),this.knock.failIfNotAuthenticated();const t=this.buildQueryParams(e==null?void 0:e.filters),s=this.formatQueryKey(t),i=this.store.state.queries[s];if(i)return i;this.store.setState(r=>({...r,queries:{...r.queries,[s]:{status:"loading"}}}));let n;try{this.knock.log("[Guide] Fetching all eligible guides");const r=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"};const{entries:o,guide_groups:a,guide_group_display_logs:l}=r;this.knock.log("[Guide] Loading fetched guides"),this.store.setState(h=>({...h,guideGroups:(a==null?void 0:a.length)>0?a:[d.mockDefaultGroup(o)],guideGroupDisplayLogs:l||{},guides:d.byKey(o.map(y=>this.localCopy(y))),queries:{...h.queries,[s]:n}}))}catch(r){n={status:"error",error:r},this.store.setState(o=>({...o,queries:{...o.queries,[s]:n}}))}return n}subscribe(){if(!this.socket)return;this.knock.failIfNotAuthenticated(),this.knock.log("[Guide] Subscribing to real time updates"),this.socket.isConnected()||this.socket.connect(),this.socketChannel&&this.unsubscribe();const e=this.store.state.debug,t={...this.targetParams,user_id:this.knock.userId,force_all_guides:e.forcedGuideKey?!0:void 0,preview_session_id:e.previewSessionId||void 0},s=this.socket.channel(this.socketChannelTopic,t);for(const i of this.socketEventTypes)s.on(i,n=>this.handleSocketEvent(n));["closed","errored"].includes(s.state)&&(this.subscribeRetryCount=0,s.join().receive("ok",()=>{this.knock.log("[Guide] Successfully joined channel")}).receive("error",i=>{this.knock.log(`[Guide] Failed to join channel: ${JSON.stringify(i)}`),this.handleChannelJoinError()}).receive("timeout",()=>{this.knock.log("[Guide] Channel join timed out"),this.handleChannelJoinError()})),this.socketChannel=s}handleChannelJoinError(){if(this.subscribeRetryCount>=E){this.knock.log(`[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`),this.unsubscribe();return}this.subscribeRetryCount++}unsubscribe(){if(this.socketChannel){this.knock.log("[Guide] Unsubscribing from real time updates");for(const e of this.socketEventTypes)this.socketChannel.off(e);this.socketChannel.leave(),this.socketChannel=void 0}}handleSocketEvent(e){const{event:t,data:s}=e;switch(t){case"guide.added":return this.addOrReplaceGuide(e);case"guide.updated":return s.eligible?this.addOrReplaceGuide(e):this.removeGuide(e);case"guide.removed":return this.removeGuide(e);case"guide_group.added":case"guide_group.updated":return this.addOrReplaceGuideGroup(e);case"guide.live_preview_updated":return this.updatePreviewGuide(e);default:return}}setLocation(e,t={}){this.knock.log(`[Guide] .setLocation (loc=${e})`),this.clearGroupStage(),this.knock.log("[Guide] Updating the tracked location"),this.store.setState(s=>{var n;const i=(n=t==null?void 0:t.debug)!=null&&n.previewSessionId?s.previewGuides:{};return{...s,...t,previewGuides:i,location:e}})}exitDebugMode(){this.knock.log("[Guide] Exiting debug mode");const e=p();if(e!=null&&e.localStorage)try{e.localStorage.removeItem(k)}catch{}if(this.store.setState(t=>({...t,debug:{forcedGuideKey:null,previewSessionId:null},previewGuides:{}})),e){const t=new URL(e.location.href);(t.searchParams.has(g.GUIDE_KEY)||t.searchParams.has(g.PREVIEW_SESSION_ID))&&(t.searchParams.delete(g.GUIDE_KEY),t.searchParams.delete(g.PREVIEW_SESSION_ID),e.location.href=t.toString())}}selectGuides(e,t={}){if(this.knock.log(`[Guide] .selectGuides (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0)return this.knock.log("[Guide] Exiting selection (no guides)"),[];const s=S(e,t);return s.size===0?(this.knock.log("[Guide] Selection returned zero result"),[]):[...s.values()]}selectGuide(e,t={}){if(this.knock.log(`[Guide] .selectGuide (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0){this.knock.log("[Guide] Exiting selection (no guides)");return}const s=S(e,t);if(s.size===0){this.knock.log("[Guide] Selection found zero result");return}const[i,n]=[...s][0];if(this.knock.log(`[Guide] Selection found: \`${n.key}\` (total: ${s.size})`),n.bypass_global_group_limit)return this.knock.log(`[Guide] Returning the unthrottled guide: ${n.key}`),n;const r=d.findDefaultGroup(e.guideGroups),o=e.guideGroupDisplayLogs[d.DEFAULT_GROUP_KEY];if(r&&r.display_interval&&o&&d.checkIfThrottled(o,r.display_interval)){this.knock.log(`[Guide] Throttling the selected guide: ${n.key}`);return}switch(this.stage||(this.stage=this.openGroupStage()),this.stage.status){case"open":{this.knock.log(`[Guide] Adding to the group stage: ${n.key}`),this.stage.ordered[i]=n.key;return}case"patch":{this.knock.log(`[Guide] Patching the group stage: ${n.key}`),this.stage.ordered[i]=n.key;const a=this.stage.resolved===n.key?n:void 0;return this.knock.log(`[Guide] Returning \`${a==null?void 0:a.key}\` (stage: ${d.formatGroupStage(this.stage)})`),a}case"closed":{const a=this.stage.resolved===n.key?n:void 0;return this.knock.log(`[Guide] Returning \`${a==null?void 0:a.key}\` (stage: ${d.formatGroupStage(this.stage)})`),a}}}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=I}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],timeoutId:t},this.stage}closePendingGroupStage(){if(this.knock.log("[Guide] .closePendingGroupStage"),!this.stage||this.stage.status==="closed")return;this.ensureClearTimeout();let e;return this.store.state.debug.forcedGuideKey&&(e=this.stage.ordered.find(t=>t===this.store.state.debug.forcedGuideKey)),e||(e=this.stage.ordered.find(t=>t!==void 0)),this.knock.log(`[Guide] Closing the current group stage: resolved=${e}`),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var s;if(this.knock.log("[Guide] .patchClosedGroupStage"),((s=this.stage)==null?void 0:s.status)!=="closed")return;const{orderResolutionDuration:e=0}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.knock.log("[Guide] Patching the current group stage"),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:t},this.stage}clearGroupStage(){this.knock.log("[Guide] .clearGroupStage"),this.stage&&(this.knock.log("[Guide] Clearing the current group stage"),this.ensureClearTimeout(),this.stage=void 0)}ensureClearTimeout(){var e;(e=this.stage)!=null&&e.timeoutId&&clearTimeout(this.stage.timeoutId)}_selectGuide(e,t={}){return this.openGroupStage(),this.selectGuide(e,t),this.closePendingGroupStage(),this.selectGuide(e,t)}async markAsSeen(e,t){if(t.message.seen_at)return;this.knock.log(`[Guide] Marking as seen (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{seen_at:new Date().toISOString()});if(!s)return;const i={...this.buildEngagementEventBaseParams(e,s),content:s.content,data:this.targetParams.data};return this.knock.user.markGuideStepAs("seen",i),s}async markAsInteracted(e,t,s){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}; Step ref:${t.ref})`);const i=new Date().toISOString(),n=this.setStepMessageAttrs(e.key,t.ref,{read_at:i,interacted_at:i});if(!n)return;const r={...this.buildEngagementEventBaseParams(e,n),metadata:s};return this.knock.user.markGuideStepAs("interacted",r),n}async markAsArchived(e,t){if(t.message.archived_at)return;this.knock.log(`[Guide] Marking as archived (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{archived_at:new Date().toISOString()});if(!s)return;const i=this.buildEngagementEventBaseParams(e,s);return this.knock.user.markGuideStepAs("archived",{...i,unthrottled:e.bypass_global_group_limit}),s}localCopy(e){const t=this,s={...e,getStep(){return t.store.state.debug.forcedGuideKey===this.key?this.steps[0]:this.steps.find(i=>!i.message.archived_at)}};return s.getStep=s.getStep.bind(s),s.steps=e.steps.map(({message:i,...n})=>{const r={...n,message:{...i},markAsSeen(){if(!this.message.seen_at)return t.markAsSeen(s,this)},markAsInteracted({metadata:o}={}){return t.markAsInteracted(s,this,o)},markAsArchived(){if(!this.message.archived_at)return t.markAsArchived(s,this)}};return r.markAsSeen=r.markAsSeen.bind(r),r.markAsInteracted=r.markAsInteracted.bind(r),r.markAsArchived=r.markAsArchived.bind(r),r}),s.activation_url_patterns=e.activation_url_patterns.map(i=>({...i,pattern:new b.URLPattern({pathname:i.pathname})})),s}buildQueryParams(e={}){const t={...this.targetParams,...e};this.store.state.debug.forcedGuideKey&&(t.force_all_guides=!0);let i=Object.fromEntries(Object.entries(t).filter(([n,r])=>r!=null));return i=i.data?{...i,data:JSON.stringify(i.data)}:i,i}formatQueryKey(e){const s=Object.keys(e).sort().map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`).join("&"),i=G(this.knock.userId);return s?`${i}?${s}`:i}setStepMessageAttrs(e,t,s){let i;return s.archived_at&&this.clearGroupStage(),this.store.setState(n=>{let r=n.guides[e];if(!r)return n;const o=r.steps.map(h=>(h.ref!==t||(h.message={...h.message,...s},i=h),h));r=i?{...r,steps:o}:r;const a={...n.guides,[r.key]:r},l=s.archived_at&&!r.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[d.DEFAULT_GROUP_KEY]:s.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:a,guideGroupDisplayLogs:l}}),i}buildEngagementEventBaseParams(e,t){return{channel_id:e.channel_id,guide_key:e.key,guide_id:e.id,guide_step_ref:t.ref,tenant:this.targetParams.tenant}}addOrReplaceGuide({data:e}){this.patchClosedGroupStage();const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.guides,[t.key]:t};return{...s,guides:i}})}removeGuide({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const{[e.guide.key]:s,...i}=t.guides;return{...t,guides:i}})}addOrReplaceGuideGroup({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const s=[e.guide_group],i=e.guide_group.display_sequence_unthrottled||[],n=e.guide_group.display_sequence_throttled||[];let r=t.guides;return r=i.reduce((o,a)=>{if(!o[a])return o;const l={...o[a],bypass_global_group_limit:!0};return{...o,[a]:l}},r),r=n.reduce((o,a)=>{if(!o[a])return o;const l={...o[a],bypass_global_group_limit:!1};return{...o,[a]:l}},r),{...t,guides:r,guideGroups:s}})}updatePreviewGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>{const i={...s.previewGuides,[t.key]:t};return{...s,previewGuides:i}})}checkDebugStateChanged(e,t){return!!e.forcedGuideKey!=!!t.forcedGuideKey||e.previewSessionId!==t.previewSessionId}listenForLocationChangesFromWindow(){const e=p();if(e!=null&&e.history){e.addEventListener("popstate",this.handleLocationChange),e.addEventListener("hashchange",this.handleLocationChange);const t=e.history.pushState,s=e.history.replaceState;e.history.pushState=new Proxy(t,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),e.history.replaceState=new Proxy(s,{apply:(i,n,r)=>{Reflect.apply(i,n,r),setTimeout(()=>{this.handleLocationChange()},0)}}),this.pushStateFn=t,this.replaceStateFn=s}else this.knock.log("[Guide] Unable to access the `window.history` object to detect location changes")}removeLocationChangeEventListeners(){const e=p();e!=null&&e.history&&(e.removeEventListener("popstate",this.handleLocationChange),e.removeEventListener("hashchange",this.handleLocationChange),this.pushStateFn&&(e.history.pushState=this.pushStateFn,this.pushStateFn=void 0),this.replaceStateFn&&(e.history.replaceState=this.replaceStateFn,this.replaceStateFn=void 0))}}exports.DEBUG_QUERY_PARAMS=g;exports.KnockGuideClient=P;exports.guidesApiRootPath=G;
1
+ "use strict";var m=Object.defineProperty;var v=(u,e,t)=>e in u?m(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var c=(u,e,t)=>v(u,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("@tanstack/store"),b=require("urlpattern-polyfill"),d=require("./helpers.js"),I=50,C=30*1e3,E=3,g={GUIDE_KEY:"knock_guide_key",PREVIEW_SESSION_ID:"knock_preview_session_id"},k="knock_guide_debug",p=()=>{if(typeof window<"u")return window},G=u=>`/v1/users/${u}/guides`,f=()=>{const u=p();if(!u)return{forcedGuideKey:null,previewSessionId:null};const e=new URLSearchParams(u.location.search),t=e.get(g.GUIDE_KEY),s=e.get(g.PREVIEW_SESSION_ID);if(t||s){if(u.localStorage)try{const i={forcedGuideKey:t,previewSessionId:s};u.localStorage.setItem(k,JSON.stringify(i))}catch{}return{forcedGuideKey:t,previewSessionId:s}}let r=null,n=null;if(u.localStorage)try{const i=u.localStorage.getItem(k);if(i){const o=w(i);r=o.forcedGuideKey,n=o.previewSessionId}}catch{}return{forcedGuideKey:r,previewSessionId:n}},w=u=>{try{const e=JSON.parse(u);return{forcedGuideKey:(e==null?void 0:e.forcedGuideKey)??null,previewSessionId:(e==null?void 0:e.previewSessionId)??null}}catch{return{forcedGuideKey:null,previewSessionId:null}}},S=(u,e={})=>{const t=new d.SelectionResult,s=d.findDefaultGroup(u.guideGroups);if(!s)return t;const r=[...s.display_sequence],n=u.location;if(u.debug.forcedGuideKey){const i=r.indexOf(u.debug.forcedGuideKey);i>-1&&r.splice(i,1),r.unshift(u.debug.forcedGuideKey)}for(const[i,o]of r.entries()){let a=u.guides[o];u.debug.forcedGuideKey===o&&u.previewGuides[o]&&(a=u.previewGuides[o]),!(!a||!R(a,{location:n,filters:e,debug:u.debug}))&&t.set(i,a)}return t.metadata={guideGroup:s},t},R=(u,{location:e,filters:t={},debug:s={}})=>{if(t.type&&t.type!==u.type||t.key&&t.key!==u.key)return!1;if(s.forcedGuideKey===u.key)return!0;if(!u.active||u.steps.every(o=>!!o.message.archived_at))return!1;const r=e?d.newUrl(e):void 0,n=u.activation_url_rules||[],i=u.activation_url_patterns||[];if(r&&n.length>0){if(!d.predicateUrlRules(r,n))return!1}else if(r&&i.length>0&&!d.predicateUrlPatterns(r,i))return!1;return!0};class P{constructor(e,t,s={},r={}){c(this,"store");c(this,"socket");c(this,"socketChannel");c(this,"socketChannelTopic");c(this,"socketEventTypes",["guide.added","guide.updated","guide.removed","guide_group.added","guide_group.updated","guide.live_preview_updated"]);c(this,"subscribeRetryCount",0);c(this,"pushStateFn");c(this,"replaceStateFn");c(this,"stage");c(this,"counterIntervalId");c(this,"handleLocationChange",()=>{this.knock.log("[Guide] .handleLocationChange");const e=p();if(!(e!=null&&e.location))return;const t=e.location.href;if(this.store.state.location===t)return;this.knock.log(`[Guide] Detected a location change: ${t}`);const s=this.store.state.debug,r=f();this.setLocation(t,{debug:r}),this.checkDebugStateChanged(s,r)&&(this.knock.log("[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel"),this.fetch(),this.subscribe())});this.knock=e,this.channelId=t,this.targetParams=s,this.options=r;const{trackLocationFromWindow:n=!0,throttleCheckInterval:i=C}=r,o=p(),a=n?o==null?void 0:o.location.href:void 0,l=f();this.store=new _.Store({guideGroups:[],guideGroupDisplayLogs:{},guides:{},previewGuides:{},queries:{},location:a,counter:0,debug:l});const{socket:h}=this.knock.client();this.socket=h,this.socketChannelTopic=`guides:${t}`,n&&this.listenForLocationChangesFromWindow(),i&&this.startCounterInterval(i),this.knock.log("[Guide] Initialized a guide client")}incrementCounter(){this.knock.log("[Guide] Incrementing the counter"),this.store.setState(e=>({...e,counter:e.counter+1}))}startCounterInterval(e){this.counterIntervalId=setInterval(()=>{this.knock.log("[Guide] Counter interval tick"),!(this.stage&&this.stage.status!=="closed")&&this.incrementCounter()},e)}clearCounterInterval(){this.counterIntervalId&&(clearInterval(this.counterIntervalId),this.counterIntervalId=void 0)}cleanup(){this.unsubscribe(),this.removeLocationChangeEventListeners(),this.clearGroupStage(),this.clearCounterInterval()}async fetch(e){this.knock.log("[Guide] .fetch"),this.knock.failIfNotAuthenticated();const t=this.buildQueryParams(e==null?void 0:e.filters),s=this.formatQueryKey(t),r=this.store.state.queries[s];if(r)return r;this.store.setState(i=>({...i,queries:{...i.queries,[s]:{status:"loading"}}}));let n;try{this.knock.log("[Guide] Fetching all eligible guides");const i=await this.knock.user.getGuides(this.channelId,t);n={status:"ok"};const{entries:o,guide_groups:a,guide_group_display_logs:l}=i;this.knock.log("[Guide] Loading fetched guides"),this.store.setState(h=>({...h,guideGroups:(a==null?void 0:a.length)>0?a:[d.mockDefaultGroup(o)],guideGroupDisplayLogs:l||{},guides:d.byKey(o.map(y=>this.localCopy(y))),queries:{...h.queries,[s]:n}}))}catch(i){n={status:"error",error:i},this.store.setState(o=>({...o,queries:{...o.queries,[s]:n}}))}return n}subscribe(){if(!this.socket)return;this.knock.failIfNotAuthenticated(),this.knock.log("[Guide] Subscribing to real time updates"),this.socket.isConnected()||this.socket.connect(),this.socketChannel&&this.unsubscribe();const e=this.store.state.debug,t={...this.targetParams,user_id:this.knock.userId,force_all_guides:e.forcedGuideKey?!0:void 0,preview_session_id:e.previewSessionId||void 0},s=this.socket.channel(this.socketChannelTopic,t);for(const r of this.socketEventTypes)s.on(r,n=>this.handleSocketEvent(n));["closed","errored"].includes(s.state)&&(this.subscribeRetryCount=0,s.join().receive("ok",()=>{this.knock.log("[Guide] Successfully joined channel")}).receive("error",r=>{this.knock.log(`[Guide] Failed to join channel: ${JSON.stringify(r)}`),this.handleChannelJoinError()}).receive("timeout",()=>{this.knock.log("[Guide] Channel join timed out"),this.handleChannelJoinError()})),this.socketChannel=s}handleChannelJoinError(){if(this.subscribeRetryCount>=E){this.knock.log(`[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`),this.unsubscribe();return}this.subscribeRetryCount++}unsubscribe(){if(this.socketChannel){this.knock.log("[Guide] Unsubscribing from real time updates");for(const e of this.socketEventTypes)this.socketChannel.off(e);this.socketChannel.leave(),this.socketChannel=void 0}}handleSocketEvent(e){const{event:t,data:s}=e;switch(t){case"guide.added":return this.addOrReplaceGuide(e);case"guide.updated":return s.eligible?this.addOrReplaceGuide(e):this.removeGuide(e);case"guide.removed":return this.removeGuide(e);case"guide_group.added":case"guide_group.updated":return this.addOrReplaceGuideGroup(e);case"guide.live_preview_updated":return this.updatePreviewGuide(e);default:return}}setLocation(e,t={}){this.knock.log(`[Guide] .setLocation (loc=${e})`),this.clearGroupStage(),this.knock.log("[Guide] Updating the tracked location"),this.store.setState(s=>{var n;const r=(n=t==null?void 0:t.debug)!=null&&n.previewSessionId?s.previewGuides:{};return{...s,...t,previewGuides:r,location:e}})}exitDebugMode(){this.knock.log("[Guide] Exiting debug mode");const e=p();if(e!=null&&e.localStorage)try{e.localStorage.removeItem(k)}catch{}if(this.store.setState(t=>({...t,debug:{forcedGuideKey:null,previewSessionId:null},previewGuides:{}})),e){const t=new URL(e.location.href);(t.searchParams.has(g.GUIDE_KEY)||t.searchParams.has(g.PREVIEW_SESSION_ID))&&(t.searchParams.delete(g.GUIDE_KEY),t.searchParams.delete(g.PREVIEW_SESSION_ID),e.location.href=t.toString())}}selectGuides(e,t={},s={}){if(this.knock.log(`[Guide] .selectGuides (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),!this.selectGuide(e,t,s))return[];const n=[...S(e,t).values()];if(!s.includeThrottled&&d.checkStateIfThrottled(e)){const i=n.filter(a=>a.bypass_global_group_limit),o=n.length-i.length;return this.knock.log(`[Guide] Throttling ${o} guides from selection, and returning ${i.length} guides`),i}return this.knock.log(`[Guide] Returning ${n.length} guides from selection`),n}selectGuide(e,t={},s={}){if(this.knock.log(`[Guide] .selectGuide (filters: ${d.formatFilters(t)}; state: ${d.formatState(e)})`),Object.keys(e.guides).length===0&&Object.keys(e.previewGuides).length===0){this.knock.log("[Guide] Exiting selection (no guides)");return}const r=S(e,t);if(r.size===0){this.knock.log("[Guide] Selection found zero result");return}const[n,i]=[...r][0];if(this.knock.log(`[Guide] Selection found: \`${i.key}\` (total: ${r.size})`),i.bypass_global_group_limit)return this.knock.log(`[Guide] Returning the unthrottled guide: ${i.key}`),i;if(!s.includeThrottled&&d.checkStateIfThrottled(e)){this.knock.log(`[Guide] Throttling the selected guide: ${i.key}`);return}switch(this.stage||(this.stage=this.openGroupStage()),this.stage.status){case"open":{this.knock.log(`[Guide] Adding to the group stage: ${i.key}`),this.stage.ordered[n]=i.key;return}case"patch":{this.knock.log(`[Guide] Patching the group stage: ${i.key}`),this.stage.ordered[n]=i.key;const o=this.stage.resolved===i.key?i:void 0;return this.knock.log(`[Guide] Returning \`${o==null?void 0:o.key}\` (stage: ${d.formatGroupStage(this.stage)})`),o}case"closed":{const o=this.stage.resolved===i.key?i:void 0;return this.knock.log(`[Guide] Returning \`${o==null?void 0:o.key}\` (stage: ${d.formatGroupStage(this.stage)})`),o}}}openGroupStage(){this.knock.log("[Guide] Opening a new group stage");const{orderResolutionDuration:e=I}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.stage={status:"open",ordered:[],timeoutId:t},this.stage}closePendingGroupStage(){if(this.knock.log("[Guide] .closePendingGroupStage"),!this.stage||this.stage.status==="closed")return;this.ensureClearTimeout();let e;return this.store.state.debug.forcedGuideKey&&(e=this.stage.ordered.find(t=>t===this.store.state.debug.forcedGuideKey)),e||(e=this.stage.ordered.find(t=>t!==void 0)),this.knock.log(`[Guide] Closing the current group stage: resolved=${e}`),this.stage={...this.stage,status:"closed",resolved:e,timeoutId:null},this.stage}patchClosedGroupStage(){var s;if(this.knock.log("[Guide] .patchClosedGroupStage"),((s=this.stage)==null?void 0:s.status)!=="closed")return;const{orderResolutionDuration:e=0}=this.options,t=setTimeout(()=>{this.closePendingGroupStage(),this.incrementCounter()},e);return this.ensureClearTimeout(),this.knock.log("[Guide] Patching the current group stage"),this.stage={...this.stage,status:"patch",ordered:[],timeoutId:t},this.stage}clearGroupStage(){this.knock.log("[Guide] .clearGroupStage"),this.stage&&(this.knock.log("[Guide] Clearing the current group stage"),this.ensureClearTimeout(),this.stage=void 0)}ensureClearTimeout(){var e;(e=this.stage)!=null&&e.timeoutId&&clearTimeout(this.stage.timeoutId)}_selectGuide(e,t={},s={}){return this.openGroupStage(),this.selectGuide(e,t,s),this.closePendingGroupStage(),this.selectGuide(e,t,s)}_selectGuides(e,t={},s={}){return this.openGroupStage(),this.selectGuides(e,t,s),this.closePendingGroupStage(),this.selectGuides(e,t,s)}async markAsSeen(e,t){if(t.message.seen_at)return;this.knock.log(`[Guide] Marking as seen (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{seen_at:new Date().toISOString()});if(!s)return;const r={...this.buildEngagementEventBaseParams(e,s),content:s.content,data:this.targetParams.data};return this.knock.user.markGuideStepAs("seen",r),s}async markAsInteracted(e,t,s){this.knock.log(`[Guide] Marking as interacted (Guide key: ${e.key}; Step ref:${t.ref})`);const r=new Date().toISOString(),n=this.setStepMessageAttrs(e.key,t.ref,{read_at:r,interacted_at:r});if(!n)return;const i={...this.buildEngagementEventBaseParams(e,n),metadata:s};return this.knock.user.markGuideStepAs("interacted",i),n}async markAsArchived(e,t){if(t.message.archived_at)return;this.knock.log(`[Guide] Marking as archived (Guide key: ${e.key}, Step ref:${t.ref})`);const s=this.setStepMessageAttrs(e.key,t.ref,{archived_at:new Date().toISOString()});if(!s)return;const r=this.buildEngagementEventBaseParams(e,s);return this.knock.user.markGuideStepAs("archived",{...r,unthrottled:e.bypass_global_group_limit}),s}localCopy(e){const t=this,s={...e,getStep(){return t.store.state.debug.forcedGuideKey===this.key?this.steps[0]:this.steps.find(r=>!r.message.archived_at)}};return s.getStep=s.getStep.bind(s),s.steps=e.steps.map(({message:r,...n})=>{const i={...n,message:{...r},markAsSeen(){if(!this.message.seen_at)return t.markAsSeen(s,this)},markAsInteracted({metadata:o}={}){return t.markAsInteracted(s,this,o)},markAsArchived(){if(!this.message.archived_at)return t.markAsArchived(s,this)}};return i.markAsSeen=i.markAsSeen.bind(i),i.markAsInteracted=i.markAsInteracted.bind(i),i.markAsArchived=i.markAsArchived.bind(i),i}),s.activation_url_patterns=e.activation_url_patterns.map(r=>({...r,pattern:new b.URLPattern({pathname:r.pathname})})),s}buildQueryParams(e={}){const t={...this.targetParams,...e};this.store.state.debug.forcedGuideKey&&(t.force_all_guides=!0);let r=Object.fromEntries(Object.entries(t).filter(([n,i])=>i!=null));return r=r.data?{...r,data:JSON.stringify(r.data)}:r,r}formatQueryKey(e){const s=Object.keys(e).sort().map(n=>`${encodeURIComponent(n)}=${encodeURIComponent(e[n])}`).join("&"),r=G(this.knock.userId);return s?`${r}?${s}`:r}setStepMessageAttrs(e,t,s){let r;return s.archived_at&&this.clearGroupStage(),this.store.setState(n=>{let i=n.guides[e];if(!i)return n;const o=i.steps.map(h=>(h.ref!==t||(h.message={...h.message,...s},r=h),h));i=r?{...i,steps:o}:i;const a={...n.guides,[i.key]:i},l=s.archived_at&&!i.bypass_global_group_limit?{...n.guideGroupDisplayLogs,[d.DEFAULT_GROUP_KEY]:s.archived_at}:n.guideGroupDisplayLogs;return{...n,guides:a,guideGroupDisplayLogs:l}}),r}buildEngagementEventBaseParams(e,t){return{channel_id:e.channel_id,guide_key:e.key,guide_id:e.id,guide_step_ref:t.ref,tenant:this.targetParams.tenant}}addOrReplaceGuide({data:e}){this.patchClosedGroupStage();const t=this.localCopy(e.guide);this.store.setState(s=>{const r={...s.guides,[t.key]:t};return{...s,guides:r}})}removeGuide({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const{[e.guide.key]:s,...r}=t.guides;return{...t,guides:r}})}addOrReplaceGuideGroup({data:e}){this.patchClosedGroupStage(),this.store.setState(t=>{const s=[e.guide_group],r=e.guide_group.display_sequence_unthrottled||[],n=e.guide_group.display_sequence_throttled||[];let i=t.guides;return i=r.reduce((o,a)=>{if(!o[a])return o;const l={...o[a],bypass_global_group_limit:!0};return{...o,[a]:l}},i),i=n.reduce((o,a)=>{if(!o[a])return o;const l={...o[a],bypass_global_group_limit:!1};return{...o,[a]:l}},i),{...t,guides:i,guideGroups:s}})}updatePreviewGuide({data:e}){const t=this.localCopy(e.guide);this.store.setState(s=>{const r={...s.previewGuides,[t.key]:t};return{...s,previewGuides:r}})}checkDebugStateChanged(e,t){return!!e.forcedGuideKey!=!!t.forcedGuideKey||e.previewSessionId!==t.previewSessionId}listenForLocationChangesFromWindow(){const e=p();if(e!=null&&e.history){e.addEventListener("popstate",this.handleLocationChange),e.addEventListener("hashchange",this.handleLocationChange);const t=e.history.pushState,s=e.history.replaceState;e.history.pushState=new Proxy(t,{apply:(r,n,i)=>{Reflect.apply(r,n,i),setTimeout(()=>{this.handleLocationChange()},0)}}),e.history.replaceState=new Proxy(s,{apply:(r,n,i)=>{Reflect.apply(r,n,i),setTimeout(()=>{this.handleLocationChange()},0)}}),this.pushStateFn=t,this.replaceStateFn=s}else this.knock.log("[Guide] Unable to access the `window.history` object to detect location changes")}removeLocationChangeEventListeners(){const e=p();e!=null&&e.history&&(e.removeEventListener("popstate",this.handleLocationChange),e.removeEventListener("hashchange",this.handleLocationChange),this.pushStateFn&&(e.history.pushState=this.pushStateFn,this.pushStateFn=void 0),this.replaceStateFn&&(e.history.replaceState=this.replaceStateFn,this.replaceStateFn=void 0))}}exports.DEBUG_QUERY_PARAMS=g;exports.KnockGuideClient=P;exports.guidesApiRootPath=G;
2
2
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../../../src/clients/guide/client.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport { Store } from \"@tanstack/store\";\nimport { Channel, Socket } from \"phoenix\";\nimport { URLPattern } from \"urlpattern-polyfill\";\n\nimport Knock from \"../../knock\";\n\nimport {\n DEFAULT_GROUP_KEY,\n SelectionResult,\n byKey,\n checkIfThrottled,\n findDefaultGroup,\n formatFilters,\n formatGroupStage,\n formatState,\n mockDefaultGroup,\n newUrl,\n predicateUrlPatterns,\n predicateUrlRules,\n} from \"./helpers\";\nimport {\n Any,\n ConstructorOpts,\n DebugState,\n GetGuidesQueryParams,\n GetGuidesResponse,\n GroupStage,\n GuideAddedEvent,\n GuideData,\n GuideGroupAddedEvent,\n GuideGroupUpdatedEvent,\n GuideLivePreviewUpdatedEvent,\n GuideRemovedEvent,\n GuideSocketEvent,\n GuideStepData,\n GuideUpdatedEvent,\n KnockGuide,\n KnockGuideStep,\n MarkAsArchivedParams,\n MarkAsInteractedParams,\n MarkAsSeenParams,\n MarkGuideAsResponse,\n QueryFilterParams,\n QueryStatus,\n SelectFilterParams,\n StepMessageState,\n StoreState,\n TargetParams,\n} from \"./types\";\n\n// How long to wait until we resolve the guides order and determine the\n// prevailing guide.\nconst DEFAULT_ORDER_RESOLUTION_DURATION = 50; // in milliseconds\n\n// How often we should increment the counter to refresh the store state and\n// trigger subscribed callbacks.\nconst DEFAULT_COUNTER_INCREMENT_INTERVAL = 30 * 1000; // in milliseconds\n\n// Maximum number of retry attempts for channel subscription\nconst SUBSCRIBE_RETRY_LIMIT = 3;\n\n// Debug query param keys\nexport const DEBUG_QUERY_PARAMS = {\n GUIDE_KEY: \"knock_guide_key\",\n PREVIEW_SESSION_ID: \"knock_preview_session_id\",\n};\n\nconst DEBUG_STORAGE_KEY = \"knock_guide_debug\";\n\n// Return the global window object if defined, so to safely guard against SSR.\nconst checkForWindow = () => {\n if (typeof window !== \"undefined\") {\n return window;\n }\n};\n\nexport const guidesApiRootPath = (userId: string | undefined | null) =>\n `/v1/users/${userId}/guides`;\n\n// Detect debug params from URL or local storage\nconst detectDebugParams = (): DebugState => {\n const win = checkForWindow();\n if (!win) {\n return { forcedGuideKey: null, previewSessionId: null };\n }\n\n const urlParams = new URLSearchParams(win.location.search);\n const urlGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const urlPreviewSessionId = urlParams.get(\n DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID,\n );\n\n // If URL params exist, persist them to localStorage and return them\n if (urlGuideKey || urlPreviewSessionId) {\n if (win.localStorage) {\n try {\n const debugState = {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n win.localStorage.setItem(DEBUG_STORAGE_KEY, JSON.stringify(debugState));\n } catch {\n // Silently fail in privacy mode\n }\n }\n return {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n }\n\n // Check local storage if no URL params\n let storedGuideKey = null;\n let storedPreviewSessionId = null;\n\n if (win.localStorage) {\n try {\n const storedDebugState = win.localStorage.getItem(DEBUG_STORAGE_KEY);\n if (storedDebugState) {\n const parsedDebugState = safeJsonParseDebugParams(storedDebugState);\n storedGuideKey = parsedDebugState.forcedGuideKey;\n storedPreviewSessionId = parsedDebugState.previewSessionId;\n }\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n return {\n forcedGuideKey: storedGuideKey,\n previewSessionId: storedPreviewSessionId,\n };\n};\n\nconst safeJsonParseDebugParams = (value: string): DebugState => {\n try {\n const parsed = JSON.parse(value);\n return {\n forcedGuideKey: parsed?.forcedGuideKey ?? null,\n previewSessionId: parsed?.previewSessionId ?? null,\n };\n } catch {\n return {\n forcedGuideKey: null,\n previewSessionId: null,\n };\n }\n};\n\nconst select = (state: StoreState, filters: SelectFilterParams = {}) => {\n // A map of selected guides as values, with its order index as keys.\n const result = new SelectionResult();\n\n const defaultGroup = findDefaultGroup(state.guideGroups);\n if (!defaultGroup) return result;\n\n const displaySequence = [...defaultGroup.display_sequence];\n const location = state.location;\n\n // If in debug mode, put the forced guide at the beginning of the display sequence.\n if (state.debug.forcedGuideKey) {\n const forcedKeyIndex = displaySequence.indexOf(state.debug.forcedGuideKey);\n if (forcedKeyIndex > -1) {\n displaySequence.splice(forcedKeyIndex, 1);\n }\n displaySequence.unshift(state.debug.forcedGuideKey);\n }\n\n for (const [index, guideKey] of displaySequence.entries()) {\n let guide = state.guides[guideKey];\n\n // Use preview guide if it exists and matches the forced guide key\n if (\n state.debug.forcedGuideKey === guideKey &&\n state.previewGuides[guideKey]\n ) {\n guide = state.previewGuides[guideKey];\n }\n\n if (!guide) continue;\n\n const affirmed = predicate(guide, {\n location,\n filters,\n debug: state.debug,\n });\n\n if (!affirmed) continue;\n\n result.set(index, guide);\n }\n\n result.metadata = { guideGroup: defaultGroup };\n return result;\n};\n\ntype PredicateOpts = {\n location?: string | undefined;\n filters?: SelectFilterParams | undefined;\n debug: DebugState;\n};\n\nconst predicate = (\n guide: KnockGuide,\n { location, filters = {}, debug = {} }: PredicateOpts,\n) => {\n if (filters.type && filters.type !== guide.type) {\n return false;\n }\n\n if (filters.key && filters.key !== guide.key) {\n return false;\n }\n\n // Bypass filtering if the debugged guide matches the given filters.\n // This should always run AFTER checking the filters but BEFORE\n // checking archived status and location rules.\n if (debug.forcedGuideKey === guide.key) {\n return true;\n }\n\n if (!guide.active) {\n return false;\n }\n\n if (guide.steps.every((s) => !!s.message.archived_at)) {\n return false;\n }\n\n const url = location ? newUrl(location) : undefined;\n\n const urlRules = guide.activation_url_rules || [];\n const urlPatterns = guide.activation_url_patterns || [];\n\n // A guide can have either activation url rules XOR url patterns, but not both.\n if (url && urlRules.length > 0) {\n const allowed = predicateUrlRules(url, urlRules);\n if (!allowed) return false;\n } else if (url && urlPatterns.length > 0) {\n const allowed = predicateUrlPatterns(url, urlPatterns);\n if (!allowed) return false;\n }\n\n return true;\n};\n\nexport class KnockGuideClient {\n public store: Store<StoreState, (state: StoreState) => StoreState>;\n\n // Phoenix channels for real time guide updates over websocket\n private socket: Socket | undefined;\n private socketChannel: Channel | undefined;\n private socketChannelTopic: string;\n private socketEventTypes = [\n \"guide.added\",\n \"guide.updated\",\n \"guide.removed\",\n \"guide_group.added\",\n \"guide_group.updated\",\n \"guide.live_preview_updated\",\n ];\n private subscribeRetryCount = 0;\n\n // Original history methods to monkey patch, or restore in cleanups.\n private pushStateFn: History[\"pushState\"] | undefined;\n private replaceStateFn: History[\"replaceState\"] | undefined;\n\n // Guides that are competing to render are \"staged\" first without rendering\n // and ranked based on its relative order in the group over a duration of time\n // to resolve and render the prevailing one.\n private stage: GroupStage | undefined;\n\n private counterIntervalId: ReturnType<typeof setInterval> | undefined;\n\n constructor(\n readonly knock: Knock,\n readonly channelId: string,\n readonly targetParams: TargetParams = {},\n readonly options: ConstructorOpts = {},\n ) {\n const {\n trackLocationFromWindow = true,\n throttleCheckInterval = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = options;\n const win = checkForWindow();\n\n const location = trackLocationFromWindow ? win?.location.href : undefined;\n\n const debug = detectDebugParams();\n\n this.store = new Store<StoreState>({\n guideGroups: [],\n guideGroupDisplayLogs: {},\n guides: {},\n previewGuides: {},\n queries: {},\n location,\n // Increment to update the state store and trigger re-selection.\n counter: 0,\n debug,\n });\n\n // In server environments we might not have a socket connection.\n const { socket: maybeSocket } = this.knock.client();\n this.socket = maybeSocket;\n this.socketChannelTopic = `guides:${channelId}`;\n\n if (trackLocationFromWindow) {\n this.listenForLocationChangesFromWindow();\n }\n\n if (throttleCheckInterval) {\n // Start the counter loop to increment at an interval.\n this.startCounterInterval(throttleCheckInterval);\n }\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n private incrementCounter() {\n this.knock.log(\"[Guide] Incrementing the counter\");\n this.store.setState((state) => ({ ...state, counter: state.counter + 1 }));\n }\n\n private startCounterInterval(delay: number) {\n this.counterIntervalId = setInterval(() => {\n this.knock.log(\"[Guide] Counter interval tick\");\n if (this.stage && this.stage.status !== \"closed\") return;\n\n this.incrementCounter();\n }, delay);\n }\n\n private clearCounterInterval() {\n if (this.counterIntervalId) {\n clearInterval(this.counterIntervalId);\n this.counterIntervalId = undefined;\n }\n }\n\n cleanup() {\n this.unsubscribe();\n this.removeLocationChangeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\n }\n\n async fetch(opts?: { filters?: QueryFilterParams }) {\n this.knock.log(\"[Guide] .fetch\");\n this.knock.failIfNotAuthenticated();\n\n const queryParams = this.buildQueryParams(opts?.filters);\n const queryKey = this.formatQueryKey(queryParams);\n\n // If already fetched before, then noop.\n const maybeQueryStatus = this.store.state.queries[queryKey];\n if (maybeQueryStatus) {\n return maybeQueryStatus;\n }\n\n // Mark this query status as loading.\n this.store.setState((state) => ({\n ...state,\n queries: { ...state.queries, [queryKey]: { status: \"loading\" } },\n }));\n\n let queryStatus: QueryStatus;\n try {\n this.knock.log(\"[Guide] Fetching all eligible guides\");\n const data = await this.knock.user.getGuides<\n GetGuidesQueryParams,\n GetGuidesResponse\n >(this.channelId, queryParams);\n queryStatus = { status: \"ok\" };\n\n const { entries, guide_groups: groups, guide_group_display_logs } = data;\n\n this.knock.log(\"[Guide] Loading fetched guides\");\n this.store.setState((state) => ({\n ...state,\n guideGroups: groups?.length > 0 ? groups : [mockDefaultGroup(entries)],\n guideGroupDisplayLogs: guide_group_display_logs || {},\n guides: byKey(entries.map((g) => this.localCopy(g))),\n queries: { ...state.queries, [queryKey]: queryStatus },\n }));\n } catch (e) {\n queryStatus = { status: \"error\", error: e as Error };\n\n this.store.setState((state) => ({\n ...state,\n queries: { ...state.queries, [queryKey]: queryStatus },\n }));\n }\n\n return queryStatus;\n }\n\n subscribe() {\n if (!this.socket) return;\n this.knock.failIfNotAuthenticated();\n this.knock.log(\"[Guide] Subscribing to real time updates\");\n\n // Ensure a live socket connection if not yet connected.\n if (!this.socket.isConnected()) {\n this.socket.connect();\n }\n\n // If there's an existing connected channel, then disconnect.\n if (this.socketChannel) {\n this.unsubscribe();\n }\n\n // Join the channel topic and subscribe to supported events.\n const debugState = this.store.state.debug;\n const params = {\n ...this.targetParams,\n user_id: this.knock.userId,\n force_all_guides: debugState.forcedGuideKey ? true : undefined,\n preview_session_id: debugState.previewSessionId || undefined,\n };\n\n const newChannel = this.socket.channel(this.socketChannelTopic, params);\n\n for (const eventType of this.socketEventTypes) {\n newChannel.on(eventType, (payload) => this.handleSocketEvent(payload));\n }\n\n if ([\"closed\", \"errored\"].includes(newChannel.state)) {\n // Reset retry count for new subscription attempt\n this.subscribeRetryCount = 0;\n\n newChannel\n .join()\n .receive(\"ok\", () => {\n this.knock.log(\"[Guide] Successfully joined channel\");\n })\n .receive(\"error\", (resp) => {\n this.knock.log(\n `[Guide] Failed to join channel: ${JSON.stringify(resp)}`,\n );\n this.handleChannelJoinError();\n })\n .receive(\"timeout\", () => {\n this.knock.log(\"[Guide] Channel join timed out\");\n this.handleChannelJoinError();\n });\n }\n\n // Track the joined channel.\n this.socketChannel = newChannel;\n }\n\n private handleChannelJoinError() {\n // Prevent phx channel from retrying forever in case of either network or\n // other errors (e.g. auth error, invalid channel etc)\n if (this.subscribeRetryCount >= SUBSCRIBE_RETRY_LIMIT) {\n this.knock.log(\n `[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`,\n );\n this.unsubscribe();\n return;\n }\n\n this.subscribeRetryCount++;\n }\n\n unsubscribe() {\n if (!this.socketChannel) return;\n this.knock.log(\"[Guide] Unsubscribing from real time updates\");\n\n // Unsubscribe from the socket events and leave the channel.\n for (const eventType of this.socketEventTypes) {\n this.socketChannel.off(eventType);\n }\n this.socketChannel.leave();\n\n // Unset the channel.\n this.socketChannel = undefined;\n }\n\n private handleSocketEvent(payload: GuideSocketEvent) {\n const { event, data } = payload;\n\n switch (event) {\n case \"guide.added\":\n return this.addOrReplaceGuide(payload);\n\n case \"guide.updated\":\n return data.eligible\n ? this.addOrReplaceGuide(payload)\n : this.removeGuide(payload);\n\n case \"guide.removed\":\n return this.removeGuide(payload);\n\n case \"guide_group.added\":\n case \"guide_group.updated\":\n return this.addOrReplaceGuideGroup(payload);\n\n case \"guide.live_preview_updated\":\n return this.updatePreviewGuide(payload);\n\n default:\n return;\n }\n }\n\n setLocation(href: string, additionalParams: Partial<StoreState> = {}) {\n this.knock.log(`[Guide] .setLocation (loc=${href})`);\n\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.knock.log(\"[Guide] Updating the tracked location\");\n this.store.setState((state) => {\n // Clear preview guides if no longer in preview mode\n const previewGuides = additionalParams?.debug?.previewSessionId\n ? state.previewGuides\n : {};\n\n return {\n ...state,\n ...additionalParams,\n previewGuides,\n location: href,\n };\n });\n }\n\n exitDebugMode() {\n this.knock.log(\"[Guide] Exiting debug mode\");\n\n // Clear localStorage debug params\n const win = checkForWindow();\n if (win?.localStorage) {\n try {\n win.localStorage.removeItem(DEBUG_STORAGE_KEY);\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n // Clear debug state from store\n this.store.setState((state) => ({\n ...state,\n debug: { forcedGuideKey: null, previewSessionId: null },\n previewGuides: {}, // Clear preview guides when exiting debug mode\n }));\n\n // Remove URL query params if present\n // Only update the URL if params need to be cleared to avoid unnecessary navigations\n if (win) {\n const url = new URL(win.location.href);\n if (\n url.searchParams.has(DEBUG_QUERY_PARAMS.GUIDE_KEY) ||\n url.searchParams.has(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID)\n ) {\n url.searchParams.delete(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n url.searchParams.delete(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n win.location.href = url.toString();\n }\n }\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C>[] {\n this.knock.log(\n `[Guide] .selectGuides (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n this.knock.log(\"[Guide] Exiting selection (no guides)\");\n return [];\n }\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection returned zero result\");\n return [];\n }\n\n // Return all selected guides, since we cannot apply the one-at-a-time limit\n // or throttle settings, but rather defer to the caller to decide which ones\n // to render. Note\n return [...result.values()];\n }\n\n selectGuide<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n ): KnockGuide<C> | undefined {\n this.knock.log(\n `[Guide] .selectGuide (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n this.knock.log(\"[Guide] Exiting selection (no guides)\");\n return undefined;\n }\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection found zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n this.knock.log(\n `[Guide] Selection found: \\`${guide.key}\\` (total: ${result.size})`,\n );\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n this.knock.log(`[Guide] Returning the unthrottled guide: ${guide.key}`);\n return guide;\n }\n\n // Check if inside the throttle window (i.e. throttled) and if so stop and\n // return undefined.\n const defaultGroup = findDefaultGroup(state.guideGroups);\n const throttleWindowStartedAt =\n state.guideGroupDisplayLogs[DEFAULT_GROUP_KEY];\n\n if (\n defaultGroup &&\n defaultGroup.display_interval &&\n throttleWindowStartedAt\n ) {\n const throttled = checkIfThrottled(\n throttleWindowStartedAt,\n defaultGroup.display_interval,\n );\n if (throttled) {\n this.knock.log(`[Guide] Throttling the selected guide: ${guide.key}`);\n return undefined;\n }\n }\n\n // Starting here to the end of this method represents the core logic of how\n // \"group stage\" works. It provides a mechanism for 1) figuring out which\n // guide components are about to render on a page, 2) determining which\n // among them ranks highest in the configured display sequence, and 3)\n // returning only the prevailing guide to render at a time.\n //\n // Imagine N number of components that use the `useGuide()` hook which\n // calls this `selectGuide()` method, and the logic works like this:\n // * The first time this method is called, we don't have an \"open\" group\n // stage, so we open one (this occurs when a new page/route is rendering).\n // * While it is open, we record which guide was selected and its order\n // index from each call, but we do NOT return any guide to render yet.\n // * When a group stage opens, it schedules a timer to close itself. How\n // long this timer waits is configurable. Note, `setTimeout` with 0\n // delay seems to work well for React apps, where we \"yield\" to React\n // for one render cycle and close the group right after.\n // * When a group stage closes, we evaluate which guides were selected and\n // recorded, then determine the winning guide (i.e. the one with the\n // lowest order index value).\n // * Then increment the internal counter to trigger a store state update,\n // which allows `useGuide()` and `selectGuide()` to re-run. This second\n // round of `selectGuide()` calls, occurring when the group stage is\n // closed, results in returning the prevailing guide.\n // * Whenever a user navigates to a new page, we repeat the same process\n // above.\n // * There's a third status called \"patch,\" which is for handling real-time\n // updates received from the API. It's similar to the \"open\" to \"closed\"\n // flow, except we keep the resolved guide in place while we recalculate.\n // This is done so that we don't cause flickers or CLS.\n if (!this.stage) {\n this.stage = this.openGroupStage(); // Assign here to make tsc happy\n }\n\n switch (this.stage.status) {\n case \"open\": {\n this.knock.log(`[Guide] Adding to the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return undefined;\n }\n\n case \"patch\": {\n this.knock.log(`[Guide] Patching the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\n }\n\n case \"closed\": {\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\n }\n }\n }\n\n private openGroupStage() {\n this.knock.log(\"[Guide] Opening a new group stage\");\n\n const {\n orderResolutionDuration: delay = DEFAULT_ORDER_RESOLUTION_DURATION,\n } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n this.stage = {\n status: \"open\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n // Close the current non-closed stage to resolve the prevailing guide up next\n // for display amongst the ones that have been staged.\n private closePendingGroupStage() {\n this.knock.log(\"[Guide] .closePendingGroupStage\");\n if (!this.stage || this.stage.status === \"closed\") return;\n\n // Should have been cleared already since this method should be called as a\n // callback to a setTimeout, but just to be safe.\n this.ensureClearTimeout();\n\n // If in debug mode, try to resolve the forced guide, otherwise return the first non-undefined guide.\n let resolved = undefined;\n if (this.store.state.debug.forcedGuideKey) {\n resolved = this.stage.ordered.find(\n (x) => x === this.store.state.debug.forcedGuideKey,\n );\n }\n\n if (!resolved) {\n resolved = this.stage.ordered.find((x) => x !== undefined);\n }\n\n this.knock.log(\n `[Guide] Closing the current group stage: resolved=${resolved}`,\n );\n\n this.stage = {\n ...this.stage,\n status: \"closed\",\n resolved,\n timeoutId: null,\n };\n\n return this.stage;\n }\n\n // Set the current closed stage status to \"patch\" to allow re-running\n // selections and re-building a group stage with the latest/updated state,\n // while keeping the currently resolved guide in place so that it stays\n // rendered until we are ready to resolve the updated stage and re-render.\n // Note, must be called ahead of updating the state store.\n private patchClosedGroupStage() {\n this.knock.log(\"[Guide] .patchClosedGroupStage\");\n if (this.stage?.status !== \"closed\") return;\n\n const { orderResolutionDuration: delay = 0 } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n // Just to be safe.\n this.ensureClearTimeout();\n\n this.knock.log(\"[Guide] Patching the current group stage\");\n\n this.stage = {\n ...this.stage,\n status: \"patch\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n private clearGroupStage() {\n this.knock.log(\"[Guide] .clearGroupStage\");\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\n this.ensureClearTimeout();\n this.stage = undefined;\n }\n\n private ensureClearTimeout() {\n if (this.stage?.timeoutId) {\n clearTimeout(this.stage.timeoutId);\n }\n }\n\n // Test helper that opens and closes the group stage to return the select\n // result immediately.\n private _selectGuide(state: StoreState, filters: SelectFilterParams = {}) {\n this.openGroupStage();\n\n this.selectGuide(state, filters);\n this.closePendingGroupStage();\n\n return this.selectGuide(state, filters);\n }\n\n //\n // Engagement event handlers\n //\n // Make an optimistic update on the client side first, then send an engagement\n // event to the backend.\n //\n\n async markAsSeen(guide: GuideData, step: GuideStepData) {\n if (step.message.seen_at) return;\n\n this.knock.log(\n `[Guide] Marking as seen (Guide key: ${guide.key}, Step ref:${step.ref})`,\n );\n\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n seen_at: new Date().toISOString(),\n });\n if (!updatedStep) return;\n\n const params = {\n ...this.buildEngagementEventBaseParams(guide, updatedStep),\n content: updatedStep.content,\n data: this.targetParams.data,\n };\n\n this.knock.user.markGuideStepAs<MarkAsSeenParams, MarkGuideAsResponse>(\n \"seen\",\n params,\n );\n\n return updatedStep;\n }\n\n async markAsInteracted(\n guide: GuideData,\n step: GuideStepData,\n metadata?: GenericData,\n ) {\n this.knock.log(\n `[Guide] Marking as interacted (Guide key: ${guide.key}; Step ref:${step.ref})`,\n );\n\n const ts = new Date().toISOString();\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n read_at: ts,\n interacted_at: ts,\n });\n if (!updatedStep) return;\n\n const params = {\n ...this.buildEngagementEventBaseParams(guide, updatedStep),\n metadata,\n };\n\n this.knock.user.markGuideStepAs<\n MarkAsInteractedParams,\n MarkGuideAsResponse\n >(\"interacted\", params);\n\n return updatedStep;\n }\n\n async markAsArchived(guide: GuideData, step: GuideStepData) {\n if (step.message.archived_at) return;\n\n this.knock.log(\n `[Guide] Marking as archived (Guide key: ${guide.key}, Step ref:${step.ref})`,\n );\n\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n archived_at: new Date().toISOString(),\n });\n if (!updatedStep) return;\n\n const params = this.buildEngagementEventBaseParams(guide, updatedStep);\n\n this.knock.user.markGuideStepAs<MarkAsArchivedParams, MarkGuideAsResponse>(\n \"archived\",\n {\n ...params,\n unthrottled: guide.bypass_global_group_limit,\n },\n );\n\n return updatedStep;\n }\n\n //\n // Helpers\n //\n\n private localCopy(remoteGuide: GuideData) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n // Build a local copy with helper methods added.\n const localGuide = {\n ...remoteGuide,\n // Get the next unarchived step.\n getStep() {\n // If debugging this guide, return the first step regardless of archive status\n if (self.store.state.debug.forcedGuideKey === this.key) {\n return this.steps[0];\n }\n\n return this.steps.find((s) => !s.message.archived_at);\n },\n } as KnockGuide;\n\n localGuide.getStep = localGuide.getStep.bind(localGuide);\n\n localGuide.steps = remoteGuide.steps.map(({ message, ...rest }) => {\n const localStep = {\n ...rest,\n message: { ...message },\n markAsSeen() {\n // Send a seen event if it has not been previously seen.\n if (this.message.seen_at) return;\n return self.markAsSeen(localGuide, this);\n },\n markAsInteracted({ metadata }: { metadata?: GenericData } = {}) {\n // Always send an interaction event through.\n return self.markAsInteracted(localGuide, this, metadata);\n },\n markAsArchived() {\n // Send an archived event if it has not been previously archived.\n if (this.message.archived_at) return;\n return self.markAsArchived(localGuide, this);\n },\n };\n\n // Bind all engagement action handler methods to the local step object so\n // they can operate on itself.\n localStep.markAsSeen = localStep.markAsSeen.bind(localStep);\n localStep.markAsInteracted = localStep.markAsInteracted.bind(localStep);\n localStep.markAsArchived = localStep.markAsArchived.bind(localStep);\n\n return localStep;\n });\n\n localGuide.activation_url_patterns =\n remoteGuide.activation_url_patterns.map((rule) => {\n return {\n ...rule,\n pattern: new URLPattern({ pathname: rule.pathname }),\n };\n });\n\n return localGuide;\n }\n\n private buildQueryParams(filterParams: QueryFilterParams = {}) {\n // Combine the target params with the given filter params.\n const combinedParams: GenericData = {\n ...this.targetParams,\n ...filterParams,\n };\n\n // Append debug params\n const debugState = this.store.state.debug;\n if (debugState.forcedGuideKey) {\n combinedParams.force_all_guides = true;\n }\n\n // Prune out any keys that have an undefined or null value.\n let params = Object.fromEntries(\n Object.entries(combinedParams).filter(\n ([_k, v]) => v !== undefined && v !== null,\n ),\n );\n\n // Encode target data as a JSON string, if provided.\n params = params.data\n ? { ...params, data: JSON.stringify(params.data) }\n : params;\n\n return params as GetGuidesQueryParams;\n }\n\n private formatQueryKey(queryParams: GenericData) {\n const sortedKeys = Object.keys(queryParams).sort();\n\n const queryStr = sortedKeys\n .map(\n (key) =>\n `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`,\n )\n .join(\"&\");\n\n const basePath = guidesApiRootPath(this.knock.userId);\n return queryStr ? `${basePath}?${queryStr}` : basePath;\n }\n\n private setStepMessageAttrs(\n guideKey: string,\n stepRef: string,\n attrs: Partial<StepMessageState>,\n ) {\n let updatedStep: KnockGuideStep | undefined;\n\n // If we are marking as archived, clear the group stage so we can render\n // the next guide in the group.\n if (attrs.archived_at) {\n this.clearGroupStage();\n }\n\n this.store.setState((state) => {\n let guide = state.guides[guideKey];\n if (!guide) return state;\n\n const steps = guide.steps.map((step) => {\n if (step.ref !== stepRef) return step;\n\n // Mutate in place and maintain the same obj ref so to make it easier\n // to use in hook deps.\n step.message = { ...step.message, ...attrs };\n updatedStep = step;\n\n return step;\n });\n // If updated, return the guide as a new object so useStore can trigger.\n guide = updatedStep ? { ...guide, steps } : guide;\n\n const guides = { ...state.guides, [guide.key]: guide };\n\n // If the guide is subject to throttled settings and we are marking as\n // archived, then update the display logs to start a new throttle window.\n const guideGroupDisplayLogs =\n attrs.archived_at && !guide.bypass_global_group_limit\n ? {\n ...state.guideGroupDisplayLogs,\n [DEFAULT_GROUP_KEY]: attrs.archived_at,\n }\n : state.guideGroupDisplayLogs;\n\n return { ...state, guides, guideGroupDisplayLogs };\n });\n\n return updatedStep;\n }\n\n private buildEngagementEventBaseParams(\n guide: GuideData,\n step: GuideStepData,\n ) {\n return {\n channel_id: guide.channel_id,\n guide_key: guide.key,\n guide_id: guide.id,\n guide_step_ref: step.ref,\n // Can be used for scoping guide messages.\n tenant: this.targetParams.tenant,\n };\n }\n\n private addOrReplaceGuide({ data }: GuideAddedEvent | GuideUpdatedEvent) {\n this.patchClosedGroupStage();\n\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const guides = { ...state.guides, [guide.key]: guide };\n\n return { ...state, guides };\n });\n }\n\n private removeGuide({ data }: GuideUpdatedEvent | GuideRemovedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n const { [data.guide.key]: _, ...rest } = state.guides;\n return { ...state, guides: rest };\n });\n }\n\n private addOrReplaceGuideGroup({\n data,\n }: GuideGroupAddedEvent | GuideGroupUpdatedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n // Currently we only support a single default global group, so we can just\n // update the list with the added/updated group.\n const guideGroups = [data.guide_group];\n\n // A guide group event can include lists of unthrottled vs throttled guide\n // keys which we can use to bulk update the guides in the store already.\n const unthrottled = data.guide_group.display_sequence_unthrottled || [];\n const throttled = data.guide_group.display_sequence_throttled || [];\n\n let guides = state.guides;\n\n guides = unthrottled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: true };\n return { ...acc, [key]: guide };\n }, guides);\n\n guides = throttled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: false };\n return { ...acc, [key]: guide };\n }, guides);\n\n return { ...state, guides, guideGroups };\n });\n }\n\n private updatePreviewGuide({ data }: GuideLivePreviewUpdatedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const previewGuides = { ...state.previewGuides, [guide.key]: guide };\n return { ...state, previewGuides };\n });\n }\n\n // Define as an arrow func property to always bind this to the class instance.\n private handleLocationChange = () => {\n this.knock.log(`[Guide] .handleLocationChange`);\n const win = checkForWindow();\n if (!win?.location) return;\n\n const href = win.location.href;\n if (this.store.state.location === href) return;\n\n this.knock.log(`[Guide] Detected a location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n\n this.setLocation(href, { debug: newDebugParams });\n\n // If debug state has changed, refetch guides and resubscribe to the websocket channel\n const debugStateChanged = this.checkDebugStateChanged(\n currentDebugParams,\n newDebugParams,\n );\n\n if (debugStateChanged) {\n this.knock.log(\n `[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel`,\n );\n this.fetch();\n this.subscribe();\n }\n };\n\n // Returns whether debug params have changed. For guide key, we only check\n // presence since the exact value has no impact on fetch/subscribe\n private checkDebugStateChanged(a: DebugState, b: DebugState): boolean {\n return (\n Boolean(a.forcedGuideKey) !== Boolean(b.forcedGuideKey) ||\n a.previewSessionId !== b.previewSessionId\n );\n }\n\n private listenForLocationChangesFromWindow() {\n const win = checkForWindow();\n if (win?.history) {\n // 1. Listen for browser back/forward button clicks.\n win.addEventListener(\"popstate\", this.handleLocationChange);\n\n // 2. Listen for hash changes in case it's used for routing.\n win.addEventListener(\"hashchange\", this.handleLocationChange);\n\n // 3. Monkey-patch history methods to catch programmatic navigation.\n const pushStateFn = win.history.pushState;\n const replaceStateFn = win.history.replaceState;\n\n // Use setTimeout to allow the browser state to potentially settle.\n win.history.pushState = new Proxy(pushStateFn, {\n apply: (target, history, args) => {\n Reflect.apply(target, history, args);\n setTimeout(() => {\n this.handleLocationChange();\n }, 0);\n },\n });\n win.history.replaceState = new Proxy(replaceStateFn, {\n apply: (target, history, args) => {\n Reflect.apply(target, history, args);\n setTimeout(() => {\n this.handleLocationChange();\n }, 0);\n },\n });\n\n // 4. Keep refs to the original handlers so we can restore during cleanup.\n this.pushStateFn = pushStateFn;\n this.replaceStateFn = replaceStateFn;\n } else {\n this.knock.log(\n \"[Guide] Unable to access the `window.history` object to detect location changes\",\n );\n }\n }\n\n removeLocationChangeEventListeners() {\n const win = checkForWindow();\n if (!win?.history) return;\n\n win.removeEventListener(\"popstate\", this.handleLocationChange);\n win.removeEventListener(\"hashchange\", this.handleLocationChange);\n\n if (this.pushStateFn) {\n win.history.pushState = this.pushStateFn;\n this.pushStateFn = undefined;\n }\n if (this.replaceStateFn) {\n win.history.replaceState = this.replaceStateFn;\n this.replaceStateFn = undefined;\n }\n }\n}\n"],"names":["DEFAULT_ORDER_RESOLUTION_DURATION","DEFAULT_COUNTER_INCREMENT_INTERVAL","SUBSCRIBE_RETRY_LIMIT","DEBUG_QUERY_PARAMS","DEBUG_STORAGE_KEY","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","urlGuideKey","urlPreviewSessionId","debugState","storedGuideKey","storedPreviewSessionId","storedDebugState","parsedDebugState","safeJsonParseDebugParams","value","parsed","select","state","filters","result","SelectionResult","defaultGroup","findDefaultGroup","displaySequence","location","forcedKeyIndex","index","guideKey","guide","predicate","debug","s","url","newUrl","urlRules","urlPatterns","predicateUrlRules","predicateUrlPatterns","KnockGuideClient","knock","channelId","targetParams","options","__publicField","href","currentDebugParams","newDebugParams","trackLocationFromWindow","throttleCheckInterval","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","formatState","throttleWindowStartedAt","DEFAULT_GROUP_KEY","checkIfThrottled","ret","formatGroupStage","timeoutId","resolved","x","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","rule","URLPattern","filterParams","combinedParams","_k","v","queryStr","key","basePath","stepRef","attrs","steps","guides","guideGroupDisplayLogs","_","guideGroups","unthrottled","throttled","acc","a","b","pushStateFn","replaceStateFn","target","history","args"],"mappings":"kVAqDMA,EAAoC,GAIpCC,EAAqC,GAAK,IAG1CC,EAAwB,EAGjBC,EAAqB,CAChC,UAAW,kBACX,mBAAoB,0BACtB,EAEMC,EAAoB,oBAGpBC,EAAiB,IAAM,CACvB,GAAA,OAAO,OAAW,IACb,OAAA,MAEX,EAEaC,EAAqBC,GAChC,aAAaA,CAAM,UAGfC,EAAoB,IAAkB,CAC1C,MAAMC,EAAMJ,EAAe,EAC3B,GAAI,CAACI,EACH,MAAO,CAAE,eAAgB,KAAM,iBAAkB,IAAK,EAGxD,MAAMC,EAAY,IAAI,gBAAgBD,EAAI,SAAS,MAAM,EACnDE,EAAcD,EAAU,IAAIP,EAAmB,SAAS,EACxDS,EAAsBF,EAAU,IACpCP,EAAmB,kBACrB,EAGA,GAAIQ,GAAeC,EAAqB,CACtC,GAAIH,EAAI,aACF,GAAA,CACF,MAAMI,EAAa,CACjB,eAAgBF,EAChB,iBAAkBC,CACpB,EACAH,EAAI,aAAa,QAAQL,EAAmB,KAAK,UAAUS,CAAU,CAAC,CAAA,MAChE,CAAA,CAIH,MAAA,CACL,eAAgBF,EAChB,iBAAkBC,CACpB,CAAA,CAIF,IAAIE,EAAiB,KACjBC,EAAyB,KAE7B,GAAIN,EAAI,aACF,GAAA,CACF,MAAMO,EAAmBP,EAAI,aAAa,QAAQL,CAAiB,EACnE,GAAIY,EAAkB,CACd,MAAAC,EAAmBC,EAA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ACzDA,EAAA,oBAAoB,aAAc,KAAK,oBAAoB,EAE3D,KAAK,cACHA,EAAA,QAAQ,UAAY,KAAK,YAC7B,KAAK,YAAc,QAEjB,KAAK,iBACHA,EAAA,QAAQ,aAAe,KAAK,eAChC,KAAK,eAAiB,QACxB,CAEJ"}
1
+ {"version":3,"file":"client.js","sources":["../../../../src/clients/guide/client.ts"],"sourcesContent":["import { GenericData } from \"@knocklabs/types\";\nimport { Store } from \"@tanstack/store\";\nimport { Channel, Socket } from \"phoenix\";\nimport { URLPattern } from \"urlpattern-polyfill\";\n\nimport Knock from \"../../knock\";\n\nimport {\n DEFAULT_GROUP_KEY,\n SelectionResult,\n byKey,\n checkStateIfThrottled,\n findDefaultGroup,\n formatFilters,\n formatGroupStage,\n formatState,\n mockDefaultGroup,\n newUrl,\n predicateUrlPatterns,\n predicateUrlRules,\n} from \"./helpers\";\nimport {\n Any,\n ConstructorOpts,\n DebugState,\n GetGuidesQueryParams,\n GetGuidesResponse,\n GroupStage,\n GuideAddedEvent,\n GuideData,\n GuideGroupAddedEvent,\n GuideGroupUpdatedEvent,\n GuideLivePreviewUpdatedEvent,\n GuideRemovedEvent,\n GuideSocketEvent,\n GuideStepData,\n GuideUpdatedEvent,\n KnockGuide,\n KnockGuideStep,\n MarkAsArchivedParams,\n MarkAsInteractedParams,\n MarkAsSeenParams,\n MarkGuideAsResponse,\n QueryFilterParams,\n QueryStatus,\n SelectFilterParams,\n SelectGuideOpts,\n SelectGuidesOpts,\n StepMessageState,\n StoreState,\n TargetParams,\n} from \"./types\";\n\n// How long to wait until we resolve the guides order and determine the\n// prevailing guide.\nconst DEFAULT_ORDER_RESOLUTION_DURATION = 50; // in milliseconds\n\n// How often we should increment the counter to refresh the store state and\n// trigger subscribed callbacks.\nconst DEFAULT_COUNTER_INCREMENT_INTERVAL = 30 * 1000; // in milliseconds\n\n// Maximum number of retry attempts for channel subscription\nconst SUBSCRIBE_RETRY_LIMIT = 3;\n\n// Debug query param keys\nexport const DEBUG_QUERY_PARAMS = {\n GUIDE_KEY: \"knock_guide_key\",\n PREVIEW_SESSION_ID: \"knock_preview_session_id\",\n};\n\nconst DEBUG_STORAGE_KEY = \"knock_guide_debug\";\n\n// Return the global window object if defined, so to safely guard against SSR.\nconst checkForWindow = () => {\n if (typeof window !== \"undefined\") {\n return window;\n }\n};\n\nexport const guidesApiRootPath = (userId: string | undefined | null) =>\n `/v1/users/${userId}/guides`;\n\n// Detect debug params from URL or local storage\nconst detectDebugParams = (): DebugState => {\n const win = checkForWindow();\n if (!win) {\n return { forcedGuideKey: null, previewSessionId: null };\n }\n\n const urlParams = new URLSearchParams(win.location.search);\n const urlGuideKey = urlParams.get(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n const urlPreviewSessionId = urlParams.get(\n DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID,\n );\n\n // If URL params exist, persist them to localStorage and return them\n if (urlGuideKey || urlPreviewSessionId) {\n if (win.localStorage) {\n try {\n const debugState = {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n win.localStorage.setItem(DEBUG_STORAGE_KEY, JSON.stringify(debugState));\n } catch {\n // Silently fail in privacy mode\n }\n }\n return {\n forcedGuideKey: urlGuideKey,\n previewSessionId: urlPreviewSessionId,\n };\n }\n\n // Check local storage if no URL params\n let storedGuideKey = null;\n let storedPreviewSessionId = null;\n\n if (win.localStorage) {\n try {\n const storedDebugState = win.localStorage.getItem(DEBUG_STORAGE_KEY);\n if (storedDebugState) {\n const parsedDebugState = safeJsonParseDebugParams(storedDebugState);\n storedGuideKey = parsedDebugState.forcedGuideKey;\n storedPreviewSessionId = parsedDebugState.previewSessionId;\n }\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n return {\n forcedGuideKey: storedGuideKey,\n previewSessionId: storedPreviewSessionId,\n };\n};\n\nconst safeJsonParseDebugParams = (value: string): DebugState => {\n try {\n const parsed = JSON.parse(value);\n return {\n forcedGuideKey: parsed?.forcedGuideKey ?? null,\n previewSessionId: parsed?.previewSessionId ?? null,\n };\n } catch {\n return {\n forcedGuideKey: null,\n previewSessionId: null,\n };\n }\n};\n\nconst select = (state: StoreState, filters: SelectFilterParams = {}) => {\n // A map of selected guides as values, with its order index as keys.\n const result = new SelectionResult();\n\n const defaultGroup = findDefaultGroup(state.guideGroups);\n if (!defaultGroup) return result;\n\n const displaySequence = [...defaultGroup.display_sequence];\n const location = state.location;\n\n // If in debug mode, put the forced guide at the beginning of the display sequence.\n if (state.debug.forcedGuideKey) {\n const forcedKeyIndex = displaySequence.indexOf(state.debug.forcedGuideKey);\n if (forcedKeyIndex > -1) {\n displaySequence.splice(forcedKeyIndex, 1);\n }\n displaySequence.unshift(state.debug.forcedGuideKey);\n }\n\n for (const [index, guideKey] of displaySequence.entries()) {\n let guide = state.guides[guideKey];\n\n // Use preview guide if it exists and matches the forced guide key\n if (\n state.debug.forcedGuideKey === guideKey &&\n state.previewGuides[guideKey]\n ) {\n guide = state.previewGuides[guideKey];\n }\n\n if (!guide) continue;\n\n const affirmed = predicate(guide, {\n location,\n filters,\n debug: state.debug,\n });\n\n if (!affirmed) continue;\n\n result.set(index, guide);\n }\n\n result.metadata = { guideGroup: defaultGroup };\n return result;\n};\n\ntype PredicateOpts = {\n location?: string | undefined;\n filters?: SelectFilterParams | undefined;\n debug: DebugState;\n};\n\nconst predicate = (\n guide: KnockGuide,\n { location, filters = {}, debug = {} }: PredicateOpts,\n) => {\n if (filters.type && filters.type !== guide.type) {\n return false;\n }\n\n if (filters.key && filters.key !== guide.key) {\n return false;\n }\n\n // Bypass filtering if the debugged guide matches the given filters.\n // This should always run AFTER checking the filters but BEFORE\n // checking archived status and location rules.\n if (debug.forcedGuideKey === guide.key) {\n return true;\n }\n\n if (!guide.active) {\n return false;\n }\n\n if (guide.steps.every((s) => !!s.message.archived_at)) {\n return false;\n }\n\n const url = location ? newUrl(location) : undefined;\n\n const urlRules = guide.activation_url_rules || [];\n const urlPatterns = guide.activation_url_patterns || [];\n\n // A guide can have either activation url rules XOR url patterns, but not both.\n if (url && urlRules.length > 0) {\n const allowed = predicateUrlRules(url, urlRules);\n if (!allowed) return false;\n } else if (url && urlPatterns.length > 0) {\n const allowed = predicateUrlPatterns(url, urlPatterns);\n if (!allowed) return false;\n }\n\n return true;\n};\n\nexport class KnockGuideClient {\n public store: Store<StoreState, (state: StoreState) => StoreState>;\n\n // Phoenix channels for real time guide updates over websocket\n private socket: Socket | undefined;\n private socketChannel: Channel | undefined;\n private socketChannelTopic: string;\n private socketEventTypes = [\n \"guide.added\",\n \"guide.updated\",\n \"guide.removed\",\n \"guide_group.added\",\n \"guide_group.updated\",\n \"guide.live_preview_updated\",\n ];\n private subscribeRetryCount = 0;\n\n // Original history methods to monkey patch, or restore in cleanups.\n private pushStateFn: History[\"pushState\"] | undefined;\n private replaceStateFn: History[\"replaceState\"] | undefined;\n\n // Guides that are competing to render are \"staged\" first without rendering\n // and ranked based on its relative order in the group over a duration of time\n // to resolve and render the prevailing one.\n private stage: GroupStage | undefined;\n\n private counterIntervalId: ReturnType<typeof setInterval> | undefined;\n\n constructor(\n readonly knock: Knock,\n readonly channelId: string,\n readonly targetParams: TargetParams = {},\n readonly options: ConstructorOpts = {},\n ) {\n const {\n trackLocationFromWindow = true,\n throttleCheckInterval = DEFAULT_COUNTER_INCREMENT_INTERVAL,\n } = options;\n const win = checkForWindow();\n\n const location = trackLocationFromWindow ? win?.location.href : undefined;\n\n const debug = detectDebugParams();\n\n this.store = new Store<StoreState>({\n guideGroups: [],\n guideGroupDisplayLogs: {},\n guides: {},\n previewGuides: {},\n queries: {},\n location,\n // Increment to update the state store and trigger re-selection.\n counter: 0,\n debug,\n });\n\n // In server environments we might not have a socket connection.\n const { socket: maybeSocket } = this.knock.client();\n this.socket = maybeSocket;\n this.socketChannelTopic = `guides:${channelId}`;\n\n if (trackLocationFromWindow) {\n this.listenForLocationChangesFromWindow();\n }\n\n if (throttleCheckInterval) {\n // Start the counter loop to increment at an interval.\n this.startCounterInterval(throttleCheckInterval);\n }\n\n this.knock.log(\"[Guide] Initialized a guide client\");\n }\n\n private incrementCounter() {\n this.knock.log(\"[Guide] Incrementing the counter\");\n this.store.setState((state) => ({ ...state, counter: state.counter + 1 }));\n }\n\n private startCounterInterval(delay: number) {\n this.counterIntervalId = setInterval(() => {\n this.knock.log(\"[Guide] Counter interval tick\");\n if (this.stage && this.stage.status !== \"closed\") return;\n\n this.incrementCounter();\n }, delay);\n }\n\n private clearCounterInterval() {\n if (this.counterIntervalId) {\n clearInterval(this.counterIntervalId);\n this.counterIntervalId = undefined;\n }\n }\n\n cleanup() {\n this.unsubscribe();\n this.removeLocationChangeEventListeners();\n this.clearGroupStage();\n this.clearCounterInterval();\n }\n\n async fetch(opts?: { filters?: QueryFilterParams }) {\n this.knock.log(\"[Guide] .fetch\");\n this.knock.failIfNotAuthenticated();\n\n const queryParams = this.buildQueryParams(opts?.filters);\n const queryKey = this.formatQueryKey(queryParams);\n\n // If already fetched before, then noop.\n const maybeQueryStatus = this.store.state.queries[queryKey];\n if (maybeQueryStatus) {\n return maybeQueryStatus;\n }\n\n // Mark this query status as loading.\n this.store.setState((state) => ({\n ...state,\n queries: { ...state.queries, [queryKey]: { status: \"loading\" } },\n }));\n\n let queryStatus: QueryStatus;\n try {\n this.knock.log(\"[Guide] Fetching all eligible guides\");\n const data = await this.knock.user.getGuides<\n GetGuidesQueryParams,\n GetGuidesResponse\n >(this.channelId, queryParams);\n queryStatus = { status: \"ok\" };\n\n const { entries, guide_groups: groups, guide_group_display_logs } = data;\n\n this.knock.log(\"[Guide] Loading fetched guides\");\n this.store.setState((state) => ({\n ...state,\n guideGroups: groups?.length > 0 ? groups : [mockDefaultGroup(entries)],\n guideGroupDisplayLogs: guide_group_display_logs || {},\n guides: byKey(entries.map((g) => this.localCopy(g))),\n queries: { ...state.queries, [queryKey]: queryStatus },\n }));\n } catch (e) {\n queryStatus = { status: \"error\", error: e as Error };\n\n this.store.setState((state) => ({\n ...state,\n queries: { ...state.queries, [queryKey]: queryStatus },\n }));\n }\n\n return queryStatus;\n }\n\n subscribe() {\n if (!this.socket) return;\n this.knock.failIfNotAuthenticated();\n this.knock.log(\"[Guide] Subscribing to real time updates\");\n\n // Ensure a live socket connection if not yet connected.\n if (!this.socket.isConnected()) {\n this.socket.connect();\n }\n\n // If there's an existing connected channel, then disconnect.\n if (this.socketChannel) {\n this.unsubscribe();\n }\n\n // Join the channel topic and subscribe to supported events.\n const debugState = this.store.state.debug;\n const params = {\n ...this.targetParams,\n user_id: this.knock.userId,\n force_all_guides: debugState.forcedGuideKey ? true : undefined,\n preview_session_id: debugState.previewSessionId || undefined,\n };\n\n const newChannel = this.socket.channel(this.socketChannelTopic, params);\n\n for (const eventType of this.socketEventTypes) {\n newChannel.on(eventType, (payload) => this.handleSocketEvent(payload));\n }\n\n if ([\"closed\", \"errored\"].includes(newChannel.state)) {\n // Reset retry count for new subscription attempt\n this.subscribeRetryCount = 0;\n\n newChannel\n .join()\n .receive(\"ok\", () => {\n this.knock.log(\"[Guide] Successfully joined channel\");\n })\n .receive(\"error\", (resp) => {\n this.knock.log(\n `[Guide] Failed to join channel: ${JSON.stringify(resp)}`,\n );\n this.handleChannelJoinError();\n })\n .receive(\"timeout\", () => {\n this.knock.log(\"[Guide] Channel join timed out\");\n this.handleChannelJoinError();\n });\n }\n\n // Track the joined channel.\n this.socketChannel = newChannel;\n }\n\n private handleChannelJoinError() {\n // Prevent phx channel from retrying forever in case of either network or\n // other errors (e.g. auth error, invalid channel etc)\n if (this.subscribeRetryCount >= SUBSCRIBE_RETRY_LIMIT) {\n this.knock.log(\n `[Guide] Channel join max retry limit reached: ${this.subscribeRetryCount}`,\n );\n this.unsubscribe();\n return;\n }\n\n this.subscribeRetryCount++;\n }\n\n unsubscribe() {\n if (!this.socketChannel) return;\n this.knock.log(\"[Guide] Unsubscribing from real time updates\");\n\n // Unsubscribe from the socket events and leave the channel.\n for (const eventType of this.socketEventTypes) {\n this.socketChannel.off(eventType);\n }\n this.socketChannel.leave();\n\n // Unset the channel.\n this.socketChannel = undefined;\n }\n\n private handleSocketEvent(payload: GuideSocketEvent) {\n const { event, data } = payload;\n\n switch (event) {\n case \"guide.added\":\n return this.addOrReplaceGuide(payload);\n\n case \"guide.updated\":\n return data.eligible\n ? this.addOrReplaceGuide(payload)\n : this.removeGuide(payload);\n\n case \"guide.removed\":\n return this.removeGuide(payload);\n\n case \"guide_group.added\":\n case \"guide_group.updated\":\n return this.addOrReplaceGuideGroup(payload);\n\n case \"guide.live_preview_updated\":\n return this.updatePreviewGuide(payload);\n\n default:\n return;\n }\n }\n\n setLocation(href: string, additionalParams: Partial<StoreState> = {}) {\n this.knock.log(`[Guide] .setLocation (loc=${href})`);\n\n // Make sure to clear out the stage.\n this.clearGroupStage();\n\n this.knock.log(\"[Guide] Updating the tracked location\");\n this.store.setState((state) => {\n // Clear preview guides if no longer in preview mode\n const previewGuides = additionalParams?.debug?.previewSessionId\n ? state.previewGuides\n : {};\n\n return {\n ...state,\n ...additionalParams,\n previewGuides,\n location: href,\n };\n });\n }\n\n exitDebugMode() {\n this.knock.log(\"[Guide] Exiting debug mode\");\n\n // Clear localStorage debug params\n const win = checkForWindow();\n if (win?.localStorage) {\n try {\n win.localStorage.removeItem(DEBUG_STORAGE_KEY);\n } catch {\n // Silently fail in privacy mode\n }\n }\n\n // Clear debug state from store\n this.store.setState((state) => ({\n ...state,\n debug: { forcedGuideKey: null, previewSessionId: null },\n previewGuides: {}, // Clear preview guides when exiting debug mode\n }));\n\n // Remove URL query params if present\n // Only update the URL if params need to be cleared to avoid unnecessary navigations\n if (win) {\n const url = new URL(win.location.href);\n if (\n url.searchParams.has(DEBUG_QUERY_PARAMS.GUIDE_KEY) ||\n url.searchParams.has(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID)\n ) {\n url.searchParams.delete(DEBUG_QUERY_PARAMS.GUIDE_KEY);\n url.searchParams.delete(DEBUG_QUERY_PARAMS.PREVIEW_SESSION_ID);\n win.location.href = url.toString();\n }\n }\n }\n\n //\n // Store selector\n //\n\n selectGuides<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n opts: SelectGuidesOpts = {},\n ): KnockGuide<C>[] {\n this.knock.log(\n `[Guide] .selectGuides (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n\n const selectedGuide = this.selectGuide(state, filters, opts);\n if (!selectedGuide) {\n return [];\n }\n\n // There should be at least one guide to return here now.\n const guides = [...select(state, filters).values()];\n\n if (!opts.includeThrottled && checkStateIfThrottled(state)) {\n const unthrottledGuides = guides.filter(\n (g) => g.bypass_global_group_limit,\n );\n const throttledCount = guides.length - unthrottledGuides.length;\n this.knock.log(\n `[Guide] Throttling ${throttledCount} guides from selection, and returning ${unthrottledGuides.length} guides`,\n );\n\n return unthrottledGuides;\n }\n\n this.knock.log(`[Guide] Returning ${guides.length} guides from selection`);\n return guides;\n }\n\n selectGuide<C = Any>(\n state: StoreState,\n filters: SelectFilterParams = {},\n opts: SelectGuideOpts = {},\n ): KnockGuide<C> | undefined {\n this.knock.log(\n `[Guide] .selectGuide (filters: ${formatFilters(filters)}; state: ${formatState(state)})`,\n );\n if (\n Object.keys(state.guides).length === 0 &&\n Object.keys(state.previewGuides).length === 0\n ) {\n this.knock.log(\"[Guide] Exiting selection (no guides)\");\n return undefined;\n }\n\n const result = select(state, filters);\n\n if (result.size === 0) {\n this.knock.log(\"[Guide] Selection found zero result\");\n return undefined;\n }\n\n const [index, guide] = [...result][0]!;\n this.knock.log(\n `[Guide] Selection found: \\`${guide.key}\\` (total: ${result.size})`,\n );\n\n // If a guide ignores the group limit, then return immediately to render\n // always.\n if (guide.bypass_global_group_limit) {\n this.knock.log(`[Guide] Returning the unthrottled guide: ${guide.key}`);\n return guide;\n }\n\n // Check if inside the throttle window (i.e. throttled) and if so stop and\n // return undefined unless explicitly given the option to include throttled.\n if (!opts.includeThrottled && checkStateIfThrottled(state)) {\n this.knock.log(`[Guide] Throttling the selected guide: ${guide.key}`);\n return undefined;\n }\n\n // Starting here to the end of this method represents the core logic of how\n // \"group stage\" works. It provides a mechanism for 1) figuring out which\n // guide components are about to render on a page, 2) determining which\n // among them ranks highest in the configured display sequence, and 3)\n // returning only the prevailing guide to render at a time.\n //\n // Imagine N number of components that use the `useGuide()` hook which\n // calls this `selectGuide()` method, and the logic works like this:\n // * The first time this method is called, we don't have an \"open\" group\n // stage, so we open one (this occurs when a new page/route is rendering).\n // * While it is open, we record which guide was selected and its order\n // index from each call, but we do NOT return any guide to render yet.\n // * When a group stage opens, it schedules a timer to close itself. How\n // long this timer waits is configurable. Note, `setTimeout` with 0\n // delay seems to work well for React apps, where we \"yield\" to React\n // for one render cycle and close the group right after.\n // * When a group stage closes, we evaluate which guides were selected and\n // recorded, then determine the winning guide (i.e. the one with the\n // lowest order index value).\n // * Then increment the internal counter to trigger a store state update,\n // which allows `useGuide()` and `selectGuide()` to re-run. This second\n // round of `selectGuide()` calls, occurring when the group stage is\n // closed, results in returning the prevailing guide.\n // * Whenever a user navigates to a new page, we repeat the same process\n // above.\n // * There's a third status called \"patch,\" which is for handling real-time\n // updates received from the API. It's similar to the \"open\" to \"closed\"\n // flow, except we keep the resolved guide in place while we recalculate.\n // This is done so that we don't cause flickers or CLS.\n if (!this.stage) {\n this.stage = this.openGroupStage(); // Assign here to make tsc happy\n }\n\n switch (this.stage.status) {\n case \"open\": {\n this.knock.log(`[Guide] Adding to the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n return undefined;\n }\n\n case \"patch\": {\n this.knock.log(`[Guide] Patching the group stage: ${guide.key}`);\n this.stage.ordered[index] = guide.key;\n\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\n }\n\n case \"closed\": {\n const ret = this.stage.resolved === guide.key ? guide : undefined;\n this.knock.log(\n `[Guide] Returning \\`${ret?.key}\\` (stage: ${formatGroupStage(this.stage)})`,\n );\n return ret;\n }\n }\n }\n\n private openGroupStage() {\n this.knock.log(\"[Guide] Opening a new group stage\");\n\n const {\n orderResolutionDuration: delay = DEFAULT_ORDER_RESOLUTION_DURATION,\n } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n this.stage = {\n status: \"open\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n // Close the current non-closed stage to resolve the prevailing guide up next\n // for display amongst the ones that have been staged.\n private closePendingGroupStage() {\n this.knock.log(\"[Guide] .closePendingGroupStage\");\n if (!this.stage || this.stage.status === \"closed\") return;\n\n // Should have been cleared already since this method should be called as a\n // callback to a setTimeout, but just to be safe.\n this.ensureClearTimeout();\n\n // If in debug mode, try to resolve the forced guide, otherwise return the first non-undefined guide.\n let resolved = undefined;\n if (this.store.state.debug.forcedGuideKey) {\n resolved = this.stage.ordered.find(\n (x) => x === this.store.state.debug.forcedGuideKey,\n );\n }\n\n if (!resolved) {\n resolved = this.stage.ordered.find((x) => x !== undefined);\n }\n\n this.knock.log(\n `[Guide] Closing the current group stage: resolved=${resolved}`,\n );\n\n this.stage = {\n ...this.stage,\n status: \"closed\",\n resolved,\n timeoutId: null,\n };\n\n return this.stage;\n }\n\n // Set the current closed stage status to \"patch\" to allow re-running\n // selections and re-building a group stage with the latest/updated state,\n // while keeping the currently resolved guide in place so that it stays\n // rendered until we are ready to resolve the updated stage and re-render.\n // Note, must be called ahead of updating the state store.\n private patchClosedGroupStage() {\n this.knock.log(\"[Guide] .patchClosedGroupStage\");\n if (this.stage?.status !== \"closed\") return;\n\n const { orderResolutionDuration: delay = 0 } = this.options;\n\n const timeoutId = setTimeout(() => {\n this.closePendingGroupStage();\n this.incrementCounter();\n }, delay);\n\n // Just to be safe.\n this.ensureClearTimeout();\n\n this.knock.log(\"[Guide] Patching the current group stage\");\n\n this.stage = {\n ...this.stage,\n status: \"patch\",\n ordered: [],\n timeoutId,\n };\n\n return this.stage;\n }\n\n private clearGroupStage() {\n this.knock.log(\"[Guide] .clearGroupStage\");\n if (!this.stage) return;\n\n this.knock.log(\"[Guide] Clearing the current group stage\");\n this.ensureClearTimeout();\n this.stage = undefined;\n }\n\n private ensureClearTimeout() {\n if (this.stage?.timeoutId) {\n clearTimeout(this.stage.timeoutId);\n }\n }\n\n // Test helpers to open and close the group stage to return the select result\n // immediately.\n private _selectGuide(\n state: StoreState,\n filters: SelectFilterParams = {},\n opts: SelectGuideOpts = {},\n ) {\n this.openGroupStage();\n\n this.selectGuide(state, filters, opts);\n this.closePendingGroupStage();\n\n return this.selectGuide(state, filters, opts);\n }\n\n private _selectGuides(\n state: StoreState,\n filters: SelectFilterParams = {},\n opts: SelectGuidesOpts = {},\n ) {\n this.openGroupStage();\n\n this.selectGuides(state, filters, opts);\n this.closePendingGroupStage();\n\n return this.selectGuides(state, filters, opts);\n }\n\n //\n // Engagement event handlers\n //\n // Make an optimistic update on the client side first, then send an engagement\n // event to the backend.\n //\n\n async markAsSeen(guide: GuideData, step: GuideStepData) {\n if (step.message.seen_at) return;\n\n this.knock.log(\n `[Guide] Marking as seen (Guide key: ${guide.key}, Step ref:${step.ref})`,\n );\n\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n seen_at: new Date().toISOString(),\n });\n if (!updatedStep) return;\n\n const params = {\n ...this.buildEngagementEventBaseParams(guide, updatedStep),\n content: updatedStep.content,\n data: this.targetParams.data,\n };\n\n this.knock.user.markGuideStepAs<MarkAsSeenParams, MarkGuideAsResponse>(\n \"seen\",\n params,\n );\n\n return updatedStep;\n }\n\n async markAsInteracted(\n guide: GuideData,\n step: GuideStepData,\n metadata?: GenericData,\n ) {\n this.knock.log(\n `[Guide] Marking as interacted (Guide key: ${guide.key}; Step ref:${step.ref})`,\n );\n\n const ts = new Date().toISOString();\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n read_at: ts,\n interacted_at: ts,\n });\n if (!updatedStep) return;\n\n const params = {\n ...this.buildEngagementEventBaseParams(guide, updatedStep),\n metadata,\n };\n\n this.knock.user.markGuideStepAs<\n MarkAsInteractedParams,\n MarkGuideAsResponse\n >(\"interacted\", params);\n\n return updatedStep;\n }\n\n async markAsArchived(guide: GuideData, step: GuideStepData) {\n if (step.message.archived_at) return;\n\n this.knock.log(\n `[Guide] Marking as archived (Guide key: ${guide.key}, Step ref:${step.ref})`,\n );\n\n const updatedStep = this.setStepMessageAttrs(guide.key, step.ref, {\n archived_at: new Date().toISOString(),\n });\n if (!updatedStep) return;\n\n const params = this.buildEngagementEventBaseParams(guide, updatedStep);\n\n this.knock.user.markGuideStepAs<MarkAsArchivedParams, MarkGuideAsResponse>(\n \"archived\",\n {\n ...params,\n unthrottled: guide.bypass_global_group_limit,\n },\n );\n\n return updatedStep;\n }\n\n //\n // Helpers\n //\n\n private localCopy(remoteGuide: GuideData) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n // Build a local copy with helper methods added.\n const localGuide = {\n ...remoteGuide,\n // Get the next unarchived step.\n getStep() {\n // If debugging this guide, return the first step regardless of archive status\n if (self.store.state.debug.forcedGuideKey === this.key) {\n return this.steps[0];\n }\n\n return this.steps.find((s) => !s.message.archived_at);\n },\n } as KnockGuide;\n\n localGuide.getStep = localGuide.getStep.bind(localGuide);\n\n localGuide.steps = remoteGuide.steps.map(({ message, ...rest }) => {\n const localStep = {\n ...rest,\n message: { ...message },\n markAsSeen() {\n // Send a seen event if it has not been previously seen.\n if (this.message.seen_at) return;\n return self.markAsSeen(localGuide, this);\n },\n markAsInteracted({ metadata }: { metadata?: GenericData } = {}) {\n // Always send an interaction event through.\n return self.markAsInteracted(localGuide, this, metadata);\n },\n markAsArchived() {\n // Send an archived event if it has not been previously archived.\n if (this.message.archived_at) return;\n return self.markAsArchived(localGuide, this);\n },\n };\n\n // Bind all engagement action handler methods to the local step object so\n // they can operate on itself.\n localStep.markAsSeen = localStep.markAsSeen.bind(localStep);\n localStep.markAsInteracted = localStep.markAsInteracted.bind(localStep);\n localStep.markAsArchived = localStep.markAsArchived.bind(localStep);\n\n return localStep;\n });\n\n localGuide.activation_url_patterns =\n remoteGuide.activation_url_patterns.map((rule) => {\n return {\n ...rule,\n pattern: new URLPattern({ pathname: rule.pathname }),\n };\n });\n\n return localGuide;\n }\n\n private buildQueryParams(filterParams: QueryFilterParams = {}) {\n // Combine the target params with the given filter params.\n const combinedParams: GenericData = {\n ...this.targetParams,\n ...filterParams,\n };\n\n // Append debug params\n const debugState = this.store.state.debug;\n if (debugState.forcedGuideKey) {\n combinedParams.force_all_guides = true;\n }\n\n // Prune out any keys that have an undefined or null value.\n let params = Object.fromEntries(\n Object.entries(combinedParams).filter(\n ([_k, v]) => v !== undefined && v !== null,\n ),\n );\n\n // Encode target data as a JSON string, if provided.\n params = params.data\n ? { ...params, data: JSON.stringify(params.data) }\n : params;\n\n return params as GetGuidesQueryParams;\n }\n\n private formatQueryKey(queryParams: GenericData) {\n const sortedKeys = Object.keys(queryParams).sort();\n\n const queryStr = sortedKeys\n .map(\n (key) =>\n `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`,\n )\n .join(\"&\");\n\n const basePath = guidesApiRootPath(this.knock.userId);\n return queryStr ? `${basePath}?${queryStr}` : basePath;\n }\n\n private setStepMessageAttrs(\n guideKey: string,\n stepRef: string,\n attrs: Partial<StepMessageState>,\n ) {\n let updatedStep: KnockGuideStep | undefined;\n\n // If we are marking as archived, clear the group stage so we can render\n // the next guide in the group.\n if (attrs.archived_at) {\n this.clearGroupStage();\n }\n\n this.store.setState((state) => {\n let guide = state.guides[guideKey];\n if (!guide) return state;\n\n const steps = guide.steps.map((step) => {\n if (step.ref !== stepRef) return step;\n\n // Mutate in place and maintain the same obj ref so to make it easier\n // to use in hook deps.\n step.message = { ...step.message, ...attrs };\n updatedStep = step;\n\n return step;\n });\n // If updated, return the guide as a new object so useStore can trigger.\n guide = updatedStep ? { ...guide, steps } : guide;\n\n const guides = { ...state.guides, [guide.key]: guide };\n\n // If the guide is subject to throttled settings and we are marking as\n // archived, then update the display logs to start a new throttle window.\n const guideGroupDisplayLogs =\n attrs.archived_at && !guide.bypass_global_group_limit\n ? {\n ...state.guideGroupDisplayLogs,\n [DEFAULT_GROUP_KEY]: attrs.archived_at,\n }\n : state.guideGroupDisplayLogs;\n\n return { ...state, guides, guideGroupDisplayLogs };\n });\n\n return updatedStep;\n }\n\n private buildEngagementEventBaseParams(\n guide: GuideData,\n step: GuideStepData,\n ) {\n return {\n channel_id: guide.channel_id,\n guide_key: guide.key,\n guide_id: guide.id,\n guide_step_ref: step.ref,\n // Can be used for scoping guide messages.\n tenant: this.targetParams.tenant,\n };\n }\n\n private addOrReplaceGuide({ data }: GuideAddedEvent | GuideUpdatedEvent) {\n this.patchClosedGroupStage();\n\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const guides = { ...state.guides, [guide.key]: guide };\n\n return { ...state, guides };\n });\n }\n\n private removeGuide({ data }: GuideUpdatedEvent | GuideRemovedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n const { [data.guide.key]: _, ...rest } = state.guides;\n return { ...state, guides: rest };\n });\n }\n\n private addOrReplaceGuideGroup({\n data,\n }: GuideGroupAddedEvent | GuideGroupUpdatedEvent) {\n this.patchClosedGroupStage();\n\n this.store.setState((state) => {\n // Currently we only support a single default global group, so we can just\n // update the list with the added/updated group.\n const guideGroups = [data.guide_group];\n\n // A guide group event can include lists of unthrottled vs throttled guide\n // keys which we can use to bulk update the guides in the store already.\n const unthrottled = data.guide_group.display_sequence_unthrottled || [];\n const throttled = data.guide_group.display_sequence_throttled || [];\n\n let guides = state.guides;\n\n guides = unthrottled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: true };\n return { ...acc, [key]: guide };\n }, guides);\n\n guides = throttled.reduce((acc, key) => {\n if (!acc[key]) return acc;\n const guide = { ...acc[key], bypass_global_group_limit: false };\n return { ...acc, [key]: guide };\n }, guides);\n\n return { ...state, guides, guideGroups };\n });\n }\n\n private updatePreviewGuide({ data }: GuideLivePreviewUpdatedEvent) {\n const guide = this.localCopy(data.guide);\n\n this.store.setState((state) => {\n const previewGuides = { ...state.previewGuides, [guide.key]: guide };\n return { ...state, previewGuides };\n });\n }\n\n // Define as an arrow func property to always bind this to the class instance.\n private handleLocationChange = () => {\n this.knock.log(`[Guide] .handleLocationChange`);\n const win = checkForWindow();\n if (!win?.location) return;\n\n const href = win.location.href;\n if (this.store.state.location === href) return;\n\n this.knock.log(`[Guide] Detected a location change: ${href}`);\n\n // If entering debug mode, fetch all guides.\n const currentDebugParams = this.store.state.debug;\n const newDebugParams = detectDebugParams();\n\n this.setLocation(href, { debug: newDebugParams });\n\n // If debug state has changed, refetch guides and resubscribe to the websocket channel\n const debugStateChanged = this.checkDebugStateChanged(\n currentDebugParams,\n newDebugParams,\n );\n\n if (debugStateChanged) {\n this.knock.log(\n `[Guide] Debug state changed, refetching guides and resubscribing to the websocket channel`,\n );\n this.fetch();\n this.subscribe();\n }\n };\n\n // Returns whether debug params have changed. For guide key, we only check\n // presence since the exact value has no impact on fetch/subscribe\n private checkDebugStateChanged(a: DebugState, b: DebugState): boolean {\n return (\n Boolean(a.forcedGuideKey) !== Boolean(b.forcedGuideKey) ||\n a.previewSessionId !== b.previewSessionId\n );\n }\n\n private listenForLocationChangesFromWindow() {\n const win = checkForWindow();\n if (win?.history) {\n // 1. Listen for browser back/forward button clicks.\n win.addEventListener(\"popstate\", this.handleLocationChange);\n\n // 2. Listen for hash changes in case it's used for routing.\n win.addEventListener(\"hashchange\", this.handleLocationChange);\n\n // 3. Monkey-patch history methods to catch programmatic navigation.\n const pushStateFn = win.history.pushState;\n const replaceStateFn = win.history.replaceState;\n\n // Use setTimeout to allow the browser state to potentially settle.\n win.history.pushState = new Proxy(pushStateFn, {\n apply: (target, history, args) => {\n Reflect.apply(target, history, args);\n setTimeout(() => {\n this.handleLocationChange();\n }, 0);\n },\n });\n win.history.replaceState = new Proxy(replaceStateFn, {\n apply: (target, history, args) => {\n Reflect.apply(target, history, args);\n setTimeout(() => {\n this.handleLocationChange();\n }, 0);\n },\n });\n\n // 4. Keep refs to the original handlers so we can restore during cleanup.\n this.pushStateFn = pushStateFn;\n this.replaceStateFn = replaceStateFn;\n } else {\n this.knock.log(\n \"[Guide] Unable to access the `window.history` object to detect location changes\",\n );\n }\n }\n\n removeLocationChangeEventListeners() {\n const win = checkForWindow();\n if (!win?.history) return;\n\n win.removeEventListener(\"popstate\", this.handleLocationChange);\n win.removeEventListener(\"hashchange\", this.handleLocationChange);\n\n if (this.pushStateFn) {\n win.history.pushState = this.pushStateFn;\n this.pushStateFn = undefined;\n }\n if (this.replaceStateFn) {\n win.history.replaceState = this.replaceStateFn;\n this.replaceStateFn = undefined;\n }\n }\n}\n"],"names":["DEFAULT_ORDER_RESOLUTION_DURATION","DEFAULT_COUNTER_INCREMENT_INTERVAL","SUBSCRIBE_RETRY_LIMIT","DEBUG_QUERY_PARAMS","DEBUG_STORAGE_KEY","checkForWindow","guidesApiRootPath","userId","detectDebugParams","win","urlParams","urlGuideKey","urlPreviewSessionId","debugState","storedGuideKey","storedPreviewSessionId","storedDebugState","parsedDebugState","safeJsonParseDebugParams","value","parsed","select","state","filters","result","SelectionResult","defaultGroup","findDefaultGroup","displaySequence","location","forcedKeyIndex","index","guideKey","guide","predicate","debug","s","url","newUrl","urlRules","urlPatterns","predicateUrlRules","predicateUrlPatterns","KnockGuideClient","knock","channelId","targetParams","options","__publicField","href","currentDebugParams","newDebugParams","trackLocationFromWindow","throttleCheckInterval","Store","maybeSocket","delay","opts","queryParams","queryKey","maybeQueryStatus","queryStatus","data","entries","groups","guide_group_display_logs","mockDefaultGroup","byKey","g","e","params","newChannel","eventType","payload","resp","event","additionalParams","previewGuides","_a","formatFilters","formatState","guides","checkStateIfThrottled","unthrottledGuides","throttledCount","ret","formatGroupStage","timeoutId","resolved","x","step","updatedStep","metadata","ts","remoteGuide","self","localGuide","message","rest","localStep","rule","URLPattern","filterParams","combinedParams","_k","v","queryStr","key","basePath","stepRef","attrs","steps","guideGroupDisplayLogs","DEFAULT_GROUP_KEY","_","guideGroups","unthrottled","throttled","acc","a","b","pushStateFn","replaceStateFn","target","history","args"],"mappings":"kVAuDMA,EAAoC,GAIpCC,EAAqC,GAAK,IAG1CC,EAAwB,EAGjBC,EAAqB,CAChC,UAAW,kBACX,mBAAoB,0BACtB,EAEMC,EAAoB,oBAGpBC,EAAiB,IAAM,CACvB,GAAA,OAAO,OAAW,IACb,OAAA,MAEX,EAEaC,EAAqBC,GAChC,aAAaA,CAAM,UAGfC,EAAoB,IAAkB,CAC1C,MAAMC,EAAMJ,EAAe,EAC3B,GAAI,CAACI,EACH,MAAO,CAAE,eAAgB,KAAM,iBAAkB,IAAK,EAGxD,MAAMC,EAAY,IAAI,gBAAgBD,EAAI,SAAS,MAAM,EACnDE,EAAcD,EAAU,IAAIP,EAAmB,SAAS,EACxDS,EAAsBF,EAAU,IACpCP,EAAmB,kBACrB,EAGA,GAAIQ,GAAeC,EAAqB,CACtC,GAAIH,EAAI,aACF,GAAA,CACF,MAAMI,EAAa,CACjB,eAAgBF,EAChB,iBAAkBC,CACpB,EACAH,EAAI,aAAa,QAAQL,EAAmB,KAAK,UAAUS,CAAU,CAAC,CAAA,MAChE,CAAA,CAIH,MAAA,CACL,eAAgBF,EAChB,iBAAkBC,CACpB,CAAA,CAIF,IAAIE,EAAiB,KACjBC,EAAyB,KAE7B,GAAIN,EAAI,aACF,GAAA,CACF,MAAMO,EAAmBP,EAAI,aAAa,QAAQL,CAAiB,EACnE,GAAIY,EAAkB,CACd,MAAAC,EAAmBC,EAAyBF,CAAgB,EAClEF,EAAiBG,EAAiB,eAClCF,EAAyBE,EAAiB,gBAAA,CAC5C,MACM,CAAA,CAKH,MAAA,CACL,eAAgBH,EAChB,iBAAkBC,CACpB,CACF,EAEMG,EAA4BC,GAA8B,CAC1D,GAAA,CACI,MAAAC,EAAS,KAAK,MAAMD,CAAK,EACxB,MAAA,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F,oCAAqC,CACnC,MAAMjH,EAAMJ,EAAe,EACtBI,GAAA,MAAAA,EAAK,UAENA,EAAA,oBAAoB,WAAY,KAAK,oBAAoB,EACzDA,EAAA,oBAAoB,aAAc,KAAK,oBAAoB,EAE3D,KAAK,cACHA,EAAA,QAAQ,UAAY,KAAK,YAC7B,KAAK,YAAc,QAEjB,KAAK,iBACHA,EAAA,QAAQ,aAAe,KAAK,eAChC,KAAK,eAAiB,QACxB,CAEJ"}
@@ -1,2 +1,2 @@
1
- "use strict";var u=Object.defineProperty;var d=(e,t,r)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var s=(e,t,r)=>d(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class l extends Map{constructor(){super();s(this,"metadata")}}const m=e=>`status=${e.status}, resolved=${e.resolved}`,f=e=>`loc=${e.location}`,p=(e={})=>[e.key&&`key=${e.key}`,e.type&&`type=${e.type}`].filter(t=>t).join(", "),h=e=>e.reduce((t,r)=>({...t,[r.key]:r}),{}),y=e=>[...e].sort((t,r)=>new Date(t.inserted_at).getTime()-new Date(r.inserted_at).getTime()),c="default",i="$default",_=(e=[])=>{const t=new Date;return{__typename:"GuideGroup",key:i,display_sequence:y(e).map(r=>r.key),display_interval:null,inserted_at:t.toISOString(),updated_at:t.toISOString()}},g=e=>e.find(t=>t.key===c||t.key===i),w=(e,t)=>{const r=new Date(e);if(isNaN(r.getTime()))return!1;const n=r.getTime()+t*1e3;return new Date().getTime()<=n},U=e=>{try{return new URL(e)}catch{return}},o=(e,t)=>t.variable==="pathname"?t.operator==="equal_to"?(t.argument.startsWith("/")?t.argument:`/${t.argument}`)===e.pathname:t.operator==="contains"?e.pathname.includes(t.argument):!1:!1,k=(e,t)=>t.reduce((r,n)=>{if(r===!1)return!1;switch(n.directive){case"allow":return r===!0||o(e,n)?!0:void 0;case"block":return o(e,n)?!1:r}},void 0),v=(e,t)=>t.reduce((r,n)=>{if(r===!1)return!1;switch(n.directive){case"allow":return r===!0||n.pattern.test(e)?!0:void 0;case"block":return n.pattern.test(e)?!1:r}},void 0);exports.DEFAULT_GROUP_KEY=c;exports.SelectionResult=l;exports.byKey=h;exports.checkIfThrottled=w;exports.evaluateUrlRule=o;exports.findDefaultGroup=g;exports.formatFilters=p;exports.formatGroupStage=m;exports.formatState=f;exports.mockDefaultGroup=_;exports.newUrl=U;exports.predicateUrlPatterns=v;exports.predicateUrlRules=k;
1
+ "use strict";var d=Object.defineProperty;var l=(e,t,r)=>t in e?d(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var i=(e,t,r)=>l(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class f extends Map{constructor(){super();i(this,"metadata")}}const m=e=>`status=${e.status}, resolved=${e.resolved}`,p=e=>`loc=${e.location}`,h=(e={})=>[e.key&&`key=${e.key}`,e.type&&`type=${e.type}`].filter(t=>t).join(", "),y=e=>e.reduce((t,r)=>({...t,[r.key]:r}),{}),g=e=>[...e].sort((t,r)=>new Date(t.inserted_at).getTime()-new Date(r.inserted_at).getTime()),s="default",c="$default",_=(e=[])=>{const t=new Date;return{__typename:"GuideGroup",key:c,display_sequence:g(e).map(r=>r.key),display_interval:null,inserted_at:t.toISOString(),updated_at:t.toISOString()}},u=e=>e.find(t=>t.key===s||t.key===c),v=e=>{const t=u(e.guideGroups),r=e.guideGroupDisplayLogs[s];return t&&t.display_interval&&r?w(r,t.display_interval):!1},w=(e,t)=>{const r=new Date(e);if(isNaN(r.getTime()))return!1;const n=r.getTime()+t*1e3;return new Date().getTime()<=n},S=e=>{try{return new URL(e)}catch{return}},o=(e,t)=>t.variable==="pathname"?t.operator==="equal_to"?(t.argument.startsWith("/")?t.argument:`/${t.argument}`)===e.pathname:t.operator==="contains"?e.pathname.includes(t.argument):!1:!1,k=(e,t)=>t.reduce((r,n)=>{if(r===!1)return!1;switch(n.directive){case"allow":return r===!0||o(e,n)?!0:void 0;case"block":return o(e,n)?!1:r}},void 0),G=(e,t)=>t.reduce((r,n)=>{if(r===!1)return!1;switch(n.directive){case"allow":return r===!0||n.pattern.test(e)?!0:void 0;case"block":return n.pattern.test(e)?!1:r}},void 0);exports.DEFAULT_GROUP_KEY=s;exports.SelectionResult=f;exports.byKey=y;exports.checkStateIfThrottled=v;exports.evaluateUrlRule=o;exports.findDefaultGroup=u;exports.formatFilters=h;exports.formatGroupStage=m;exports.formatState=p;exports.mockDefaultGroup=_;exports.newUrl=S;exports.predicateUrlPatterns=G;exports.predicateUrlRules=k;
2
2
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sources":["../../../../src/clients/guide/helpers.ts"],"sourcesContent":["import {\n GroupStage,\n GuideActivationUrlRuleData,\n GuideData,\n GuideGroupData,\n KnockGuide,\n KnockGuideActivationUrlPattern,\n SelectFilterParams,\n StoreState,\n} from \"./types\";\n\n// Extends the map class to allow having metadata on it, which is used to record\n// the guide group context for the selection result (though currently only a\n// default global group is supported).\nexport class SelectionResult<K = number, V = KnockGuide> extends Map<K, V> {\n metadata: { guideGroup: GuideGroupData } | undefined;\n\n constructor() {\n super();\n }\n}\n\nexport const formatGroupStage = (stage: GroupStage) => {\n return `status=${stage.status}, resolved=${stage.resolved}`;\n};\n\nexport const formatState = (state: StoreState) => {\n return `loc=${state.location}`;\n};\n\nexport const formatFilters = (filters: SelectFilterParams = {}) => {\n return [\n filters.key && `key=${filters.key}`,\n filters.type && `type=${filters.type}`,\n ]\n .filter((x) => x)\n .join(\", \");\n};\n\nexport const byKey = <T extends { key: string }>(items: T[]) => {\n return items.reduce((acc, item) => ({ ...acc, [item.key]: item }), {});\n};\n\nconst sortGuides = <T extends GuideData>(guides: T[]) => {\n return [...guides].sort(\n (a, b) =>\n new Date(a.inserted_at).getTime() - new Date(b.inserted_at).getTime(),\n );\n};\n\n// Default global guide group key.\nexport const DEFAULT_GROUP_KEY = \"default\";\n\n// Prefixed with a special char $ to distinguish from an actual default group.\nconst MOCK_DEFAULT_GROUP_KEY = \"$default\";\n\n// Build a notional default group to fall back on in case there is none, only\n// for safety as there should always be a default guide group created.\nexport const mockDefaultGroup = (entries: GuideData[] = []) => {\n const now = new Date();\n\n return {\n __typename: \"GuideGroup\",\n key: MOCK_DEFAULT_GROUP_KEY,\n display_sequence: sortGuides(entries).map((g) => g.key),\n display_interval: null,\n inserted_at: now.toISOString(),\n updated_at: now.toISOString(),\n } as GuideGroupData;\n};\n\nexport const findDefaultGroup = (guideGroups: GuideGroupData[]) =>\n guideGroups.find(\n (group) =>\n group.key === DEFAULT_GROUP_KEY || group.key === MOCK_DEFAULT_GROUP_KEY,\n );\n\n// Checks whether we are currently throttled (inside a \"throttle window\").\n// A throttle window opens when a user dismisses (archives) a guide, and lasts\n// for the configured display interval of the guide group used (currently only\n// the default global group).\nexport const checkIfThrottled = (\n throttleWindowStartedAtTs: string,\n windowDurationInSeconds: number,\n) => {\n // 1. Parse the given timestamp string into a Date object.\n // Date.parse() handles ISO 8601 strings correctly and returns milliseconds\n // since epoch. This inherently handles timezones by converting everything to\n // a universal time representation (UTC).\n const throttleWindowStartDate = new Date(throttleWindowStartedAtTs);\n\n // Check if the given throttle window start timestamp string was valid, and\n // if not disregard.\n if (isNaN(throttleWindowStartDate.getTime())) {\n return false;\n }\n\n // 2. Calculate the throttle window end time in milliseconds by adding the\n // duration to the throttle window start time.\n const throttleWindowEndInMilliseconds =\n throttleWindowStartDate.getTime() + windowDurationInSeconds * 1000;\n\n // 3. Get the current timestamp in milliseconds since epoch.\n const currentTimeInMilliseconds = new Date().getTime();\n\n // 4. Compare the current timestamp with the calculated future timestamp.\n // Both are in milliseconds since epoch (UTC), so direct comparison is\n // accurate regardless of local timezones.\n return currentTimeInMilliseconds <= throttleWindowEndInMilliseconds;\n};\n\n// Safely parse and build a new URL object.\nexport const newUrl = (location: string) => {\n try {\n return new URL(location);\n } catch {\n return undefined;\n }\n};\n\n// Evaluates whether the given location url satisfies the url rule.\nexport const evaluateUrlRule = (\n url: URL,\n urlRule: GuideActivationUrlRuleData,\n) => {\n if (urlRule.variable === \"pathname\") {\n if (urlRule.operator === \"equal_to\") {\n const argument = urlRule.argument.startsWith(\"/\")\n ? urlRule.argument\n : `/${urlRule.argument}`;\n\n return argument === url.pathname;\n }\n\n if (urlRule.operator === \"contains\") {\n return url.pathname.includes(urlRule.argument);\n }\n\n return false;\n }\n\n return false;\n};\n\nexport const predicateUrlRules = (\n url: URL,\n urlRules: GuideActivationUrlRuleData[],\n) => {\n return urlRules.reduce<boolean | undefined>((acc, urlRule) => {\n // Any matched block rule prevails so no need to evaluate further\n // as soon as there is one.\n if (acc === false) return false;\n\n // At this point we either have a matched allow rule (acc is true),\n // or no matched rule found yet (acc is undefined).\n\n switch (urlRule.directive) {\n case \"allow\": {\n // No need to evaluate more allow rules once we matched one\n // since any matched allowed rule means allow.\n if (acc === true) return true;\n\n const matched = evaluateUrlRule(url, urlRule);\n return matched ? true : undefined;\n }\n\n case \"block\": {\n // Always test block rules (unless already matched to block)\n // because they'd prevail over matched allow rules.\n const matched = evaluateUrlRule(url, urlRule);\n return matched ? false : acc;\n }\n }\n }, undefined);\n};\n\nexport const predicateUrlPatterns = (\n url: URL,\n urlPatterns: KnockGuideActivationUrlPattern[],\n) => {\n return urlPatterns.reduce<boolean | undefined>((acc, urlPattern) => {\n // Any matched block rule prevails so no need to evaluate further\n // as soon as there is one.\n if (acc === false) return false;\n\n // At this point we either have a matched allow rule (acc is true),\n // or no matched rule found yet (acc is undefined).\n\n switch (urlPattern.directive) {\n case \"allow\": {\n // No need to evaluate more allow rules once we matched one\n // since any matched allowed rule means allow.\n if (acc === true) return true;\n\n const matched = urlPattern.pattern.test(url);\n return matched ? true : undefined;\n }\n\n case \"block\": {\n // Always test block rules (unless already matched to block)\n // because they'd prevail over matched allow rules.\n const matched = urlPattern.pattern.test(url);\n return matched ? false : acc;\n }\n }\n }, undefined);\n};\n"],"names":["SelectionResult","__publicField","formatGroupStage","stage","formatState","state","formatFilters","filters","x","byKey","items","acc","item","sortGuides","guides","a","b","DEFAULT_GROUP_KEY","MOCK_DEFAULT_GROUP_KEY","mockDefaultGroup","entries","now","g","findDefaultGroup","guideGroups","group","checkIfThrottled","throttleWindowStartedAtTs","windowDurationInSeconds","throttleWindowStartDate","throttleWindowEndInMilliseconds","newUrl","location","evaluateUrlRule","url","urlRule","predicateUrlRules","urlRules","predicateUrlPatterns","urlPatterns","urlPattern"],"mappings":"oPAcO,MAAMA,UAAoD,GAAU,CAGzE,aAAc,CACN,MAAA,EAHRC,EAAA,gBAGQ,CAEV,CAEa,MAAAC,EAAoBC,GACxB,UAAUA,EAAM,MAAM,cAAcA,EAAM,QAAQ,GAG9CC,EAAeC,GACnB,OAAOA,EAAM,QAAQ,GAGjBC,EAAgB,CAACC,EAA8B,KACnD,CACLA,EAAQ,KAAO,OAAOA,EAAQ,GAAG,GACjCA,EAAQ,MAAQ,QAAQA,EAAQ,IAAI,EAAA,EAEnC,OAAQC,GAAMA,CAAC,EACf,KAAK,IAAI,EAGDC,EAAoCC,GACxCA,EAAM,OAAO,CAACC,EAAKC,KAAU,CAAE,GAAGD,EAAK,CAACC,EAAK,GAAG,EAAGA,CAAK,GAAI,CAAA,CAAE,EAGjEC,EAAmCC,GAChC,CAAC,GAAGA,CAAM,EAAE,KACjB,CAACC,EAAGC,IACF,IAAI,KAAKD,EAAE,WAAW,EAAE,QAAA,EAAY,IAAI,KAAKC,EAAE,WAAW,EAAE,QAAQ,CACxE,EAIWC,EAAoB,UAG3BC,EAAyB,WAIlBC,EAAmB,CAACC,EAAuB,KAAO,CACvD,MAAAC,MAAU,KAET,MAAA,CACL,WAAY,aACZ,IAAKH,EACL,iBAAkBL,EAAWO,CAAO,EAAE,IAAKE,GAAMA,EAAE,GAAG,EACtD,iBAAkB,KAClB,YAAaD,EAAI,YAAY,EAC7B,WAAYA,EAAI,YAAY,CAC9B,CACF,EAEaE,EAAoBC,GAC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,"file":"helpers.js","sources":["../../../../src/clients/guide/helpers.ts"],"sourcesContent":["import {\n GroupStage,\n GuideActivationUrlRuleData,\n GuideData,\n GuideGroupData,\n KnockGuide,\n KnockGuideActivationUrlPattern,\n SelectFilterParams,\n StoreState,\n} from \"./types\";\n\n// Extends the map class to allow having metadata on it, which is used to record\n// the guide group context for the selection result (though currently only a\n// default global group is supported).\nexport class SelectionResult<K = number, V = KnockGuide> extends Map<K, V> {\n metadata: { guideGroup: GuideGroupData } | undefined;\n\n constructor() {\n super();\n }\n}\n\nexport const formatGroupStage = (stage: GroupStage) => {\n return `status=${stage.status}, resolved=${stage.resolved}`;\n};\n\nexport const formatState = (state: StoreState) => {\n return `loc=${state.location}`;\n};\n\nexport const formatFilters = (filters: SelectFilterParams = {}) => {\n return [\n filters.key && `key=${filters.key}`,\n filters.type && `type=${filters.type}`,\n ]\n .filter((x) => x)\n .join(\", \");\n};\n\nexport const byKey = <T extends { key: string }>(items: T[]) => {\n return items.reduce((acc, item) => ({ ...acc, [item.key]: item }), {});\n};\n\nconst sortGuides = <T extends GuideData>(guides: T[]) => {\n return [...guides].sort(\n (a, b) =>\n new Date(a.inserted_at).getTime() - new Date(b.inserted_at).getTime(),\n );\n};\n\n// Default global guide group key.\nexport const DEFAULT_GROUP_KEY = \"default\";\n\n// Prefixed with a special char $ to distinguish from an actual default group.\nconst MOCK_DEFAULT_GROUP_KEY = \"$default\";\n\n// Build a notional default group to fall back on in case there is none, only\n// for safety as there should always be a default guide group created.\nexport const mockDefaultGroup = (entries: GuideData[] = []) => {\n const now = new Date();\n\n return {\n __typename: \"GuideGroup\",\n key: MOCK_DEFAULT_GROUP_KEY,\n display_sequence: sortGuides(entries).map((g) => g.key),\n display_interval: null,\n inserted_at: now.toISOString(),\n updated_at: now.toISOString(),\n } as GuideGroupData;\n};\n\nexport const findDefaultGroup = (guideGroups: GuideGroupData[]) =>\n guideGroups.find(\n (group) =>\n group.key === DEFAULT_GROUP_KEY || group.key === MOCK_DEFAULT_GROUP_KEY,\n );\n\nexport const checkStateIfThrottled = (state: StoreState) => {\n const defaultGroup = findDefaultGroup(state.guideGroups);\n const throttleWindowStartedAt =\n state.guideGroupDisplayLogs[DEFAULT_GROUP_KEY];\n\n if (\n defaultGroup &&\n defaultGroup.display_interval &&\n throttleWindowStartedAt\n ) {\n return checkTimeIfThrottled(\n throttleWindowStartedAt,\n defaultGroup.display_interval,\n );\n }\n\n // Fall back to false, though this should never happen.\n return false;\n};\n\n// Checks whether we are currently throttled (inside a \"throttle window\").\n// A throttle window opens when a user dismisses (archives) a guide, and lasts\n// for the configured display interval of the guide group used (currently only\n// the default global group).\nconst checkTimeIfThrottled = (\n throttleWindowStartedAtTs: string,\n windowDurationInSeconds: number,\n) => {\n // 1. Parse the given timestamp string into a Date object.\n // Date.parse() handles ISO 8601 strings correctly and returns milliseconds\n // since epoch. This inherently handles timezones by converting everything to\n // a universal time representation (UTC).\n const throttleWindowStartDate = new Date(throttleWindowStartedAtTs);\n\n // Check if the given throttle window start timestamp string was valid, and\n // if not disregard.\n if (isNaN(throttleWindowStartDate.getTime())) {\n return false;\n }\n\n // 2. Calculate the throttle window end time in milliseconds by adding the\n // duration to the throttle window start time.\n const throttleWindowEndInMilliseconds =\n throttleWindowStartDate.getTime() + windowDurationInSeconds * 1000;\n\n // 3. Get the current timestamp in milliseconds since epoch.\n const currentTimeInMilliseconds = new Date().getTime();\n\n // 4. Compare the current timestamp with the calculated future timestamp.\n // Both are in milliseconds since epoch (UTC), so direct comparison is\n // accurate regardless of local timezones.\n return currentTimeInMilliseconds <= throttleWindowEndInMilliseconds;\n};\n\n// Safely parse and build a new URL object.\nexport const newUrl = (location: string) => {\n try {\n return new URL(location);\n } catch {\n return undefined;\n }\n};\n\n// Evaluates whether the given location url satisfies the url rule.\nexport const evaluateUrlRule = (\n url: URL,\n urlRule: GuideActivationUrlRuleData,\n) => {\n if (urlRule.variable === \"pathname\") {\n if (urlRule.operator === \"equal_to\") {\n const argument = urlRule.argument.startsWith(\"/\")\n ? urlRule.argument\n : `/${urlRule.argument}`;\n\n return argument === url.pathname;\n }\n\n if (urlRule.operator === \"contains\") {\n return url.pathname.includes(urlRule.argument);\n }\n\n return false;\n }\n\n return false;\n};\n\nexport const predicateUrlRules = (\n url: URL,\n urlRules: GuideActivationUrlRuleData[],\n) => {\n return urlRules.reduce<boolean | undefined>((acc, urlRule) => {\n // Any matched block rule prevails so no need to evaluate further\n // as soon as there is one.\n if (acc === false) return false;\n\n // At this point we either have a matched allow rule (acc is true),\n // or no matched rule found yet (acc is undefined).\n\n switch (urlRule.directive) {\n case \"allow\": {\n // No need to evaluate more allow rules once we matched one\n // since any matched allowed rule means allow.\n if (acc === true) return true;\n\n const matched = evaluateUrlRule(url, urlRule);\n return matched ? true : undefined;\n }\n\n case \"block\": {\n // Always test block rules (unless already matched to block)\n // because they'd prevail over matched allow rules.\n const matched = evaluateUrlRule(url, urlRule);\n return matched ? false : acc;\n }\n }\n }, undefined);\n};\n\nexport const predicateUrlPatterns = (\n url: URL,\n urlPatterns: KnockGuideActivationUrlPattern[],\n) => {\n return urlPatterns.reduce<boolean | undefined>((acc, urlPattern) => {\n // Any matched block rule prevails so no need to evaluate further\n // as soon as there is one.\n if (acc === false) return false;\n\n // At this point we either have a matched allow rule (acc is true),\n // or no matched rule found yet (acc is undefined).\n\n switch (urlPattern.directive) {\n case \"allow\": {\n // No need to evaluate more allow rules once we matched one\n // since any matched allowed rule means allow.\n if (acc === true) return true;\n\n const matched = urlPattern.pattern.test(url);\n return matched ? true : undefined;\n }\n\n case \"block\": {\n // Always test block rules (unless already matched to block)\n // because they'd prevail over matched allow rules.\n const matched = urlPattern.pattern.test(url);\n return matched ? false : acc;\n }\n }\n }, undefined);\n};\n"],"names":["SelectionResult","__publicField","formatGroupStage","stage","formatState","state","formatFilters","filters","x","byKey","items","acc","item","sortGuides","guides","a","b","DEFAULT_GROUP_KEY","MOCK_DEFAULT_GROUP_KEY","mockDefaultGroup","entries","now","g","findDefaultGroup","guideGroups","group","checkStateIfThrottled","defaultGroup","throttleWindowStartedAt","checkTimeIfThrottled","throttleWindowStartedAtTs","windowDurationInSeconds","throttleWindowStartDate","throttleWindowEndInMilliseconds","newUrl","location","evaluateUrlRule","url","urlRule","predicateUrlRules","urlRules","predicateUrlPatterns","urlPatterns","urlPattern"],"mappings":"oPAcO,MAAMA,UAAoD,GAAU,CAGzE,aAAc,CACN,MAAA,EAHRC,EAAA,gBAGQ,CAEV,CAEa,MAAAC,EAAoBC,GACxB,UAAUA,EAAM,MAAM,cAAcA,EAAM,QAAQ,GAG9CC,EAAeC,GACnB,OAAOA,EAAM,QAAQ,GAGjBC,EAAgB,CAACC,EAA8B,KACnD,CACLA,EAAQ,KAAO,OAAOA,EAAQ,GAAG,GACjCA,EAAQ,MAAQ,QAAQA,EAAQ,IAAI,EAAA,EAEnC,OAAQC,GAAMA,CAAC,EACf,KAAK,IAAI,EAGDC,EAAoCC,GACxCA,EAAM,OAAO,CAACC,EAAKC,KAAU,CAAE,GAAGD,EAAK,CAACC,EAAK,GAAG,EAAGA,CAAK,GAAI,CAAA,CAAE,EAGjEC,EAAmCC,GAChC,CAAC,GAAGA,CAAM,EAAE,KACjB,CAACC,EAAGC,IACF,IAAI,KAAKD,EAAE,WAAW,EAAE,QAAA,EAAY,IAAI,KAAKC,EAAE,WAAW,EAAE,QAAQ,CACxE,EAIWC,EAAoB,UAG3BC,EAAyB,WAIlBC,EAAmB,CAACC,EAAuB,KAAO,CACvD,MAAAC,MAAU,KAET,MAAA,CACL,WAAY,aACZ,IAAKH,EACL,iBAAkBL,EAAWO,CAAO,EAAE,IAAKE,GAAMA,EAAE,GAAG,EACtD,iBAAkB,KAClB,YAAaD,EAAI,YAAY,EAC7B,WAAYA,EAAI,YAAY,CAC9B,CACF,EAEaE,EAAoBC,GAC/BA,EAAY,KACTC,GACCA,EAAM,MAAQR,GAAqBQ,EAAM,MAAQP,CACrD,EAEWQ,EAAyBrB,GAAsB,CACpD,MAAAsB,EAA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,EAAW,QAAQ,KAAKN,CAAG,EAC1B,GAAQ1B,CAC3B,GAED,MAAS"}
package/dist/esm/api.mjs CHANGED
@@ -56,7 +56,7 @@ class k {
56
56
  return i.isNetworkError(e) ? !0 : e.response ? e.response.status >= 500 && e.response.status <= 599 || e.response.status === 429 : !1;
57
57
  }
58
58
  getKnockClientHeader() {
59
- return "Knock/ClientJS 0.19.4";
59
+ return "Knock/ClientJS 0.20.1";
60
60
  }
61
61
  }
62
62
  export {