@mrrocket/sdk 0.29.1 → 0.29.2
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 +7 -0
- package/dist/browser/mrrocket-preview.js +1 -1
- package/dist/browser/mrrocket.js +1 -1
- package/dist/core.d.ts +1 -1
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/preview.js +11 -1
- package/dist/preview.js.map +1 -1
- package/dist/react-native/index.d.cts +1 -1
- package/dist/react-native/index.d.ts +1 -1
- package/dist/react-native/index.js +1 -1
- package/dist/react-native/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this package. It follows semantic versioning; before 1.0 a minor version may change an API.
|
|
4
4
|
|
|
5
|
+
## 0.29.2
|
|
6
|
+
|
|
7
|
+
Preview mode only. Web and script tag; React Native is unchanged.
|
|
8
|
+
|
|
9
|
+
- **The most used look, not the first:** a rewrite's new elements now take, per kind, the class the page uses most often. 0.29.1 took the first one it met, so where a note box came first (a grey "prices change" paragraph) every new paragraph showed as a grey box.
|
|
10
|
+
- Version reported in event batches: `0.29.2`.
|
|
11
|
+
|
|
5
12
|
## 0.29.1
|
|
6
13
|
|
|
7
14
|
Preview mode only. Web and script tag; React Native is unchanged.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(){'use strict';var N="mrr_edit",U="data-mrr-preview",k="data-mrr-preview-missed",P="mrr-preview-ready";var K=(t,e)=>{var l,g,b,h,x;let n=t!=null?t:{project:"",experiments:[]},o=((l=e.experiments)!=null?l:[]).filter(m=>m&&typeof m.key=="string"&&Array.isArray(m.variants)),a=new Set(o.map(m=>m.key)),{redirects:i,...d}=n;return {config:{...d,...(g=e.config)!=null?g:{},experiments:[...n.experiments.filter(m=>!a.has(m.key)),...o],...n.texts||e.texts?{texts:{...(b=n.texts)!=null?b:{},...(h=e.texts)!=null?h:{}}}:{}},force:{...(x=e.force)!=null?x:{}}}};var H=async(t,e,n,o=fetch)=>{let a=await o(`${t}/api/sdk/preview?token=${encodeURIComponent(e)}`),i=a.ok?await a.json().catch(()=>null):null;return i&&typeof i=="object"?{payload:i,...K(n,i)}:null},f=t=>(t!=null?t:"").replace(/\s+/g," ").trim(),B="script,style,noscript,svg,template,iframe,textarea,input,select,option,[data-mrr-bar]",z="h1,h2,h3,h4,h5,h6,p,li,a,button,blockquote,figcaption,label,span,td,th,dt,dd,summary,strong,em,b,i,small,div",R="data-mrr-wrap",A=t=>{let e=t.children.length===1?t.children[0]:null;return e&&e.getAttribute(R)!==null&&f(e.textContent)===f(t.textContent)?e:null},j=t=>{var e;return t.getAttribute("data-ck-text")||((e=A(t))==null?void 0:e.getAttribute("data-ck-text"))||void 0},X=t=>{if(!f(t.textContent))return false;if(A(t))return true;for(let e of Array.from(t.childNodes))if(e.nodeType!==3&&!(e.nodeType===1&&e.tagName.toLowerCase()==="br"))return false;return true},q=t=>{let e=[],n=t;for(;n;){let o=n.tagName.toLowerCase();if(o==="body"||o==="html"){e.unshift("body");break}if(n.id&&/^[A-Za-z][\w-]*$/.test(n.id)){e.unshift(`${o}#${n.id}`);break}let a=n.parentElement,i=a?Array.from(a.children).filter(d=>d.tagName===n.tagName):[n];e.unshift(i.length>1?`${o}:nth-of-type(${i.indexOf(n)+1})`:o),n=a;}return e.join(" > ")},Y=t=>{var a,i,d;let e=t.querySelector("[data-mrr-body]");if(e)return e;let n=new Map;for(let l of Array.from(t.querySelectorAll("p"))){let g=f(l.textContent).length;g<40||!l.parentElement||l.closest("header, footer, nav, aside")||n.set(l.parentElement,((a=n.get(l.parentElement))!=null?a:0)+g);}let o=null;for(let[l,g]of n)(!o||g>((i=n.get(o))!=null?i:0))&&(o=l);return (d=o!=null?o:t.querySelector("article"))!=null?d:t.querySelector("main")},_=t=>Array.from(t.children).flatMap(e=>[e,..._(e)]),J=(t,e)=>{var a;let n=new Map,o=i=>{var d;if(i)for(let l of _(i)){if(n.has(l.tagName)||l.closest("header, footer, nav, aside, [data-mrr-bar]"))continue;let g=(d=l.getAttribute("class"))==null?void 0:d.trim();g&&n.set(l.tagName,g);}};return o(e),o((a=t.querySelector("main"))!=null?a:t.querySelector("article")),n},Q=(t,e)=>{if(e.size)for(let n of _(t)){let o=e.get(n.tagName);o&&n.getAttribute("class")===null&&n.setAttribute("class",o);}},Z=(t,e)=>{if(e.op==="set"){let n=null;try{n=t.querySelector(e.selector);}catch(a){return `${e.selector} (not a selector)`}if(!n)return `${e.selector} (not on the page)`;let o=f(n.textContent);return e.from!==void 0&&o!==f(e.from)&&o!==f(e.text)?`${e.selector} (reads something else now)`:(n.textContent=e.text,n.setAttribute("data-mrr-changed",""),null)}if(e.op==="body"){let n=Y(t);if(!n)return "the page's text (no text block found)";let o=J(t,n);return n.innerHTML=e.html,Q(n,o),n.setAttribute("data-mrr-changed",""),null}if(e.title&&(t.title=e.title),e.description!==void 0){let n=t.querySelector('meta[name="description"]');!n&&t.head&&(n=t.createElement("meta"),n.setAttribute("name","description"),t.head.appendChild(n)),n==null||n.setAttribute("content",e.description);}return null},G=(t,e)=>{var o,a;let n=[];for(let i of (o=e.changed)!=null?o:[]){let d=Array.from(t.querySelectorAll("[data-ck-text]")).filter(l=>l.getAttribute("data-ck-text")===i);d.length||n.push(`${i} (the page does not mark this text)`);for(let l of d)(l.getAttribute(R)!==null&&l.parentElement?l.parentElement:l).setAttribute("data-mrr-changed","");}for(let i of (a=e.ops)!=null?a:[]){let d=Z(t,i);d&&n.push(d);}return n},tt=(t,e,n=[])=>{let o=t.documentElement,a=n.slice(0,20).map(d=>d.slice(0,200));if(o.setAttribute(U,e),a.length?o.setAttribute(k,JSON.stringify(a)):o.removeAttribute(k),!t.body)return;let i=t.querySelector("[data-mrr-preview-status]");i||(i=t.createElement("div"),i.setAttribute("data-mrr-preview-status",""),i.setAttribute("role","status"),i.setAttribute("style","position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none"),t.body.appendChild(i)),i.textContent=a.length?`${P} missed: ${a.join(" | ")}`:P;},et=t=>Array.from(t.querySelectorAll(z)).filter(e=>!e.closest(B)&&e.getAttribute(R)===null&&X(e)),nt="[data-mrr-bar]{position:fixed;top:0;left:0;right:0;z-index:2147483647;display:flex;align-items:center;gap:12px;height:44px;padding:0 12px;background:#fff;color:#1d2939;border-bottom:1px solid #e4e7ec;font:500 13px/1 Inter,system-ui,-apple-system,sans-serif;box-sizing:border-box}[data-mrr-bar] b{font-weight:600}[data-mrr-bar] span[data-mrr-note]{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#667085}[data-mrr-bar] button{all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 10px;border-radius:6px;font:600 13px/28px Inter,system-ui,sans-serif;color:#344054;box-shadow:inset 0 0 0 1px #d0d5dd;background:#fff}[data-mrr-bar] button[data-mrr-save]{color:#fff;background:#3f76ff;box-shadow:none}[data-mrr-bar] button[disabled]{opacity:.5;cursor:default}[data-mrr-bar] button:focus-visible{outline:2px solid #3f76ff;outline-offset:2px}html[data-mrr-editing]{scroll-padding-top:52px}html[data-mrr-editing] body{margin-top:44px!important}[data-mrr-edit]{cursor:text;outline:1px dashed transparent;outline-offset:2px;border-radius:2px}[data-mrr-edit]:hover{outline-color:#98a2b3}[data-mrr-edit][data-mrr-changed]{outline:1px solid #3f76ff}[data-mrr-edit]:focus{outline:2px solid #3f76ff}[data-mrr-edit][data-mrr-edited]{background:rgba(63,118,255,.08)}",rt=t=>{var n;if(!t.ok)return t.error||"Could not save. Open the page from MRRocket again.";let e=[];return t.saved&&e.push(`${t.saved} saved`),t.handed&&e.push(`${t.handed} handed to the agent`),(n=t.missed)!=null&&n.length&&e.push(`${t.missed.length} not saved (${t.missed[0].reason})`),e.length?`${e.join(" \xB7 ")}. The request in MRRocket shows the new version.`:"Nothing changed."},ot=(t,e,n)=>{var V,L,D;let o=t.documentElement;o.setAttribute("data-mrr-editing","");let a=t.createElement("style");a.setAttribute("data-mrr-bar-style",""),a.textContent=nt,((V=t.head)!=null?V:o).appendChild(a);let i=t.createElement("div");i.setAttribute("data-mrr-bar",""),i.setAttribute("role","toolbar"),i.setAttribute("aria-label","MRRocket page editor");let d=t.createElement("b");d.textContent="MRRocket";let l=t.createElement("span");l.setAttribute("data-mrr-note",""),l.setAttribute("aria-live","polite");let g=`Editing ${[e.title,e.version].filter(Boolean).join(" \xB7 ")||"this page"}. Click any text to change it.`;l.textContent=g;let b=t.createElement("button");b.setAttribute("type","button"),b.textContent="Cancel";let h=t.createElement("button");h.setAttribute("type","button"),h.setAttribute("data-mrr-save",""),h.textContent="Save",i.appendChild(d),i.appendChild(l),i.appendChild(b),i.appendChild(h),((L=t.body)!=null?L:o).appendChild(i);let x=new Map,m=et(t);for(let r of m)x.set(r,(D=r.textContent)!=null?D:""),r.setAttribute("data-mrr-edit",""),r.setAttribute("contenteditable","plaintext-only"),r.contentEditable!==void 0&&r.contentEditable!=="plaintext-only"&&r.setAttribute("contenteditable","true"),r.setAttribute("spellcheck","true");let w=()=>m.filter(r=>f(r.textContent)!==f(x.get(r))).map(r=>({selector:q(r),...j(r)?{textId:j(r)}:{},from:f(x.get(r)),to:f(r.textContent)})),E=r=>{var s;return !!(r&&((s=r.closest)!=null&&s.call(r,"[data-mrr-bar]")))},v=r=>{E(r.target)||(r.preventDefault(),r.stopPropagation());},S=r=>{var c,u,p,y;let s=r;E(s.target)||(s.key==="Enter"&&(s.preventDefault(),(u=(c=s.target)==null?void 0:c.blur)==null||u.call(c)),s.key==="Escape"&&((y=(p=s.target)==null?void 0:p.blur)==null||y.call(p)),s.stopPropagation());},I=r=>{var p,y,F;let s=r;if(E(s.target))return;s.preventDefault();let c=(y=(p=s.clipboardData)==null?void 0:p.getData("text/plain"))!=null?y:"",u=(F=t.getSelection)==null?void 0:F.call(t);u!=null&&u.rangeCount&&(u.deleteFromDocument(),u.getRangeAt(0).insertNode(t.createTextNode(c.replace(/\s+/g," "))),u.collapseToEnd());},$=r=>{var u,p;let s=(p=(u=r.target)==null?void 0:u.closest)==null?void 0:p.call(u,"[data-mrr-edit]");if(!s)return;f(s.textContent)!==f(x.get(s))?s.setAttribute("data-mrr-edited",""):s.removeAttribute("data-mrr-edited");let c=w().length;l.textContent=c?`${c} ${c===1?"change":"changes"} not saved yet.`:g;},M=r=>{var c,u;let s=(u=(c=r.target)==null?void 0:c.closest)==null?void 0:u.call(c,"[data-mrr-edit]");s&&s.children.length&&!A(s)&&(s.textContent=f(s.textContent));};t.addEventListener("click",v,true),t.addEventListener("submit",v,true),t.addEventListener("keydown",S,true),t.addEventListener("paste",I,true),t.addEventListener("input",$,true),t.addEventListener("blur",M,true);let O=()=>{t.removeEventListener("click",v,true),t.removeEventListener("submit",v,true),t.removeEventListener("keydown",S,true),t.removeEventListener("paste",I,true),t.removeEventListener("input",$,true),t.removeEventListener("blur",M,true);for(let r of m)r.removeAttribute("contenteditable"),r.removeAttribute("data-mrr-edit"),r.removeAttribute("data-mrr-edited"),r.removeAttribute("spellcheck");i.remove(),a.remove(),o.removeAttribute("data-mrr-editing");},C=false,T=async()=>{var s;let r=w();if(!r.length)return {ok:true,saved:0};try{let c=await((s=n.fetch)!=null?s:fetch)(`${n.host}/api/sdk/preview/edit`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:n.token,path:n.path,edits:r})}),u=await c.json().catch(()=>null);return c.ok?u!=null?u:{ok:!1,error:"MRRocket's answer could not be read."}:{ok:!1,error:(u==null?void 0:u.error)||(c.status===401?"This edit link has expired. Open the page from MRRocket again.":`MRRocket answered ${c.status}.`)}}catch(c){return {ok:false,error:"MRRocket could not be reached. Nothing was saved."}}};return h.addEventListener("click",()=>{C||(C=true,h.setAttribute("disabled",""),l.textContent="Saving\u2026",T().then(r=>{var c,u;if(C=false,h.removeAttribute("disabled"),l.textContent=rt(r),!r.ok)return;let s=new Set(((c=r.missed)!=null?c:[]).map(p=>p.selector));for(let p of m)s.has(q(p))||(x.set(p,(u=p.textContent)!=null?u:""),p.removeAttribute("data-mrr-edited"));b.textContent="Done";}));}),b.addEventListener("click",()=>{var r,s;for(let c of m)f(c.textContent)!==f(x.get(c))&&(c.textContent=(r=x.get(c))!=null?r:"");O(),(s=n.leave)==null||s.call(n);}),{edits:w,save:T,stop:O}},it=(t,e,n)=>{let o=G(t,e);return tt(t,"ready",o),{missed:o,editor:n.edit&&e.edit&&!t.querySelector("[data-mrr-bar]")?ot(t,e,n):null}},W=async(t,e,n)=>{let o=await H(t,e,n);if(!o)return null;let a=new URLSearchParams(window.location.search).get(N)==="1";return {config:o.config,force:o.force,show:()=>{it(document,o.payload,{host:t,token:e,edit:a,path:window.location.pathname,leave:()=>window.close()});}}};window.__mrrocketPreview={bootPreview:W};})();
|
|
1
|
+
(function(){'use strict';var N="mrr_edit",U="data-mrr-preview",k="data-mrr-preview-missed",P="mrr-preview-ready";var K=(t,e)=>{var c,x,b,f,m;let n=t!=null?t:{project:"",experiments:[]},o=((c=e.experiments)!=null?c:[]).filter(p=>p&&typeof p.key=="string"&&Array.isArray(p.variants)),a=new Set(o.map(p=>p.key)),{redirects:i,...d}=n;return {config:{...d,...(x=e.config)!=null?x:{},experiments:[...n.experiments.filter(p=>!a.has(p.key)),...o],...n.texts||e.texts?{texts:{...(b=n.texts)!=null?b:{},...(f=e.texts)!=null?f:{}}}:{}},force:{...(m=e.force)!=null?m:{}}}};var H=async(t,e,n,o=fetch)=>{let a=await o(`${t}/api/sdk/preview?token=${encodeURIComponent(e)}`),i=a.ok?await a.json().catch(()=>null):null;return i&&typeof i=="object"?{payload:i,...K(n,i)}:null},h=t=>(t!=null?t:"").replace(/\s+/g," ").trim(),B="script,style,noscript,svg,template,iframe,textarea,input,select,option,[data-mrr-bar]",z="h1,h2,h3,h4,h5,h6,p,li,a,button,blockquote,figcaption,label,span,td,th,dt,dd,summary,strong,em,b,i,small,div",R="data-mrr-wrap",A=t=>{let e=t.children.length===1?t.children[0]:null;return e&&e.getAttribute(R)!==null&&h(e.textContent)===h(t.textContent)?e:null},j=t=>{var e;return t.getAttribute("data-ck-text")||((e=A(t))==null?void 0:e.getAttribute("data-ck-text"))||void 0},X=t=>{if(!h(t.textContent))return false;if(A(t))return true;for(let e of Array.from(t.childNodes))if(e.nodeType!==3&&!(e.nodeType===1&&e.tagName.toLowerCase()==="br"))return false;return true},q=t=>{let e=[],n=t;for(;n;){let o=n.tagName.toLowerCase();if(o==="body"||o==="html"){e.unshift("body");break}if(n.id&&/^[A-Za-z][\w-]*$/.test(n.id)){e.unshift(`${o}#${n.id}`);break}let a=n.parentElement,i=a?Array.from(a.children).filter(d=>d.tagName===n.tagName):[n];e.unshift(i.length>1?`${o}:nth-of-type(${i.indexOf(n)+1})`:o),n=a;}return e.join(" > ")},Y=t=>{var a,i,d;let e=t.querySelector("[data-mrr-body]");if(e)return e;let n=new Map;for(let c of Array.from(t.querySelectorAll("p"))){let x=h(c.textContent).length;x<40||!c.parentElement||c.closest("header, footer, nav, aside")||n.set(c.parentElement,((a=n.get(c.parentElement))!=null?a:0)+x);}let o=null;for(let[c,x]of n)(!o||x>((i=n.get(o))!=null?i:0))&&(o=c);return (d=o!=null?o:t.querySelector("article"))!=null?d:t.querySelector("main")},_=t=>Array.from(t.children).flatMap(e=>[e,..._(e)]),J=(t,e)=>{var a;let n=new Map,o=i=>{var c,x,b;if(!i)return;let d=new Map;for(let f of _(i)){if(n.has(f.tagName)||f.closest("header, footer, nav, aside, [data-mrr-bar]"))continue;let m=(c=f.getAttribute("class"))==null?void 0:c.trim();if(!m)continue;let p=(x=d.get(f.tagName))!=null?x:new Map;p.set(m,((b=p.get(m))!=null?b:0)+1),d.set(f.tagName,p);}for(let[f,m]of d){let p="",v=0;for(let[w,y]of m)y>v&&([p,v]=[w,y]);n.set(f,p);}};return o(e),o((a=t.querySelector("main"))!=null?a:t.querySelector("article")),n},Q=(t,e)=>{if(e.size)for(let n of _(t)){let o=e.get(n.tagName);o&&n.getAttribute("class")===null&&n.setAttribute("class",o);}},Z=(t,e)=>{if(e.op==="set"){let n=null;try{n=t.querySelector(e.selector);}catch(a){return `${e.selector} (not a selector)`}if(!n)return `${e.selector} (not on the page)`;let o=h(n.textContent);return e.from!==void 0&&o!==h(e.from)&&o!==h(e.text)?`${e.selector} (reads something else now)`:(n.textContent=e.text,n.setAttribute("data-mrr-changed",""),null)}if(e.op==="body"){let n=Y(t);if(!n)return "the page's text (no text block found)";let o=J(t,n);return n.innerHTML=e.html,Q(n,o),n.setAttribute("data-mrr-changed",""),null}if(e.title&&(t.title=e.title),e.description!==void 0){let n=t.querySelector('meta[name="description"]');!n&&t.head&&(n=t.createElement("meta"),n.setAttribute("name","description"),t.head.appendChild(n)),n==null||n.setAttribute("content",e.description);}return null},G=(t,e)=>{var o,a;let n=[];for(let i of (o=e.changed)!=null?o:[]){let d=Array.from(t.querySelectorAll("[data-ck-text]")).filter(c=>c.getAttribute("data-ck-text")===i);d.length||n.push(`${i} (the page does not mark this text)`);for(let c of d)(c.getAttribute(R)!==null&&c.parentElement?c.parentElement:c).setAttribute("data-mrr-changed","");}for(let i of (a=e.ops)!=null?a:[]){let d=Z(t,i);d&&n.push(d);}return n},tt=(t,e,n=[])=>{let o=t.documentElement,a=n.slice(0,20).map(d=>d.slice(0,200));if(o.setAttribute(U,e),a.length?o.setAttribute(k,JSON.stringify(a)):o.removeAttribute(k),!t.body)return;let i=t.querySelector("[data-mrr-preview-status]");i||(i=t.createElement("div"),i.setAttribute("data-mrr-preview-status",""),i.setAttribute("role","status"),i.setAttribute("style","position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;opacity:0;pointer-events:none"),t.body.appendChild(i)),i.textContent=a.length?`${P} missed: ${a.join(" | ")}`:P;},et=t=>Array.from(t.querySelectorAll(z)).filter(e=>!e.closest(B)&&e.getAttribute(R)===null&&X(e)),nt="[data-mrr-bar]{position:fixed;top:0;left:0;right:0;z-index:2147483647;display:flex;align-items:center;gap:12px;height:44px;padding:0 12px;background:#fff;color:#1d2939;border-bottom:1px solid #e4e7ec;font:500 13px/1 Inter,system-ui,-apple-system,sans-serif;box-sizing:border-box}[data-mrr-bar] b{font-weight:600}[data-mrr-bar] span[data-mrr-note]{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#667085}[data-mrr-bar] button{all:unset;box-sizing:border-box;cursor:pointer;height:28px;padding:0 10px;border-radius:6px;font:600 13px/28px Inter,system-ui,sans-serif;color:#344054;box-shadow:inset 0 0 0 1px #d0d5dd;background:#fff}[data-mrr-bar] button[data-mrr-save]{color:#fff;background:#3f76ff;box-shadow:none}[data-mrr-bar] button[disabled]{opacity:.5;cursor:default}[data-mrr-bar] button:focus-visible{outline:2px solid #3f76ff;outline-offset:2px}html[data-mrr-editing]{scroll-padding-top:52px}html[data-mrr-editing] body{margin-top:44px!important}[data-mrr-edit]{cursor:text;outline:1px dashed transparent;outline-offset:2px;border-radius:2px}[data-mrr-edit]:hover{outline-color:#98a2b3}[data-mrr-edit][data-mrr-changed]{outline:1px solid #3f76ff}[data-mrr-edit]:focus{outline:2px solid #3f76ff}[data-mrr-edit][data-mrr-edited]{background:rgba(63,118,255,.08)}",rt=t=>{var n;if(!t.ok)return t.error||"Could not save. Open the page from MRRocket again.";let e=[];return t.saved&&e.push(`${t.saved} saved`),t.handed&&e.push(`${t.handed} handed to the agent`),(n=t.missed)!=null&&n.length&&e.push(`${t.missed.length} not saved (${t.missed[0].reason})`),e.length?`${e.join(" \xB7 ")}. The request in MRRocket shows the new version.`:"Nothing changed."},ot=(t,e,n)=>{var V,L,D;let o=t.documentElement;o.setAttribute("data-mrr-editing","");let a=t.createElement("style");a.setAttribute("data-mrr-bar-style",""),a.textContent=nt,((V=t.head)!=null?V:o).appendChild(a);let i=t.createElement("div");i.setAttribute("data-mrr-bar",""),i.setAttribute("role","toolbar"),i.setAttribute("aria-label","MRRocket page editor");let d=t.createElement("b");d.textContent="MRRocket";let c=t.createElement("span");c.setAttribute("data-mrr-note",""),c.setAttribute("aria-live","polite");let x=`Editing ${[e.title,e.version].filter(Boolean).join(" \xB7 ")||"this page"}. Click any text to change it.`;c.textContent=x;let b=t.createElement("button");b.setAttribute("type","button"),b.textContent="Cancel";let f=t.createElement("button");f.setAttribute("type","button"),f.setAttribute("data-mrr-save",""),f.textContent="Save",i.appendChild(d),i.appendChild(c),i.appendChild(b),i.appendChild(f),((L=t.body)!=null?L:o).appendChild(i);let m=new Map,p=et(t);for(let r of p)m.set(r,(D=r.textContent)!=null?D:""),r.setAttribute("data-mrr-edit",""),r.setAttribute("contenteditable","plaintext-only"),r.contentEditable!==void 0&&r.contentEditable!=="plaintext-only"&&r.setAttribute("contenteditable","true"),r.setAttribute("spellcheck","true");let v=()=>p.filter(r=>h(r.textContent)!==h(m.get(r))).map(r=>({selector:q(r),...j(r)?{textId:j(r)}:{},from:h(m.get(r)),to:h(r.textContent)})),w=r=>{var s;return !!(r&&((s=r.closest)!=null&&s.call(r,"[data-mrr-bar]")))},y=r=>{w(r.target)||(r.preventDefault(),r.stopPropagation());},S=r=>{var l,u,g,E;let s=r;w(s.target)||(s.key==="Enter"&&(s.preventDefault(),(u=(l=s.target)==null?void 0:l.blur)==null||u.call(l)),s.key==="Escape"&&((E=(g=s.target)==null?void 0:g.blur)==null||E.call(g)),s.stopPropagation());},I=r=>{var g,E,F;let s=r;if(w(s.target))return;s.preventDefault();let l=(E=(g=s.clipboardData)==null?void 0:g.getData("text/plain"))!=null?E:"",u=(F=t.getSelection)==null?void 0:F.call(t);u!=null&&u.rangeCount&&(u.deleteFromDocument(),u.getRangeAt(0).insertNode(t.createTextNode(l.replace(/\s+/g," "))),u.collapseToEnd());},M=r=>{var u,g;let s=(g=(u=r.target)==null?void 0:u.closest)==null?void 0:g.call(u,"[data-mrr-edit]");if(!s)return;h(s.textContent)!==h(m.get(s))?s.setAttribute("data-mrr-edited",""):s.removeAttribute("data-mrr-edited");let l=v().length;c.textContent=l?`${l} ${l===1?"change":"changes"} not saved yet.`:x;},$=r=>{var l,u;let s=(u=(l=r.target)==null?void 0:l.closest)==null?void 0:u.call(l,"[data-mrr-edit]");s&&s.children.length&&!A(s)&&(s.textContent=h(s.textContent));};t.addEventListener("click",y,true),t.addEventListener("submit",y,true),t.addEventListener("keydown",S,true),t.addEventListener("paste",I,true),t.addEventListener("input",M,true),t.addEventListener("blur",$,true);let O=()=>{t.removeEventListener("click",y,true),t.removeEventListener("submit",y,true),t.removeEventListener("keydown",S,true),t.removeEventListener("paste",I,true),t.removeEventListener("input",M,true),t.removeEventListener("blur",$,true);for(let r of p)r.removeAttribute("contenteditable"),r.removeAttribute("data-mrr-edit"),r.removeAttribute("data-mrr-edited"),r.removeAttribute("spellcheck");i.remove(),a.remove(),o.removeAttribute("data-mrr-editing");},C=false,T=async()=>{var s;let r=v();if(!r.length)return {ok:true,saved:0};try{let l=await((s=n.fetch)!=null?s:fetch)(`${n.host}/api/sdk/preview/edit`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({token:n.token,path:n.path,edits:r})}),u=await l.json().catch(()=>null);return l.ok?u!=null?u:{ok:!1,error:"MRRocket's answer could not be read."}:{ok:!1,error:(u==null?void 0:u.error)||(l.status===401?"This edit link has expired. Open the page from MRRocket again.":`MRRocket answered ${l.status}.`)}}catch(l){return {ok:false,error:"MRRocket could not be reached. Nothing was saved."}}};return f.addEventListener("click",()=>{C||(C=true,f.setAttribute("disabled",""),c.textContent="Saving\u2026",T().then(r=>{var l,u;if(C=false,f.removeAttribute("disabled"),c.textContent=rt(r),!r.ok)return;let s=new Set(((l=r.missed)!=null?l:[]).map(g=>g.selector));for(let g of p)s.has(q(g))||(m.set(g,(u=g.textContent)!=null?u:""),g.removeAttribute("data-mrr-edited"));b.textContent="Done";}));}),b.addEventListener("click",()=>{var r,s;for(let l of p)h(l.textContent)!==h(m.get(l))&&(l.textContent=(r=m.get(l))!=null?r:"");O(),(s=n.leave)==null||s.call(n);}),{edits:v,save:T,stop:O}},it=(t,e,n)=>{let o=G(t,e);return tt(t,"ready",o),{missed:o,editor:n.edit&&e.edit&&!t.querySelector("[data-mrr-bar]")?ot(t,e,n):null}},W=async(t,e,n)=>{let o=await H(t,e,n);if(!o)return null;let a=new URLSearchParams(window.location.search).get(N)==="1";return {config:o.config,force:o.force,show:()=>{it(document,o.payload,{host:t,token:e,edit:a,path:window.location.pathname,leave:()=>window.close()});}}};window.__mrrocketPreview={bootPreview:W};})();
|
package/dist/browser/mrrocket.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){'use strict';var or=Object.defineProperty;var sr=(e,n,r)=>n in e?or(e,n,{enumerable:true,configurable:true,writable:true,value:r}):e[n]=r;var Le=(e,n,r)=>sr(e,typeof n!="symbol"?n+"":n,r);var nn=e=>{let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?n+=1:i<2048?n+=2:i>=55296&&i<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(n+=4,r++):n+=3;}return n},ir=(e,n,r,i)=>{let a=`{"key":${JSON.stringify(e)},${i?`"userHash":${JSON.stringify(i)},`:""}"sdk":${JSON.stringify(r)},"events":[`,d=nn(a)+2,m=[],C=[],E=[],x=d,w=()=>{C.length&&m.push({body:`${a}${C.join(",")}]}`,events:E}),C=[],E=[],x=d;};for(let v of n){let h=JSON.stringify(v),S=nn(h)+1;d+S>6e4||((C.length===100||x+S>6e4)&&w(),C.push(h),E.push(v),x+=S);}return w(),m},rn=(e,n,r,i)=>ir(e,n,r,i).map(a=>a.body);var Ye=class{constructor(n=1e3,r=30,i=3){Le(this,"windowMs",n);Le(this,"radius",r);Le(this,"count",i);Le(this,"clicks",[]);Le(this,"fired",false);}push(n,r,i){let a=this.clicks.filter(d=>i-d.t<=this.windowMs&&Math.hypot(d.x-n,d.y-r)<=this.radius);return a.length!==this.clicks.length&&(this.fired=false),this.clicks=[...a,{x:n,y:r,t:i}],this.clicks.length>=this.count&&!this.fired?(this.fired=true,true):false}};var ar='a[href],button,input,select,textarea,label,summary,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="switch"],[onclick],[data-ck-goal]',cr="[data-ck-mask]",dr="[data-ck-block]",on=/\d{4,}|^[a-z]{1,3}-[a-z0-9]{5,}$|^_|__|css-|^sc-|^jsx-/i,lr=e=>{let n=e.tagName.toLowerCase();if(e.id&&!on.test(e.id)&&e.id.length<=40)return `${n}#${e.id}`;let r=typeof e.className=="string"?e.className.split(/\s+/).filter(d=>d&&!on.test(d)&&d.length<=30&&!d.includes(":")):[],i=r.length?`${n}.${r.slice(0,2).join(".")}`:n,a=e.parentElement?[...e.parentElement.children].filter(d=>d.tagName===e.tagName):[];return a.length>1?`${i}:nth-of-type(${a.indexOf(e)+1})`:i},ur=e=>{let n=[],r=e;for(;r&&n.length<3&&r.tagName&&r.tagName!=="BODY"&&r.tagName!=="HTML";){let i=lr(r);if(n.unshift(i),i.includes("#"))break;r=r.parentElement;}return n.join(" > ").slice(0,160)},ot=e=>(e!=null?e:"").replace(/\s+/g," ").trim().slice(0,40),fr=e=>{var r,i,a,d,m;if(e.closest(`${cr},${dr}`))return "";let n=e.tagName.toLowerCase();if(n==="input"){let C=((r=e.getAttribute("type"))!=null?r:"text").toLowerCase();return ot(C==="submit"||C==="button"?(i=e.getAttribute("aria-label"))!=null?i:e.value:e.getAttribute("aria-label"))}return ot(n==="select"||n==="textarea"?e.getAttribute("aria-label"):(m=(d=(a=e.getAttribute("aria-label"))!=null?a:e.getAttribute("title"))!=null?d:e.innerText)!=null?m:e.textContent)},sn=e=>{var d,m;let n=e.target instanceof Element?e.target:null;if(!n)return null;let r=n.closest(ar),i=r!=null?r:n,a=document.documentElement;return {x:Math.round(e.clientX),y:Math.round(e.clientY+window.scrollY),vw:window.innerWidth,vh:window.innerHeight,docH:Math.max(a.scrollHeight,(m=(d=document.body)==null?void 0:d.scrollHeight)!=null?m:0),selector:ur(i),label:r?fr(r):"",interactive:!!r}},an=()=>{var r,i;let e=document.documentElement,n=Math.max(e.scrollHeight,(i=(r=document.body)==null?void 0:r.scrollHeight)!=null?i:0);return n?Math.min(100,Math.round((window.scrollY+window.innerHeight)/n*100)):0};var it="0.29.
|
|
1
|
+
(function(){'use strict';var or=Object.defineProperty;var sr=(e,n,r)=>n in e?or(e,n,{enumerable:true,configurable:true,writable:true,value:r}):e[n]=r;var Le=(e,n,r)=>sr(e,typeof n!="symbol"?n+"":n,r);var nn=e=>{let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?n+=1:i<2048?n+=2:i>=55296&&i<=56319&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320?(n+=4,r++):n+=3;}return n},ir=(e,n,r,i)=>{let a=`{"key":${JSON.stringify(e)},${i?`"userHash":${JSON.stringify(i)},`:""}"sdk":${JSON.stringify(r)},"events":[`,d=nn(a)+2,m=[],C=[],E=[],x=d,w=()=>{C.length&&m.push({body:`${a}${C.join(",")}]}`,events:E}),C=[],E=[],x=d;};for(let v of n){let h=JSON.stringify(v),S=nn(h)+1;d+S>6e4||((C.length===100||x+S>6e4)&&w(),C.push(h),E.push(v),x+=S);}return w(),m},rn=(e,n,r,i)=>ir(e,n,r,i).map(a=>a.body);var Ye=class{constructor(n=1e3,r=30,i=3){Le(this,"windowMs",n);Le(this,"radius",r);Le(this,"count",i);Le(this,"clicks",[]);Le(this,"fired",false);}push(n,r,i){let a=this.clicks.filter(d=>i-d.t<=this.windowMs&&Math.hypot(d.x-n,d.y-r)<=this.radius);return a.length!==this.clicks.length&&(this.fired=false),this.clicks=[...a,{x:n,y:r,t:i}],this.clicks.length>=this.count&&!this.fired?(this.fired=true,true):false}};var ar='a[href],button,input,select,textarea,label,summary,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="switch"],[onclick],[data-ck-goal]',cr="[data-ck-mask]",dr="[data-ck-block]",on=/\d{4,}|^[a-z]{1,3}-[a-z0-9]{5,}$|^_|__|css-|^sc-|^jsx-/i,lr=e=>{let n=e.tagName.toLowerCase();if(e.id&&!on.test(e.id)&&e.id.length<=40)return `${n}#${e.id}`;let r=typeof e.className=="string"?e.className.split(/\s+/).filter(d=>d&&!on.test(d)&&d.length<=30&&!d.includes(":")):[],i=r.length?`${n}.${r.slice(0,2).join(".")}`:n,a=e.parentElement?[...e.parentElement.children].filter(d=>d.tagName===e.tagName):[];return a.length>1?`${i}:nth-of-type(${a.indexOf(e)+1})`:i},ur=e=>{let n=[],r=e;for(;r&&n.length<3&&r.tagName&&r.tagName!=="BODY"&&r.tagName!=="HTML";){let i=lr(r);if(n.unshift(i),i.includes("#"))break;r=r.parentElement;}return n.join(" > ").slice(0,160)},ot=e=>(e!=null?e:"").replace(/\s+/g," ").trim().slice(0,40),fr=e=>{var r,i,a,d,m;if(e.closest(`${cr},${dr}`))return "";let n=e.tagName.toLowerCase();if(n==="input"){let C=((r=e.getAttribute("type"))!=null?r:"text").toLowerCase();return ot(C==="submit"||C==="button"?(i=e.getAttribute("aria-label"))!=null?i:e.value:e.getAttribute("aria-label"))}return ot(n==="select"||n==="textarea"?e.getAttribute("aria-label"):(m=(d=(a=e.getAttribute("aria-label"))!=null?a:e.getAttribute("title"))!=null?d:e.innerText)!=null?m:e.textContent)},sn=e=>{var d,m;let n=e.target instanceof Element?e.target:null;if(!n)return null;let r=n.closest(ar),i=r!=null?r:n,a=document.documentElement;return {x:Math.round(e.clientX),y:Math.round(e.clientY+window.scrollY),vw:window.innerWidth,vh:window.innerHeight,docH:Math.max(a.scrollHeight,(m=(d=document.body)==null?void 0:d.scrollHeight)!=null?m:0),selector:ur(i),label:r?fr(r):"",interactive:!!r}},an=()=>{var r,i;let e=document.documentElement,n=Math.max(e.scrollHeight,(i=(r=document.body)==null?void 0:r.scrollHeight)!=null?i:0);return n?Math.min(100,Math.round((window.scrollY+window.innerHeight)/n*100)):0};var it="0.29.2",pr=(e,n)=>{let r=n.trim().toLowerCase();for(let[i,a]of Object.entries(e))if(i.toLowerCase()===r)return a},gr=(e,n)=>{let r=e.trim().toLowerCase(),i=n.trim().toLowerCase();return i.startsWith("@")?r.endsWith(i):r===i},ln=(e,n)=>{if(e.op==="in cohort")return false;let r=pr(n,e.property),i=r==null?"":String(r);if(e.op==="\u2265"){let d=Number(i),m=Number(e.values[0]);return i!==""&&Number.isFinite(d)&&Number.isFinite(m)&&d>=m}let a=i!==""&&e.values.some(d=>gr(i,d));return e.op==="is"||e.op==="in"?a:!a},un=(e,n,r={})=>{var C;if(!e.on)return false;let i={id:n,...r},a=e.sets.length?e.sets.find(E=>E.conditions.every(x=>ln(x,i))):{rollout:100};if(!a||cn(`${e.key}:rollout:${n}`)*100>=a.rollout)return false;if(!((C=e.variants)!=null&&C.length))return true;let d=cn(`${e.key}:variant:${n}`)*100,m=0;for(let E of e.variants)if(m+=E.split,d<m)return E.key;return e.variants[e.variants.length-1].key},fn=(e,n,r,i={})=>{var d;let a=(d=n==null?void 0:n.flags)==null?void 0:d.find(m=>m.key===e);return a?un(a,r,i):false},mr=e=>e<=0?"control":String.fromCharCode(96+Math.min(e,26)),pn=(e,n,r,i={})=>{var C,E;let a=(C=n==null?void 0:n.flags)==null?void 0:C.find(x=>x.key===e);if(!(a!=null&&a.experiment)||!a.on)return null;let d={id:r,...i};if(a.sets.length&&!a.sets.some(x=>x.conditions.every(w=>ln(w,d))))return null;let m=un(a,r,i);if((E=a.variants)!=null&&E.length){let x=typeof m=="string"?a.variants.findIndex(w=>w.key===m):-1;return x<0?null:{experiment:a.experiment,variant:mr(x)}}return {experiment:a.experiment,variant:m===true?"a":"control"}},gn="$consent_off",wr=["utm_source","utm_medium","utm_campaign","utm_term","utm_content"],mn="ck_preview",wn="ck_embed",hn="mrr_preview";var It="data-mrr-preview";var Ie="ck_id";var Ue="ck_sid";var hr=e=>{var r;let n={};for(let i of wr){let a=(r=e(i))==null?void 0:r.trim();a&&(n[i]=a.slice(0,150));}return n},kn=e=>{let n=new URLSearchParams(e);return hr(r=>n.get(r))};var kr=e=>{let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return (n>>>0)/4294967296},cn=e=>{let n=2166136261;for(let r=0;r<e.length;r++)n^=e.charCodeAt(r),n=Math.imul(n,16777619);return n^=n>>>16,n=Math.imul(n,2246822507),n^=n>>>13,n=Math.imul(n,3266489909),n^=n>>>16,(n>>>0)/4294967296},yr=e=>typeof e.weight=="number"&&e.weight>0?e.weight:0,dn=(e,n)=>{var m,C;let r=(C=(m=e.variants[0])==null?void 0:m.id)!=null?C:"control";if(e.winner)return e.winner;if(e.status!=="running")return r;let i=kr(`${e.key}:${n}`),a=0,d;for(let E of e.variants){let x=yr(E);if(x&&(a+=x,d=E.id,i<a))return E.id}return d!=null?d:r},br=(e,n,r)=>{if(!r||e.winner||e.status!=="running")return dn(e,n);let i=`${e.key}
|
|
2
2
|
${n}`,a=r.get(i);if(a!==void 0&&e.variants.some(m=>m.id===a))return a;let d=dn(e,n);return r.set(i,d),d};var yn=e=>{let n=Array.isArray(e)?e[0]:e;if(!n)return {};let r={};for(let i of n.split(",")){let[a,d]=i.split(":");a&&d&&(r[a.trim()]=d.trim());}return r};var Xe=e=>e.status==="running"&&!e.winner;var bn=e=>{var r,i;let n=new Map;for(let a of (r=e==null?void 0:e.experiments)!=null?r:[])if(Xe(a))for(let d of a.variants)for(let m of Object.keys((i=d.changes)!=null?i:{}))n.has(m)||n.set(m,a.key);return n},xn=(e,n)=>{var i;let r=bn(e).get(n);return ((i=e==null?void 0:e.experiments)!=null?i:[]).filter(a=>a.variants.some(d=>d.changes&&n in d.changes)&&(!Xe(a)||a.key===r)).map(a=>a.key)},at=(e,n,r,i,a)=>{var m,C;if(i[e])return i[e];let d=n==null?void 0:n.experiments.find(E=>E.key===e);return d?r===null&&Xe(d)?(C=(m=d.variants[0])==null?void 0:m.id)!=null?C:"control":br(d,r!=null?r:"",a):"control"},vn=(e,n,r,i)=>{var E,x;let a={...(E=e==null?void 0:e.texts)!=null?E:{}},d=(x=e==null?void 0:e.experiments)!=null?x:[],m=bn(e),C=w=>{var h,S,M,T;let v=at(w.key,e,n,r,i);return v===((S=(h=w.variants[0])==null?void 0:h.id)!=null?S:"control")?{}:(T=(M=w.variants.find(H=>H.id===v))==null?void 0:M.changes)!=null?T:{}};for(let w of d)!Xe(w)&&!r[w.key]&&Object.assign(a,C(w));for(let w of d)if(!(!Xe(w)||r[w.key]))for(let[v,h]of Object.entries(C(w)))m.get(v)===w.key&&(a[v]=h);for(let w of d)r[w.key]&&Object.assign(a,C(w));return a},Je="ck_x",st=e=>e.replace(/\/+$/,"")||"/",Cn=(e,n,r,i={},a)=>{var E,x;if(!e)return null;let d;try{d=new URL(n);}catch(w){return null}if(d.searchParams.has(Je))return null;let m=st(d.pathname),C=(w,v)=>{let h;try{h=new URL(w,d);}catch(S){return}if(!(!/^https?:$/.test(h.protocol)||h.origin===d.origin&&st(h.pathname)===m))return d.searchParams.forEach((S,M)=>{h.searchParams.has(M)||h.searchParams.set(M,S);}),v&&h.searchParams.set(Je,v),h.hash||(h.hash=d.hash),h.href};for(let w of (E=e.redirects)!=null?E:[]){let v=w.from&&st(w.from)===m?C(w.to):void 0;if(v)return {to:v}}for(let w of e.experiments){if(!w.path||st(w.path)!==m)continue;let v=w.status==="running"&&!w.winner;if(v&&r===null&&!i[w.key])return null;let h=at(w.key,e,r,i,a),S=(x=w.variants.find(T=>T.id===h))==null?void 0:x.url,M=S?C(S,v?`${w.key}:${h}`:void 0):void 0;return v?{to:M,experiment:w.key,variant:h}:M?{to:M}:null}return null},Rn=(e,n)=>{let[r,i]=(n!=null?n:"").split(":"),a=e==null?void 0:e.experiments.find(d=>d.key===r);return a&&a.variants.some(d=>d.id===i)?{experiment:r,variant:i}:null};var Ft=()=>typeof crypto!="undefined"&&"randomUUID"in crypto?crypto.randomUUID():`ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;var xr="401: sign the user id on your server with userHash(id) from @mrrocket/sdk/next/server and pass identify(id, props, { hash }).",Ve=(e,n=r=>console.warn(r))=>{let r=globalThis;e!==401||r.__mrrocketUnsigned||(r.__mrrocketUnsigned=true,n(`[MRRocket] ${xr}`));},En=(e,n,r,i=a=>console.warn(a))=>{let a=typeof r=="string"?r.trim().toLowerCase():"";return /^[0-9a-f]{64}$/.test(a)?{id:n,hash:a}:(a&&i("[MRRocket] identify: that hash is no userHash(id); not sent."),e&&e.id===n?e:null)},On=(e,n)=>e&&n&&e.id===n?e.hash:void 0,_n=(e,n)=>e&&n.some(r=>r===e.id)&&n.every(r=>!r||r===e.id)?e.hash:void 0;var vr=8*1024,Cr=20,Rr=20,Er=2e3,ze=(e,n)=>e.length>n?`${e.slice(0,n-1)}\u2026`:e,Or=e=>{var n;if(e instanceof Error)return {type:e.name||"Error",message:ze(e.message||String(e),1e3),stack:e.stack?ze(e.stack,vr):void 0};if(typeof e=="string")return {type:"Error",message:ze(e,1e3)};try{return {type:"Error",message:ze((n=JSON.stringify(e))!=null?n:String(e),1e3)}}catch(r){return {type:"Error",message:String(e)}}},Sn=e=>{let n=[],r=[],i=new Set,a=0,d=`${e.host}/api/sdk/errors`,m=(h=false)=>{for(;n.length;){let S=n.splice(0,4),M=e.context(),T=M.distinctId&&M.userHash?{id:M.distinctId,hash:M.userHash}:null,H=_n(T,S.map(N=>N.distinctId)),J=JSON.stringify({key:e.apiKey,...H?{userHash:H}:{},errors:S});h&&typeof navigator!="undefined"&&"sendBeacon"in navigator&&navigator.sendBeacon(d,J)||fetch(d,{method:"POST",headers:{"content-type":"application/json"},body:J,keepalive:true}).then(N=>{N.status===401?Ve(401):!N.ok&&N.status!==429&&e.warn(`Error reports were rejected with ${N.status}. Check the public key and NEXT_PUBLIC_MRROCKET_HOST.`);}).catch(()=>{});}},C=(h,S="manual")=>{let M=e.context();if(!M.send||a>=Cr)return;let T=Or(h);if(/\/api\/sdk\/errors/.test(T.message))return;let H=`${T.type}:${T.message}`;i.has(H)||(i.add(H),a++,n.push({...T,mechanism:S,handled:S==="manual",url:window.location.href,ts:Date.now(),crumbs:r.slice(),...e.release?{release:e.release}:{},...M.distinctId?{distinctId:M.distinctId}:{},...M.sessionId?{sessionId:M.sessionId}:{}}));},E=h=>{var S;!h.error&&(!h.message||h.message==="Script error.")||C((S=h.error)!=null?S:new Error(h.message),"onerror");},x=h=>{var S;return C((S=h.reason)!=null?S:new Error("Unhandled promise rejection"),"onunhandledrejection")},w=()=>m(true);window.addEventListener("error",E),window.addEventListener("unhandledrejection",x),window.addEventListener("pagehide",w);let v=window.setInterval(()=>m(),Er);return {capture:C,crumb:(h,S)=>{r.push({ts:Date.now(),type:h,message:ze(S,120)}),r.length>Rr&&r.shift();},stop:()=>{window.removeEventListener("error",E),window.removeEventListener("unhandledrejection",x),window.removeEventListener("pagehide",w),window.clearInterval(v),m(true);}}};var Pt=globalThis,In,z=(In=Pt.__mrrocketI18n)!=null?In:Pt.__mrrocketI18n={version:0,onWords:new Set,onLocale:new Set},$t=e=>{for(let n of [...e])try{n();}catch(r){}},Ge=e=>{var n;return ((n=z.words)==null?void 0:n[e])||e};var Fn=(e,n)=>{var i;let r=z.lang===n&&JSON.stringify((i=z.words)!=null?i:{})===JSON.stringify(e!=null?e:{});z.words=e,z.lang=n,!r&&(z.version++,$t(z.onWords));},_r=e=>{let n=e==null?void 0:e.trim().replace(/_/g,"-");if(n)try{return Intl.getCanonicalLocales(n)[0]}catch(r){return r instanceof RangeError?void 0:n}},Mt=e=>{let n=_r(e);n!==z.locale&&(z.locale=n,z.version++,$t(z.onWords),$t(z.onLocale));};var ct=()=>{var e,n;return (n=(e=z.locale)!=null?e:z.device)!=null?n:typeof navigator!="undefined"&&navigator.language||void 0},dt=()=>{let e=ct();return e?`&lang=${encodeURIComponent(e)}`:""};var Pn=e=>(z.onLocale.add(e),()=>{z.onLocale.delete(e);});var Qe="$cancel_flow",j="$onboarding",At="$inapp";var Sr={version:0,question:"",reasons:[],offers:{},get confirm(){return {title:Ge("Cancel your subscription?"),body:Ge("You keep access until the end of the billing period."),button:Ge("Cancel subscription")}},offersFor:"business"},Tt="mrrocket:onboarding",ae=e=>e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,""),$n=new Set(["signed_up","signup","sign_up","registered","account_created","user_signed_up"]),lt=(e,n)=>{let r=ae(e),i=ae(n);return !r||!i?false:r===i||$n.has(r)&&$n.has(i)},Mn=e=>/^(first (launch|visit|open|session|login|sign ?in|app open)|app (opened|launched)|on load|every visit|always)?$/i.test(e.trim());var An=e=>e.trim().startsWith("/");var Ir="Needs tracking code 0.18.0",ie=e=>{var n;return (n=e.when)!=null?n:e.trigger},ut=e=>ae(e)==="from_a_checklist"||ae(e)==="from_your_code"||ae(e)===ae(Ir),Tn="after:",ft=e=>{let n=(e!=null?e:"").trim();return n.toLowerCase().startsWith(Tn)&&n.slice(Tn.length).trim()||null},Fr=e=>{var n;return (n=e.opens)!=null?n:e.startsTour?{kind:"tour",id:e.startsTour}:void 0},Fe="other:",Pr=e=>{var i,a;let n=(i=e==null?void 0:e.min)!=null?i:0,r=(a=e==null?void 0:e.max)!=null?a:10;return Array.from({length:Math.max(0,Math.min(r-n,20)+1)},(d,m)=>n+m)},Nn=(e,n)=>{var r;return !e||n==null?false:e.type==="choice"?e.other&&n.startsWith(Fe)?n.slice(Fe.length).trim().length>0:((r=e.options)!=null?r:[]).some(i=>i.id===n):e.type==="scale"?Pr(e).some(i=>String(i)===n):n.trim().length>0&&n.length<=500},$r=(e,n)=>{var r,i,a;return (e==null?void 0:e.type)!=="choice"?n.trim():e.other&&n.startsWith(Fe)?n.slice(Fe.length).trim():(a=(i=(r=e.options)==null?void 0:r.find(d=>d.id===n))==null?void 0:i.label)!=null?a:n};var Mr=()=>`cf_${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;var gt=e=>{let n=(e!=null?e:"").trim();return /^https?:\/\//i.test(n)||/^\/(?!\/)/.test(n)?n:void 0},Z=e=>{var n;return (n=e.nodes)!=null?n:e.steps},Ar=e=>Math.max(0,e.amount)*(e.unit==="hours"?36e5:864e5),Nt=(e,n)=>{let r=e.trim(),i=(n.split(/[?#]/)[0]||"/").replace(/\/+$/,"")||"/";if(!r)return false;if(r.endsWith("*")){let a=r.slice(0,-1).replace(/\/+$/,"");return !a||i===a||i.startsWith(`${a}/`)}return i===(r.replace(/\/+$/,"")||"/")},Ce=e=>e.flatMap(n=>n.kind==="condition"?[...Ce(n.yes),...Ce(n.no)]:n.kind==="wait"?[]:[n]),Tr=(e,n=Date.now())=>e==null||e===""?NaN:Math.floor((n-new Date(e).getTime())/2630016e3),pt=e=>e==null?void 0:e.trim().toLowerCase(),Nr=({when:e={}},n)=>(e.answer==null||pt(e.answer)===pt(n.answer))&&(e.plan==null||[e.plan].flat().some(r=>pt(r)===pt(n.plan)))&&!(n.months>=e.tenureUnder)&&!(n.months<e.tenureOver)&&(e.tenureUnder==null||n.months>=0)&&(e.tenureOver==null||n.months>=0),Ln=e=>{let n=null,r={...e,track:(t,o)=>{var l,f;let c=o==null?void 0:o.action;if(t===j&&(c==="shown"||c==="started")&&e.expose){let p=(f=(l=n==null?void 0:n.onboarding)==null?void 0:l.find(k=>k.id===(o==null?void 0:o.flow)))==null?void 0:f.experiment;p&&e.expose(p);}e.track(t,o);}},i=null,a=null,d=[],m=false,C=null,E,x=null,w=new Map,v=new Set,h=new Set,S=new Set,M=r.auto!==false,T=new Set,H=()=>{var t,o;return (o=(t=r.now)==null?void 0:t.call(r))!=null?o:Date.now()},J=null,te=null,N=new Map,ne=new Map,De=new Set,ue=null,re=()=>{var t;return (t=n==null?void 0:n.onboarding)!=null?t:[]},Pe=()=>re().filter(t=>t.shownBy!=="code"),q=t=>t?re().find(o=>o.id===t):void 0,B=t=>{let o=w.get(t);return o||w.set(t,o={done:new Set,dismissed:false,answers:new Map,at:new Map,reached:new Map}),o},$e=false,ye=t=>{r.track(j,t),$e=true;},A=(t,o)=>{t.done.add(o),t.at.set(o,H());},Me=t=>{var o,c,l;if((o=t.page)!=null&&o.trim()){let f=(c=r.path)==null?void 0:c.call(r);return f===void 0?false:Nt(t.page,f)}if((l=t.event)!=null&&l.trim()){if(!m)return;for(let f of T)if(lt(t.event,f))return true;return false}return false},fe=(t,o,c,l,f=0,p)=>{var k,O;for(let y=0;y<o.length;y++){let b=o[y];if(b.kind==="wait"){if(c.done.has(b.id)){p=(k=c.at.get(b.id))!=null?k:p;continue}let $=c.reached.get(b.id);if($===void 0){if(!l)return {at:"pending"};$=p!=null?p:H(),c.reached.set(b.id,$),ye({flow:t.id,step:b.id,kind:"wait",action:"shown"});}let F=$+Ar(b);if(H()<F)return {at:"wait",until:F};if(!l)return {at:"pending"};A(c,b.id),ye({flow:t.id,step:b.id,kind:"wait",action:"completed"}),p=F;continue}if(b.kind==="condition"){let $=c.answers.get(b.id);if($===void 0){if(!l)return {at:"pending"};if($=Me(b),$===void 0)return {at:"pending"};c.answers.set(b.id,$),ye({flow:t.id,step:b.id,kind:"condition",action:"answered",answer:$?"yes":"no"});}return fe(t,$?b.yes:b.no,c,l,f,p)}if(!c.done.has(b.id))return {at:"step",step:b,line:o,index:y,before:f};p=(O=c.at.get(b.id))!=null?O:p,f++;}return {at:"end"}},_=t=>{let o=w.get(t.id);return !!o&&(o.dismissed||fe(t,Z(t),o,false).at==="end")},pe=t=>`${Tt}:${t!=null?t:"visitor"}`,He=t=>`${Tt}:events:${t!=null?t:"visitor"}`,We=t=>`${Tt}:answers:${t!=null?t:"visitor"}`,ge=t=>{if(!t.finish||t.finish==="none"||t.shownBy==="code"||De.has(t.id))return;let o=w.get(t.id);!o||o.dismissed||fe(t,Z(t),o,false).at!=="end"||(De.add(t.id),ue={kind:t.finish,key:`${t.id}:${H()}`});},Q=()=>{var c;$e=false;let t=(c=r.storage)==null?void 0:c.call(r);if(!t)return;let o={};for(let[l,f]of w)o[l]={done:[...f.done],...f.dismissed?{dismissed:true}:{},...f.answers.size?{answers:Object.fromEntries([...f.answers].map(([p,k])=>[p,k?"yes":"no"]))}:{},...f.at.size?{at:Object.fromEntries(f.at)}:{},...f.reached.size?{reached:Object.fromEntries(f.reached)}:{}};try{t.set(pe(r.personId()),JSON.stringify(o)),N.size&&t.set(We(r.personId()),JSON.stringify(Object.fromEntries(N))),T.size&&t.set(He(r.personId()),JSON.stringify([...T].slice(-200)));}catch(l){}},me=t=>{var o,c,l,f;for(let[p,k]of Object.entries(t!=null?t:{})){let O=B(p);for(let y of (o=k.done)!=null?o:[])O.done.add(y);k.dismissed&&(O.dismissed=true);for(let[y,b]of Object.entries((c=k.answers)!=null?c:{}))O.answers.has(y)||O.answers.set(y,b==="yes");for(let[y,b]of Object.entries((l=k.at)!=null?l:{}))typeof b=="number"&&!O.at.has(y)&&O.at.set(y,b);for(let[y,b]of Object.entries((f=k.reached)!=null?f:{}))typeof b=="number"&&(!O.reached.has(y)||b<O.reached.get(y))&&O.reached.set(y,b);}},je=t=>{var c;J&&clearTimeout(J),J=null;let o=t-H();o>0&&o<=864e5&&(J=setTimeout(()=>(J=null,P()),o+50),(c=J.unref)==null||c.call(J));},_e=false,U=()=>{var $;_e=false;let t=q(a);if(!t)return null;let o=B(t.id);if(o.dismissed)return null;let c=fe(t,Z(t),o,true);if($e&&Q(),c.at==="wait"&&je(c.until),_e=c.at==="wait"||c.at==="pending",c.at!=="step")return null;let{step:l,line:f,index:p}=c,k=F=>!!F&&F.kind!=="wait"&&F.kind!=="condition";if(l.kind==="checklist"){let F=p;for(;F>0&&k(f[F-1])&&f[F-1].kind==="checklist";)F--;let D=p;for(;D+1<f.length&&k(f[D+1])&&f[D+1].kind==="checklist";)D++;let xe=f.slice(F,D+1).filter(k);for(let ce of xe)!o.done.has(ce.id)&&!h.has(`s:${ce.id}`)&&(h.add(`s:${ce.id}`),r.track(j,{flow:t.id,step:ce.id,kind:"checklist",action:"shown"}));return {type:"checklist",flow:t,items:xe.map(ce=>{let X=Fr(ce),Ee=X&&(X.kind==="tour"||X.kind==="modal")&&X.id!==t.id?q(X.id):void 0,ve=Ee&&Ee.shownBy!=="code"&&Z(Ee).length?Ee:void 0,de=X&&(X.kind==="page"?X.target.trim():X.kind==="code"||ve)?X:void 0;return {step:ce,done:o.done.has(ce.id),...ve&&(X==null?void 0:X.kind)==="tour"?{tour:ve}:{},...de?{opens:de}:{},...ve?{target:ve}:{}}})}}h.has(`s:${l.id}`)||(h.add(`s:${l.id}`),r.track(j,{flow:t.id,step:l.id,kind:l.kind,action:"shown"}));let O=f.slice(p+1),y=O.findIndex(F=>F.kind==="condition"),b=(y<0?O:O.slice(0,y)).filter(k).length;return {type:"step",flow:t,step:l,index:c.before,total:c.before+1+b,last:!b&&y<0,...l.kind==="question"?{answer:($=ne.get(l.id))!=null?$:l.question?N.get(l.question.key):void 0,back:c.before>0}:{}}},Y=()=>{var c,l,f;if(i){let p=i,k=(c=p.flow.followUps)==null?void 0:c[p.reason],O=k?1:0,y=p.plain?1:3+O+((l=p.flow.second)!=null&&l[p.reason]?1:0);return {type:"cancel",screen:p.screen,flow:p.flow,reason:p.reason,...p.screen==="followup"&&k?{followUp:k,answer:p.answer}:{},offer:p.screen==="offer"?p.offer:void 0,...p.screen==="offer"?{round:p.round}:{},price:p.options.price,busy:p.busy,error:p.error,step:p.screen==="survey"?1:p.screen==="followup"?2:p.screen==="offer"?1+O+p.round:y,steps:y}}let t=U();if(t)return t;if(a&&!_e){let p=te,k=a;te=null,a=null;let O=p?q(p.flow):void 0;if(p&&O){let y=Ce(Z(O)).find(F=>F.id===p.step),b=B(O.id);y&&!y.event&&!((f=w.get(k))!=null&&f.dismissed)&&!b.done.has(y.id)&&(A(b,y.id),ye({flow:O.id,step:y.id,kind:"checklist",action:"completed"}),ge(O)),a=O.id;let $=U();if($)return $;_e||(a=null);}else if(m){let y=q(k),b=y?ie(y):void 0;Promise.resolve().then(()=>W(b));}}let o=d.find(p=>!v.has(p.id));return o?{type:"message",message:o}:null},P=()=>{let t=Y();(t==null?void 0:t.type)==="message"&&!h.has(`m:${t.message.id}`)&&(h.add(`m:${t.message.id}`),r.track(At,{message:t.message.id,journey:t.message.journey,action:"shown"}));for(let o of [...S])try{o();}catch(c){}},oe=t=>a===t.id?true:a&&q(a)&&!_(q(a))?false:(a=t.id,r.track(j,{flow:t.id,action:"started"}),P(),true),we=t=>t.audience==="answered"?!!t.answered&&N.get(t.answered.question)===t.answered.option:t.audience!=="signed_in"||!!r.personId(),se=t=>{let o=q(t);return !o||_(o)},Se=(t,o=ie(t))=>{var f;let c=(f=r.path)==null?void 0:f.call(r),l=ft(o);if(l)return se(l);if(ut(o))return false;if(An(o))return c!==void 0&&Nt(o,c);if(Mn(o))return true;for(let p of T)if(lt(o,p))return true;return false},W=t=>{var f,p;if(!M||a||!m||!r.personId()&&!((f=r.storage)!=null&&f.call(r)))return;let o=(p=r.path)==null?void 0:p.call(r),c=t&&!ut(t)?ae(t):"",l=Pe().find(k=>(ft(ie(k))?se(ft(ie(k))):An(ie(k))?o!==void 0&&Nt(ie(k),o):Mn(ie(k))||!!c&&ae(ie(k))===c)&&we(k)&&Z(k).length&&!_(k));l&&oe(l);},ee=(t,o,c)=>{let l=B(c.id);l.done.clear(),l.at.clear(),l.dismissed=false,te={flow:t.id,step:o},a=c.id,r.track(j,{flow:c.id,action:"started",from:t.id}),Q(),P();},he=(t,o,c)=>{let l=o.question,f=l.type==="text"?c.trim().slice(0,500):c.startsWith(Fe)?Fe+c.slice(Fe.length).trim().slice(0,490):c;N.set(l.key,f),ne.delete(o.id),A(B(t.id),o.id),r.track(j,{flow:t.id,step:o.id,kind:"question",action:"completed",question:l.key,answer:f,label:$r(l,f)}),ge(t),Q();},be=t=>{Q(),_(t)&&Promise.resolve().then(()=>W()),P();},Ke=()=>{let t=r.personId();x!==null&&x!==t&&(w.clear(),T.clear(),N.clear(),ne.clear(),v.clear(),a=null,te=null,E=void 0),x=t;let o=(async()=>{var f,p,k,O;let c=(f=r.storage)==null?void 0:f.call(r);if(c)try{let y=await c.get(pe(t));y&&me(JSON.parse(y));let b=await c.get(He(t));if(b)for(let F of JSON.parse(b))typeof F=="string"&&T.add(F);let $=await c.get(We(t));if($)for(let[F,D]of Object.entries(JSON.parse($)))typeof D=="string"&&N.set(F,D);}catch(y){}let l=re().length>0||!!(n!=null&&n.messages);if(t&&l&&E!==t){E=t;let y=await r.fetchInApp(t).catch(()=>null);if(y&&r.personId()===t){me(y.onboarding);for(let b of (p=y.events)!=null?p:[])typeof b=="string"&&T.add(ae(b));for(let[b,$]of Object.entries((k=y.answers)!=null?k:{}))typeof $=="string"&&!N.has(b)&&N.set(b,$);d=((O=y.messages)!=null?O:[]).filter(b=>b&&b.id&&b.title);}}t||(d=[]),m=true,W(),P();})();return C=o.finally(()=>{C===o&&(C=null);}),C},V=t=>t.round>1?{round:2}:t.rule>=0?{rule:t.rule}:{},Ae=t=>{var l,f,p,k;let o={answer:t.answer,plan:t.options.plan,months:Tr(t.options.customerSince,(l=r.now)==null?void 0:l.call(r))},c=(p=(f=t.flow.rules)==null?void 0:f[t.reason])!=null?p:[];t.rule=c.findIndex(O=>Nr(O,o)),t.offer=t.rule<0?t.flow.offers[t.reason]:(k=c[t.rule].offer)!=null?k:void 0,t.round=1,t.screen=t.offer?"offer":"confirm";},Te=(t,o,c)=>{var f;let l=t.screen==="offer"?t.offer:void 0;return {outcome:o,run:t.run,...t.reason?{reason:t.reason,reasonLabel:(f=t.flow.reasons.find(p=>p.id===t.reason))==null?void 0:f.label}:{},...t.answer?{answer:t.answer}:{},...o==="saved"&&l?{offer:l}:{},...c!=null&&c.trim()?{comment:c.trim().slice(0,500)}:{}}},Re=(t,o)=>{var c;r.track(Qe,{action:"finished",run:t.run,version:t.flow.version,outcome:o.outcome,customer:(c=t.options.customer)!=null?c:"consumer",...o.reason?{reason:o.reason}:{},...o.answer?{answer:o.answer}:{},...o.offer?{offer:o.offer.kind,...V(t)}:{},...o.comment?{comment:o.comment}:{}}),i===t&&(i=null),t.resolve(o),P();},qe=(t,o,c)=>{if(t.busy)return;let l=Te(t,o,c),f=o==="saved"?t.options.onSave:t.options.onCancel;t.busy=true,t.error=void 0,P(),Promise.resolve().then(()=>f==null?void 0:f(l)).then(()=>Re(t,l),()=>{t.busy=false,t.error=Ge("Something went wrong. Please try again."),P();});};return {setConfig:t=>{n=t,a&&!q(a)&&(a=null),P();},refresh:Ke,onEvent:t=>{var O;if(t==="$pageview"&&W(),!t||t.startsWith("$"))return;let o=ae(t),c=!!o&&!T.has(o);c&&T.add(o);let l=q(a),f=false,p=[...l?[l]:[],...re().filter(y=>y.shownBy==="code"&&y.id!==(l==null?void 0:l.id))];for(let y of p){let b=B(y.id),$=false;for(let F of Ce(Z(y)))F.kind==="checklist"&&F.event&&!b.done.has(F.id)&<(F.event,t)&&(A(b,F.id),$=true,r.track(j,{flow:y.id,step:F.id,kind:F.kind,action:"completed"}));$&&(f=true,ge(y));}if(f||c&&(l||p.length)?(Q(),P()):c&&Q(),!M||!r.personId()&&!((O=r.storage)!=null&&O.call(r)))return;let k=Pe().find(y=>Z(y).length&&!ut(ie(y))&<(ie(y),t)&&we(y)&&!_(y));k&&oe(k);},openCancelFlow:(t={})=>{var k,O;if(i)return i.promise;let o=(k=n==null?void 0:n.cancelFlow)!=null?k:Sr,c=t.customer!=="business"||o.reasons.length<2,l=()=>{},f=new Promise(y=>l=y),p={flow:o,options:t,plain:c,screen:c?"confirm":"survey",round:1,run:Mr(),busy:false,resolve:l,promise:f};return i=p,r.track(Qe,{action:"shown",run:p.run,version:o.version,customer:(O=t.customer)!=null?O:"consumer",plain:c}),P(),f},startOnboarding:t=>{let o=t?q(t):Pe().find(l=>Z(l).length&&!ut(ie(l))&&!ft(ie(l))&&!_(l));if(!o||!Z(o).length||o.shownBy==="code")return false;let c=B(o.id);return c.dismissed=false,oe(o)},view:Y,subscribe:t=>(S.add(t),()=>S.delete(t)),cancel:{pick:t=>{!i||i.busy||i.screen!=="survey"||!i.flow.reasons.some(o=>o.id===t)||(i.reason!==t&&(i.answer=void 0),i.reason=t,i.error=void 0,P());},answer:t=>{let o=i;if(!o||o.busy||o.screen!=="followup")return;let c=t.slice(0,500);o.answer=c.trim()?c:void 0,P();},next:()=>{var o,c;let t=i;if(!(!t||!t.reason)){if(t.screen==="survey")r.track(Qe,{action:"answered",run:t.run,version:t.flow.version,reason:t.reason}),(o=t.flow.followUps)!=null&&o[t.reason]?t.screen="followup":Ae(t);else if(t.screen==="followup")t.answer=(c=t.answer)==null?void 0:c.trim(),Ae(t);else return;P();}},accept:t=>{var c;let o=i;!o||o.screen!=="offer"||!o.reason||(o.busy||r.track(Qe,{action:"offer",run:o.run,version:o.flow.version,reason:o.reason,offer:(c=o.offer)==null?void 0:c.kind,...V(o),outcome:"accepted"}),qe(o,"saved",t));},decline:()=>{var c,l;let t=i;if(!t||t.screen!=="offer"||t.busy)return;r.track(Qe,{action:"offer",run:t.run,version:t.flow.version,reason:t.reason,offer:(c=t.offer)==null?void 0:c.kind,...V(t),outcome:"declined"});let o=t.round===1&&t.reason?(l=t.flow.second)==null?void 0:l[t.reason]:void 0;o?(t.offer=o,t.rule=void 0,t.round=2):t.screen="confirm",t.error=void 0,P();},confirm:t=>{let o=i;!o||o.screen!=="confirm"||qe(o,"cancelled",t);},close:()=>{var c,l;let t=i;if(!t||t.busy)return;let o=Te(t,"kept");(l=(c=t.options).onClose)==null||l.call(c,o),Re(t,o);}},onboarding:{next:()=>{var c,l;let t=U();if((t==null?void 0:t.type)!=="step")return;if(t.step.kind==="question"){let f=t.step.question,p=(c=ne.get(t.step.id))!=null?c:f?N.get(f.key):void 0;if(!f||!Nn(f,p))return;he(t.flow,t.step,p),P();return}A(B(t.flow.id),t.step.id),r.track(j,{flow:t.flow.id,step:t.step.id,kind:t.step.kind,action:"completed"}),ge(t.flow),Q(),P();let o=t.step.kind==="modal"?gt(t.step.url):void 0;o&&((l=r.openUrl)==null||l.call(r,o));},check:t=>{let o=U();if((o==null?void 0:o.type)!=="checklist")return;let c=o.items.find(l=>l.step.id===t);!c||c.done||(A(B(o.flow.id),t),r.track(j,{flow:o.flow.id,step:t,kind:"checklist",action:"completed"}),ge(o.flow),Q(),P());},dismiss:()=>{let t=U();!t||t.type!=="step"&&t.type!=="checklist"||(B(t.flow.id).dismissed=true,r.track(j,{flow:t.flow.id,...t.type==="step"?{step:t.step.id}:{},action:"dismissed"}),a=te&&te.flow!==t.flow.id&&q(te.flow)?te.flow:null,te=null,Q(),P());},startTour:t=>{var l;let o=U();if((o==null?void 0:o.type)!=="checklist")return false;let c=(l=o.items.find(f=>f.step.id===t))==null?void 0:l.target;return c?(ee(o.flow,t,c),true):false},open:t=>{var f,p;let o=U();if((o==null?void 0:o.type)!=="checklist")return false;let c=o.items.find(k=>k.step.id===t),l=c==null?void 0:c.opens;return !c||!l?false:(r.track(j,{flow:o.flow.id,step:t,kind:"checklist",action:"opened",opens:l.kind}),(l.kind==="tour"||l.kind==="modal")&&c.target?(ee(o.flow,t,c.target),true):(!c.done&&!c.step.event&&(A(B(o.flow.id),t),r.track(j,{flow:o.flow.id,step:t,kind:"checklist",action:"completed"}),ge(o.flow)),Q(),P(),l.kind==="page"?(f=r.navigate)==null||f.call(r,l.target.trim()):(p=r.task)==null||p.call(r,t,o.flow),true))},answer:t=>{let o=U();(o==null?void 0:o.type)!=="step"||o.step.kind!=="question"||(ne.set(o.step.id,String(t).slice(0,500)),P());},skip:()=>{let t=U(),o=(t==null?void 0:t.type)==="step"&&t.step.kind==="question"?t.step.question:void 0;(t==null?void 0:t.type)!=="step"||!(o!=null&&o.optional)||(ne.delete(t.step.id),A(B(t.flow.id),t.step.id),r.track(j,{flow:t.flow.id,step:t.step.id,kind:"question",action:"completed",question:o.key,skipped:true}),ge(t.flow),Q(),P());},back:()=>{let t=U();if((t==null?void 0:t.type)!=="step"||t.step.kind!=="question"||!t.back)return;let o=Ce(Z(t.flow)),c=o.findIndex(f=>f.id===t.step.id),l=B(t.flow.id);for(let f=c-1;f>=0;f--)if(l.done.has(o[f].id)){l.done.delete(o[f].id),l.at.delete(o[f].id);break}Q(),P();},item:t=>{let o=q(t);if(!o)return null;let c=w.get(o.id),l=Ce(Z(o)).map(k=>{let O=k.question?N.get(k.question.key):void 0;return {...k,done:!!(c!=null&&c.done.has(k.id)),...O!==void 0?{answer:O}:{}}}),f=l.length>0&&l.every(k=>k.done),p=!!(c!=null&&c.dismissed);return {item:o,steps:l,done:f,dismissed:p,eligible:!f&&!p&&we(o)&&Se(o)}},seen:t=>{let o=q(t);if(!o||o.shownBy!=="code"||!m)return;h.has(`f:${o.id}`)||(h.add(`f:${o.id}`),r.track(j,{flow:o.id,action:"started"}));let c=w.get(o.id);for(let l of Ce(Z(o)))if(!(c!=null&&c.done.has(l.id))&&!h.has(`s:${l.id}`)&&(h.add(`s:${l.id}`),r.track(j,{flow:o.id,step:l.id,kind:l.kind,action:"shown"}),l.kind!=="checklist"))break},complete:(t,o)=>{let c=q(t),l=c&&Ce(Z(c)).find(p=>p.id===o);if(!c||!l||l.kind==="question")return;let f=B(c.id);f.done.has(l.id)||(A(f,l.id),r.track(j,{flow:c.id,step:l.id,kind:l.kind,action:"completed"}),be(c));},dismissItem:t=>{let o=q(t);if(!o)return;let c=B(o.id);c.dismissed||(c.dismissed=true,r.track(j,{flow:o.id,action:"dismissed"}),a===o.id&&(a=null),be(o));},answerItem:(t,o,c)=>{let l=q(t),f=l&&Ce(Z(l)).find(p=>{var k;return p.kind==="question"&&(p.id===o||((k=p.question)==null?void 0:k.key)===o)});!l||!(f!=null&&f.question)||!Nn(f.question,c)||(he(l,f,c),be(l));}},finale:()=>ue,accent:()=>n==null?void 0:n.onboardingAccent,answers:()=>Object.fromEntries(N),message:{click:()=>{var c;let t=Y();if((t==null?void 0:t.type)!=="message")return;v.add(t.message.id),r.track(At,{message:t.message.id,journey:t.message.journey,action:"clicked"});let o=gt(t.message.url);P(),o&&((c=r.openUrl)==null||c.call(r,o));},dismiss:()=>{let t=Y();(t==null?void 0:t.type)==="message"&&(v.add(t.message.id),r.track(At,{message:t.message.id,journey:t.message.journey,action:"dismissed"}),P());}}}};var Lr={questions:"question",checklist:"checklist",tour:"tour"},Un=(e,n,r={})=>{var C,E;let i=(C=r.type)!=null?C:"questions",a=(E=Lr[i])!=null?E:"question",d=new Set,m=x=>{var w;return e(j,{code:ae(n),name:n,type:i,...(w=r.order)!=null&&w.length?{order:r.order}:{},...x})};return {saw:(x,w)=>{d.has(x)||(d.add(x),m({step:x,title:w,kind:a,action:"shown"}));},answered:(x,w,v)=>m({step:x,kind:"question",action:"completed",question:x,answer:w,label:v!=null?v:w}),done:x=>m({step:x,kind:a,action:"completed"}),closed:x=>m({...x?{step:x}:{},kind:a,action:"dismissed"})}};var Ur="ck_pick",Vr="ck_origin",mt=e=>typeof CSS!="undefined"&&CSS.escape?CSS.escape(e):e.replace(/[^a-zA-Z0-9_-]/g,n=>`\\${n}`),Dr=e=>[...e.classList].filter(n=>n.length<30&&!/\d{2,}|[_-][a-z0-9]{5,}$|^(is|has)-|hover|active|focus|open|selected|:|\[/.test(n)).slice(0,2),Vn=e=>{let n=e.ownerDocument,r=m=>{try{return n.querySelectorAll(m).length===1}catch(C){return false}},i=e.getAttribute("data-ck-target");if(i)return `[data-ck-target="${i.replace(/"/g,'\\"')}"]`;if(e.id&&!/\d{3,}/.test(e.id)&&r(`#${mt(e.id)}`))return `#${mt(e.id)}`;let a=[],d=e;for(;d&&d!==n.documentElement&&a.length<6;){if(d!==e&&d.id&&!/\d{3,}/.test(d.id)){a.unshift(`#${mt(d.id)}`);break}let m=d.tagName.toLowerCase(),C=Dr(d).map(h=>`.${mt(h)}`).join(""),E=d.parentElement,x=E?[...E.children].filter(h=>h.tagName===d.tagName):[],w=x.length>1?`:nth-of-type(${x.indexOf(d)+1})`:"";a.unshift(`${m}${C}${w}`);let v=a.join(" > ");if(r(v))return v;d=E;}return a.join(" > ")},Dn=()=>{var w;if(typeof window=="undefined"||window.top===window)return null;let e=new URLSearchParams(window.location.search);if(e.get(Ur)!=="1")return null;let n;try{n=new URL((w=e.get(Vr))!=null?w:"").origin;}catch(v){return null}if(!/^https?:\/\//.test(n))return null;let r=v=>window.parent.postMessage(v,n),i=document.createElement("div");i.setAttribute("aria-hidden","true"),Object.assign(i.style,{position:"fixed",zIndex:"2147483647",pointerEvents:"none",border:"2px solid #0ea5e9",background:"rgba(14,165,233,.12)",borderRadius:"6px",transition:"all 60ms linear",display:"none"});let a=document.createElement("div");Object.assign(a.style,{position:"absolute",left:"-2px",bottom:"calc(100% + 4px)",font:"600 11px/1.4 system-ui, sans-serif",color:"#fff",background:"#0c4a6e",padding:"2px 6px",borderRadius:"4px",whiteSpace:"nowrap",maxWidth:"360px",overflow:"hidden",textOverflow:"ellipsis"}),i.appendChild(a),document.body.appendChild(i);let d=null,m=v=>{if(d=v&&v!==i&&!i.contains(v)?v:null,!d){i.style.display="none";return}let h=d.getBoundingClientRect();Object.assign(i.style,{display:"block",left:`${h.left-2}px`,top:`${h.top-2}px`,width:`${h.width+4}px`,height:`${h.height+4}px`}),a.textContent=Vn(d);},C=v=>m(document.elementFromPoint(v.clientX,v.clientY)),E=v=>{var S,M;v.preventDefault(),v.stopPropagation();let h=(S=document.elementFromPoint(v.clientX,v.clientY))!=null?S:d;!h||h===i||r({type:"mrrocket:picked",selector:Vn(h),text:((M=h.textContent)!=null?M:"").trim().replace(/\s+/g," ").slice(0,80)});},x=v=>{v.key==="Escape"&&r({type:"mrrocket:pick-cancel"});};return window.addEventListener("mousemove",C,true),window.addEventListener("click",E,true),window.addEventListener("keydown",x,true),r({type:"mrrocket:pick-ready"}),()=>{window.removeEventListener("mousemove",C,true),window.removeEventListener("click",E,true),window.removeEventListener("keydown",x,true),i.remove();}};var Hr={get:e=>{try{return window.localStorage.getItem(e)}catch(n){return null}},set:(e,n)=>{try{window.localStorage.setItem(e,n);}catch(r){}}},Hn=()=>{try{for(let e=window.localStorage.length-1;e>=0;e--){let n=window.localStorage.key(e);n!=null&&n.startsWith("mrrocket:onboarding")&&window.localStorage.removeItem(n);}}catch(e){}},Wn=e=>({track:e.track,personId:e.personId,auto:e.auto,storage:()=>e.canStore()?Hr:null,openUrl:n=>window.location.assign(n),path:()=>window.location.pathname,navigate:n=>{var a;let r=(a=e.onNavigate)==null?void 0:a.call(e);if(r)return r(n);let i=gt(n);i&&window.location.assign(i);},task:(n,r)=>{var i,a;return (a=(i=e.onTask)==null?void 0:i.call(e))==null?void 0:a(n,r)},fetchInApp:async n=>{var a;if(!e.apiKey)return null;let r=(a=e.userHash)==null?void 0:a.call(e,n),i=await fetch(`${e.host}/api/sdk/inapp?key=${encodeURIComponent(e.apiKey)}&distinctId=${encodeURIComponent(n)}${r?`&userHash=${r}`:""}${dt()}`);return Ve(i.status),i.ok?await i.json():null}});var kt="mrr_ref",yt="mrr_ref",Wr="mrr_ref",jr="mrr_click";var Ze=/^[A-Za-z0-9_-]{1,64}$/;var Kr=(e,n="ref")=>{let r=new URLSearchParams(e);return qr(i=>r.get(i),n)},qr=(e,n="ref")=>{let r=e(Wr);if(r&&Ze.test(r)){let a=e(jr);return {code:r,clickId:a&&Ze.test(a)?a:null,direct:false}}let i=e(n);return i&&Ze.test(i)?{code:i,clickId:null,direct:true}:null},jn=e=>{var n;return `${e.code}.${(n=e.clickId)!=null?n:""}.${e.at}`},wt=(e,n=60,r=Date.now())=>{if(!e)return null;let[i,a,d]=e.split("."),m=Number(d);return !i||!Ze.test(i)||!Number.isFinite(m)||a&&!Ze.test(a)||r-m>n*864e5||m>r+864e5?null:{code:i,clickId:a||null,at:m}};var G=null,bt=()=>typeof document!="undefined",Kn=e=>{var r;if(!bt())return;let n=(r=document.cookie.split("; ").find(i=>i.startsWith(`${e}=`)))==null?void 0:r.slice(e.length+1);try{return n?decodeURIComponent(n):void 0}catch(i){return n}},xt=()=>{try{return typeof localStorage=="undefined"?null:localStorage}catch(e){return null}},Lt=()=>{var e,n;return G||(bt()?(n=wt(Kn(kt),3650))!=null?n:wt((e=xt())==null?void 0:e.getItem(yt),3650):null)};var ht=(e,n)=>{var a;if(!bt())return;let r=Math.max(1,Math.round(n))*86400,i=typeof location!="undefined"&&location.protocol==="https:"?"; secure":"";document.cookie=`${kt}=${encodeURIComponent(jn(e))}; path=/; max-age=${r}; samesite=lax${i}`;try{(a=xt())==null||a.setItem(yt,jn(e));}catch(d){}},vt=()=>{var e;if(bt()){document.cookie=`${kt}=; path=/; max-age=0; samesite=lax`;try{(e=xt())==null||e.removeItem(yt);}catch(n){}}},qn=()=>{G=null;},Bn=async e=>{var i,a,d;let n=Kr(e.search,e.param),r=(i=e.now)!=null?i:Date.now();if(!n)return !G&&e.store&&(G=(d=wt(Kn(kt),e.days,r))!=null?d:wt((a=xt())==null?void 0:a.getItem(yt),e.days,r),G||vt()),G;if(G={code:n.code,clickId:n.clickId,at:r},e.store&&ht(G,e.days),e.beacon)try{let m=await e.beacon({code:n.code,clickId:n.clickId});m&&G&&G.code===n.code&&!G.clickId&&(G={...G,clickId:m},e.store&&ht(G,e.days));}catch(m){}return G},Yn=e=>e==="$identify"||!e.startsWith("$");var Ut=3600*24*365,zn=e=>{var r;if(typeof document=="undefined")return;let n=(r=document.cookie.split("; ").find(i=>i.startsWith(`${e}=`)))==null?void 0:r.slice(e.length+1);if(n)try{return decodeURIComponent(n)}catch(i){return n}},Ct=(e,n,r)=>{let i=window.location.protocol==="https:"?"; secure":"";document.cookie=`${e}=${encodeURIComponent(n)}; path=/; max-age=${r}; samesite=lax${i}`;},et=e=>{document.cookie=`${e}=; path=/; max-age=0; samesite=lax`;},K={utm:{}},Jn=()=>{var e;return (e=K.id)!=null?e:K.id=Ft()},Br=new Map,tt=()=>typeof window=="undefined"?void 0:Br,Vt=(e,n)=>{if(e!=="cookies")return Jn();let r=zn(Ie);if(r)return K.id=r;let i=Jn();return Ct(Ie,i,Ut),i},Dt=e=>{var a;let n=Date.now(),r=K.session,i=(a=e?zn(Ue):void 0)!=null?a:r&&n-r.last<18e5?r.id:Ft();return K.session={id:i,last:n},e&&Ct(Ue,i,18e5/1e3),i},Ht=()=>{var r;let e=window.location.href;if(K.url===e)return;K.referrer=(r=K.url)!=null?r:document.referrer||void 0,K.url=e;let n=kn(window.location.search);Object.keys(n).length&&(K.utm=n);},Gn=()=>{let e=navigator,n=window;return e.doNotTrack==="1"||n.doNotTrack==="1"||e.globalPrivacyControl===true};var Rt=window,Xr=()=>{var e,n;return (n=(e=document.currentScript)!=null?e:document.querySelector('script[data-key][src*="sdk"]'))!=null?n:document.querySelector("script[data-key][src*='mrrocket']")},Qn=new Set,le=e=>{Qn.has(e)||(Qn.add(e),console.warn(`[MRRocket] ${e}`));},Jr=()=>{var Gt,Qt,Zt,en;let e=Xr(),n=s=>{var u;return (u=e==null?void 0:e.getAttribute(`data-${s}`))!=null?u:void 0},r=(s,u)=>{let g=n(s);return g===void 0?u:!["false","0","off","no"].includes(g.trim().toLowerCase())},i=(Gt=e==null?void 0:e.src)!=null?Gt:"",a="";try{a=i?new URL(i,window.location.href).origin:"";}catch(s){a="";}n("locale")&&Mt(n("locale"));let d=((Qt=n("key"))!=null?Qt:"").trim(),m=((Zt=n("api-host"))!=null?Zt:a).trim().replace(/\/+$/,""),C=n("consent"),E=r("respect-dnt",false),x=r("heatmaps",true),w=r("errors",true),v=n("release"),h=n("attribution"),S=h==="always"||h==="off"?h:"consent",M=n("referral-param")||"ref",T={},H=(s,u)=>{var g;return (g=T[s])!=null?g:T[s]=new Promise((R,I)=>{var tn;let L=()=>Rt[u];if(L())return R(L());let ke=(tn=n(`${s}-src`))!=null?tn:i?i.replace(/(\.min)?\.js(\?[^#]*)?(#.*)?$/,`-${s}$1.js?v=${it}`):"";if(!ke)return I(new Error(s));let Oe=document.createElement("script");Oe.async=true,Oe.src=ke,Oe.onload=()=>L()?R(L()):I(new Error(s)),Oe.onerror=()=>I(new Error(s)),document.head.appendChild(Oe);}).catch(R=>{throw T[s]=void 0,R})},J=n("theme"),te={theme:J==="light"||J==="dark"?J:"auto",accent:n("accent")},N=new URLSearchParams(window.location.search),ne=yn(N.get(mn)),De=N.get(wn)==="1",ue=N.get(hn),re=De||!!ue;ue&&document.documentElement.setAttribute(It,"loading"),De&&Dn();let Pe=N.get(Je);if(Pe!==null){N.delete(Je);let s=N.toString();history.replaceState(history.state,"",`${window.location.pathname}${s?`?${s}`:""}${window.location.hash}`);}let q=Gn(),B=C==="cookies"||C==="off"?C:"cookieless",$e=r("replay",false),ye="",A,Me=null,fe,_=null,pe=false,He=false,We=null,ge=null,Q=window.location.pathname,me=[],je=new Set,_e=[],U=()=>ue||E&&q?"off":B,Y=()=>!re&&U()!=="off",P=()=>A!=null?A:ye,oe=()=>U()==="cookies"?P():A,we=()=>{var s;return (s=A!=null?A:U()!=="cookies"?_==null?void 0:_.unit:void 0)!=null?s:ye},se=s=>On(Me,s);d||le('No public key. Add data-key="mrr_pub_\u2026" to the script tag; nothing is tracked until then.');let Se=(s=false)=>{if(!me.length)return;if(!d){me.length=0;return}let u=`${m}/api/sdk/events`;for(let g of rn(d,me.splice(0),{v:it,errors:w,platform:"web"},se(oe())))s&&"sendBeacon"in navigator&&navigator.sendBeacon(u,g)||fetch(u,{method:"POST",headers:{"content-type":"application/json"},body:g,keepalive:true}).then(I=>{I.status===401?Ve(401):I.ok||le(`Events were rejected with ${I.status}. Check data-key (MRRocket \u203A Settings \u203A Products).`);}).catch(()=>le(`Could not reach ${m||"this origin"} to send events. Check data-api-host.`));},W=null,ee=null,he=(s,u,g=Date.now(),R)=>{var L;if(!Y())return;let I=Yn(s)?Lt():null;me.push({event:s,props:I?{...u,$referral:{code:I.code,clickId:I.clickId}}:u,distinctId:(L=oe())!=null?L:_==null?void 0:_.unit,sessionId:Dt(U()==="cookies"),ts:g,url:R!=null?R:window.location.href,referrer:K.referrer,...K.utm,screen:{w:window.screen.width,h:window.screen.height}});},be=(s,u)=>{typeof s!="string"||!s||(he(s,u),Y()&&(W==null||W.event(s)),V.onEvent(s));},Ke={},V=Ln({...Wn({host:m,apiKey:d,track:he,personId:()=>Y()?A:void 0,userHash:se,canStore:()=>U()==="cookies",auto:r("onboarding",true),onNavigate:()=>Ke.onNavigate,onTask:()=>Ke.onTask}),expose:s=>Et(s)}),Ae=false,Te;V.subscribe(()=>{Ae||!V.view()||re||(Ae=true,H("flows","__mrrocketFlows").then(s=>s.mountFlows(V,te)).catch(()=>{Ae=false,le("The cancel flow and onboarding dialogs did not load. Check that sdk-flows.js is served next to sdk.js.");}));});let Re=(s,u)=>{if(!Y())return;let g=`${window.location.pathname}|${s}`;je.has(g)||(je.add(g),be("$exposure",{experiment:s,variant:u}));},qe=s=>at(s,_,we(),ne,tt()),Et=s=>Re(s,qe(s)),Ot=s=>{let u=pn(s,_,we(),{...fe});return u&&Re(u.experiment,u.variant),fn(s,_,we(),{...fe})},t=()=>{if(ue)return false;let s=Cn(_,window.location.href,we(),ne,tt());return s!=null&&s.to?(Se(true),window.location.replace(s.to),true):(s!=null&&s.experiment&&Re(s.experiment,s.variant),false)},o=()=>{if(!_)return;let s=document.querySelectorAll("[data-ck-text]");if(!s.length)return;let u=vn(_,we(),ne,tt()),g=new Set;s.forEach(R=>{var ke,Oe;let I=R.dataset.ckText;if(!I)return;g.add(I),R.dataset.ckDefault===void 0&&(R.dataset.ckDefault=(ke=R.textContent)!=null?ke:"");let L=(Oe=u[I])!=null?Oe:R.dataset.ckDefault;R.textContent!==L&&(R.textContent=L);});for(let R of new Set([...g].flatMap(I=>xn(_,I))))Et(R);},c=()=>{var s,u;return (u=(s=_==null?void 0:_.referral)==null?void 0:s.cookieDays)!=null?u:60},l=()=>S==="always"?U()!=="off":S==="consent"&&U()==="cookies",f=null,p=false,k=()=>{if(!pe||re)return;if(S==="off"||U()==="off"){qn(),(S==="off"||p)&&vt();return}let s=window.location.href;f!==s&&(f=s,Bn({search:window.location.search,param:M,store:l(),days:c(),beacon:d?({code:u,clickId:g})=>fetch(`${m}/api/sdk/affiliate/click`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({key:d,code:u,clickId:g,url:s,referrer:document.referrer||void 0}),keepalive:true}).then(R=>R.ok?R.json():null).then(R=>{var I;return (I=R==null?void 0:R.clickId)!=null?I:null}):void 0}));},O=()=>{let s=l(),u=Lt();s&&u?ht(u,c()):!s&&p&&vt(),p=s;},y=0,b=false,$=()=>{var R,I;let s=Y()&&$e&&!!(_!=null&&_.replay)&&!!d;if(s===b)return;b=s;let u=++y;if(!s){W==null||W.stop(true),W=null;return}let g=(I=(R=_==null?void 0:_.replay)==null?void 0:R.sampleRate)!=null?I:.1;H("replay","__mrrocketReplay").then(L=>L.startReplay({host:m,apiKey:d,sessionId:Dt(U()==="cookies"),distinctId:oe(),identified:!!A,userHash:se(oe()),sampleRate:g,maskAllText:n("mask-all-text")===void 0?void 0:r("mask-all-text",true),warn:le})).then(L=>{u!==y?L==null||L.stop(true):W=L;}).catch(()=>le("Session recording could not start (the recorder did not load)."));},F=r("messenger",false),D=null,xe=s=>{re||d&&(D!=null||(D=H("messenger","__mrrocketMessenger").then(u=>{var L;let g=ke=>n(`messenger-${ke}`)===void 0?void 0:r(`messenger-${ke}`,true),R=n("messenger-position"),I=(L=n("messenger-theme"))!=null?L:J;return u.mountMessenger({host:m,apiKey:d,distinctId:P,user:()=>fe,userHash:()=>se(P()),launcher:F,position:R,corners:n("messenger-corners"),header:n("messenger-header"),font:n("messenger-font"),title:n("messenger-title"),greeting:n("messenger-greeting"),label:n("messenger-label"),askEmail:g("ask-email"),help:g("help"),sound:g("sound"),preview:g("preview"),theme:I==="light"||I==="dark"||I==="auto"?I:void 0,accent:n("accent")})})),D.then(s).catch(()=>{D=null,le("sdk-messenger.js did not load.");}));},ce=n("forms")==="auto",X=false,Ee=()=>{X||!d||re||!document.querySelector(ce?"form":"form[data-mrrocket-form]")||(X=true,H("forms","__mrrocketForms").then(s=>s.watchForms({host:m,apiKey:d,auto:ce,distinctId:()=>Y()?oe():void 0,userHash:se,identified:()=>!!A,identify:qt,tracking:Y,referrer:()=>K.referrer,utm:()=>K.utm})).catch(()=>X=false));},ve=()=>{!He||!Y()||ge===window.location.pathname||(ge=window.location.pathname,be("$pageview",{path:window.location.pathname}));},de=null,Wt=()=>{let s=de;x&&s&&s.max>0&&he("$scroll",{depth:s.max,docH:s.docH,vw:window.innerWidth,vh:window.innerHeight},Date.now(),s.url),de=null;},Be=()=>{var I,L;if(!x||!Y()||re)return;let s=document.documentElement,u=Math.max(s.scrollHeight,(L=(I=document.body)==null?void 0:I.scrollHeight)!=null?L:0),g=an(),R=window.location.href;(de==null?void 0:de.url)!==R?de={url:R,max:g,docH:u}:g>de.max&&(de={url:R,max:g,docH:u});},jt=()=>{let s=window.location.pathname;s!==Q&&(Q=s,!(pe&&t())&&(Wt(),Ht(),W==null||W.page(s),ee==null||ee.crumb("navigation",s),ve(),k(),window.setTimeout(()=>{Be(),o(),Ee();},0)));},Kt=()=>{let s=U(),u=We;We=s,u==="cookies"&&s!=="cookies"&&(et(Ie),et(Ue)),s==="off"&&(me.length=0,K.session=void 0),u==="cookies"&&s!=="cookies"&&Hn(),ye=Vt(s),O(),k(),$(),ve(),Be();},er=s=>{let{analytics:u,replay:g}=typeof s=="string"?{analytics:s,replay:void 0}:s!=null?s:{};if(u!==void 0&&u!=="cookieless"&&u!=="cookies"&&u!=="off"){le('setConsent: use "cookies", "cookieless" or "off".');return}u==="off"&&(me.length=0,A&&U()!=="off"&&(me.push({event:gn,distinctId:A,ts:Date.now()}),Se(true))),u&&(B=u),typeof g=="boolean"&&($e=g),Kt(),pe&&V.refresh();},qt=(s,u,g)=>{if(typeof s!="string"||!s)return;let R=oe();Me=En(Me,s,g==null?void 0:g.hash),A=s,he("$identify",{...u,id:s,...R&&R!==s?{previousId:R}:{}}),W==null||W.identify(s,se(s)),U()==="cookies"&&Ct(Ie,s,Ut),fe={...u,id:s},o(),pe&&V.refresh(),D==null||D.then(I=>I.refresh());},nt={track:be,identify:qt,reset:()=>{Se(),A=void 0,Me=null,fe=void 0,je.clear(),U()==="cookies"&&(et(Ie),et(Ue)),K.id=void 0,K.session=void 0,ye=Vt(U()),o(),pe&&V.refresh(),D==null||D.then(s=>s.refresh());},captureError:s=>ee==null?void 0:ee.capture(s,"manual"),setConsent:er,setLocale:Mt,currentLocale:ct,getFlag:s=>Ot(s)!==false,getFlagVariant:s=>{let u=Ot(s);return typeof u=="string"?u:null},getVariant:s=>{let u=qe(s);return (_||ne[s])&&Re(s,u),u},ready:s=>{typeof s=="function"&&(pe?window.setTimeout(()=>s(nt),0):_e.push(s));},getDistinctId:P,cancelFlow:{open:s=>V.openCancelFlow(s)},onboarding:{start:s=>V.startOnboarding(s),get:s=>{let u=V.onboarding.item(s);return u&&!u.done&&!u.dismissed&&V.onboarding.seen(s),u},subscribe:s=>V.subscribe(()=>s()),complete:(s,u)=>V.onboarding.complete(s,u),dismiss:s=>V.onboarding.dismissItem(s),answer:(s,u,g)=>V.onboarding.answerItem(s,u,g),report:(s,u)=>Un(be,s,u),setHandlers:s=>{Ke={onNavigate:typeof(s==null?void 0:s.onNavigate)=="function"?s.onNavigate:void 0,onTask:typeof(s==null?void 0:s.onTask)=="function"?s.onTask:void 0};}},openCancelFlow:s=>V.openCancelFlow(s),startOnboarding:s=>V.startOnboarding(s),paywall:{open:(s,u)=>(Te!=null?Te:Te=H("flows","__mrrocketFlows").then(g=>g.paywallHost({config:()=>_,distinctId:we,track:he,kept:tt()},te))).then(g=>g.open(s,u))},push:{subscribe:s=>{let u=Y()?A:void 0;if(!u)return Promise.resolve({status:"not-signed-in"});let g=window.Notification,R=Promise.resolve(g&&g.permission==="default"&&(s==null?void 0:s.ask)!==false?g.requestPermission():g==null?void 0:g.permission);return H("push","__mrrocketPush").then(I=>I.subscribeWebPush({host:m,apiKey:d,distinctId:u,userHash:se(u),permission:R},s))},unsubscribe:()=>H("push","__mrrocketPush").then(s=>s.unsubscribeWebPush({host:m,apiKey:d,distinctId:A,userHash:se(A)}))},messenger:{open:s=>xe(u=>u.open(s)),close:()=>{D==null?void 0:D.then(s=>s.close()).catch(()=>{});},toggle:()=>xe(s=>s.toggle())},openMessenger:()=>xe(s=>s.open()),version:it};Ht(),Kt();let Ne=Rt.mrrocket,tr=(en=Ne==null?void 0:Ne.q)!=null?en:[],_t=Ne&&typeof Ne=="object"?Ne:{};Object.assign(_t,nt,{__loaded:true}),delete _t.q,Rt.mrrocket=_t;for(let[s,u]of tr){let g=nt[s];if(typeof g=="function")try{g(...Array.from(u!=null?u:[]));}catch(R){console.error(R);}}He=true,ve(),w&&d&&!re&&(ee=Sn({host:m,apiKey:d,release:v,context:()=>{var s;return {send:Y(),distinctId:oe(),sessionId:(s=K.session)==null?void 0:s.id,userHash:se(oe())}},warn:le}),ee.crumb("navigation",window.location.pathname));for(let s of ["pushState","replaceState"]){let u=history[s];history[s]=function(...g){let R=u.apply(this,g);return jt(),R};}window.addEventListener("popstate",jt);let nr=new Ye;document.addEventListener("click",s=>{var L;s.target instanceof Element&&s.target.closest("[data-ck-messenger]")&&(s.preventDefault(),xe(ke=>ke.open()));let u=s.target instanceof Element?s.target.closest("[data-ck-goal]"):null;if(u!=null&&u.dataset.ckGoal&&be(u.dataset.ckGoal,{text:(L=u.textContent)==null?void 0:L.trim().slice(0,80)}),!Y())return;let g=sn(s);if(!g)return;let R=nr.push(g.x,g.y,Date.now());if((g.label||g.selector)&&(ee==null||ee.crumb("click",g.label||g.selector)),W==null||W.click(g,R),!x)return;let I={x:g.x,y:g.y,vw:g.vw,vh:g.vh,docH:g.docH,selector:g.selector,label:g.label,dead:!g.interactive};he("$click",I),R&&he("$rageclick",I);});let St=0;window.addEventListener("scroll",()=>{St||(St=window.requestAnimationFrame(()=>{St=0,Be();}));},{passive:true}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Be()):Be(),window.setInterval(()=>Se(),2e3),window.addEventListener("pagehide",()=>{Wt(),Se(true);});let Bt=()=>{if(pe=true,t())return;let s=Rn(_,Pe);s&&Re(s.experiment,s.variant),document.documentElement.classList.remove("ck-hide"),k(),$(),V.setConfig(_),V.refresh(),F&&(document.body?xe():document.addEventListener("DOMContentLoaded",()=>xe())),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{o(),Ee(),Yt();}):(o(),Ee(),Yt());for(let u of _e.splice(0))try{u(nt);}catch(g){console.error(g);}},rt,rr=s=>H("preview","__mrrocketPreview").then(u=>u.bootPreview(m,ue,_)).then(u=>{u&&(_=u.config,Object.assign(ne,u.force),rt=u.show);}).catch(()=>{}).then(s),Yt=()=>{ue&&(rt!=null?rt:(()=>document.documentElement.setAttribute(It,"failed")))();},Xt=0,Jt=s=>{let u=++Xt;return fetch(`${m}/api/sdk/config?key=${encodeURIComponent(d)}${dt()}`).then(g=>(g.ok||le(`Config request to ${m||"this origin"} answered ${g.status}. Check data-key and data-api-host.`),g.ok?g.json():null)).then(g=>{g&&Array.isArray(g.experiments)&&u===Xt&&(_=_!=null&&_.unit?{...g,unit:_.unit}:g,Fn(g.words,g.lang)),s();}).catch(()=>{le(`Could not reach ${m||"this origin"}. Check data-api-host. The page keeps its own texts and flags stay off.`),s();})},zt=ue?()=>{rr(Bt);}:Bt;d?(Jt(zt),Pn(()=>{Jt(()=>{V.setConfig(_),o();});})):zt();},Zn;typeof window!="undefined"&&typeof document!="undefined"&&!((Zn=Rt.mrrocket)!=null&&Zn.__loaded)&&Jr();
|
|
3
3
|
})();
|
package/dist/core.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ import type { CancelFlowConfig, OnboardingFlow } from "./flows.js";
|
|
|
6
6
|
import type { PaywallConfig } from "./paywall.js";
|
|
7
7
|
export type VariantId = string;
|
|
8
8
|
/** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */
|
|
9
|
-
export declare const SDK_VERSION = "0.29.
|
|
9
|
+
export declare const SDK_VERSION = "0.29.2";
|
|
10
10
|
/** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */
|
|
11
11
|
export interface VariantConfig {
|
|
12
12
|
id: VariantId;
|
package/dist/core.js
CHANGED
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core.ts"],"sourcesContent":["/**\n * The part of the SDK that runs anywhere: experiment config, variant assignment, preview links and event shapes.\n * No React, no browser APIs, so the server helper, the proxy helper and the client share it.\n */\nimport type { CancelFlowConfig, OnboardingFlow } from \"./flows\";\nimport type { PaywallConfig } from \"./paywall\";\n\nexport type VariantId = string;\n\n/** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */\nexport const SDK_VERSION = \"0.29.1\";\n\n/** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */\nexport interface VariantConfig {\n id: VariantId;\n /** Share of traffic, 0 to 1. The weights of an experiment add up to 1. */\n weight: number;\n changes?: Record<string, string>;\n /**\n * A redirect test: where this variant sends the visitor instead of the test's page (a path like \"/pricing-b\" or a\n * full address). Control has none and stays. SDK 0.7.0+.\n */\n url?: string;\n}\n\nexport interface ExperimentConfig {\n /** The experiment's key, the same as in Cockpit. */\n key: string;\n status: \"running\" | \"draft\" | \"stopped\";\n /** Control first. */\n variants: VariantConfig[];\n /** A winner that shipped: everyone gets it, and nobody is assigned anymore. */\n winner?: VariantId;\n /** A redirect test: the path of the page it runs on (\"/pricing\"). Visitors there are sent to their variant's `url`. */\n path?: string;\n}\n\n/** A page redirect set in MRRocket (Conversion › Landing pages › Redirect): everyone on `from` goes to `to`. SDK 0.7.0+. */\nexport interface RedirectConfig {\n /** A path of the site, like \"/old-pricing\". */\n from: string;\n /** A path or a full address. */\n to: string;\n}\n\nexport interface CockpitConfig {\n /** The product the public key belongs to. */\n project: string;\n /** The language the server chose for the words below, like \"de\" (`lang` on the request). SDK 0.21.0+. */\n lang?: string;\n /** The SDK's own words: English source word to translation (see words.ts). Absent for English. SDK 0.21.0+. */\n words?: Record<string, string>;\n experiments: ExperimentConfig[];\n /** The product's affiliate program: how many days a partner's referral is kept. Missing without a program. */\n referral?: { cookieDays: number };\n /** Session recordings: present only while the product records (Cockpit › Sessions). See `ReplayConfig`. */\n replay?: ReplayConfig;\n /** Feature flags of the product in Production (MRRocket › Build › Feature flags), evaluated by `useFlag` and `getFlag`. */\n flags?: FlagConfig[];\n /**\n * Published copy for texts the site marks (`<Text id>`, `data-ck-text`): a landing page's headline, subheadline and\n * button (`pricing.headline` …) and a paywall's (`paywall.<placement>.headline` …) as published in MRRocket. A\n * running test's variant changes them on top. Missing when nothing is published. SDK 0.5.0+.\n */\n texts?: Record<string, string>;\n /** The product's live cancel flow (MRRocket › Churn › Cancel flow), for `cancelFlow.open()`. SDK 0.7.0+. */\n cancelFlow?: CancelFlowConfig;\n /** The in-app steps of live onboarding flows (tours, checklists, modals). SDK 0.7.0+. */\n onboarding?: OnboardingFlow[];\n /** The product's brand color (\"#rrggbb\") for the onboarding dialogs when the app passes no accent. SDK 0.18.0+. */\n onboardingAccent?: string;\n /** A live Lifecycle journey has in-app messages: signed-in people ask `/api/sdk/inapp` for theirs. SDK 0.7.0+. */\n messages?: boolean;\n /** Page redirects set in MRRocket; the SDK sends visitors on before the page shows (`redirectFor`). SDK 0.7.0+. */\n redirects?: RedirectConfig[];\n /** Published paywalls with their pages, per placement (MRRocket › Conversion › Paywalls), for `paywall.open()`. SDK 0.14.0+. */\n paywalls?: PaywallConfig[];\n /**\n * The visitor's unit for A/B tests (0.24.0): the same daily visitor hash MRRocket counts a cookieless visitor by\n * (`v_…`, from the key, the day, the address and the browser, with a server secret). Without a signed-in id or the\n * `ck_id` cookie, tests and flags assign by it, so a visitor keeps their version all day across reloads and between\n * server render and browser, and their events carry it as `distinctId`. Held in memory only, never stored on the\n * device (a React Native app leaves it out of its cached config). Missing from an older MRRocket.\n */\n unit?: string;\n}\n\n/** One condition of a flag's audience, on a property of the person (`identify(id, props)`), the id or the page. */\nexport interface FlagCondition {\n /** \"Email\", \"Plan\", \"Country\", \"id\", \"path\" … Matched against the person's properties without regard to case. */\n property: string;\n op: \"is\" | \"is not\" | \"in\" | \"not in\" | \"≥\" | \"in cohort\";\n values: string[];\n}\n\n/** Users who match every condition, of whom `rollout` percent get the flag. No conditions: everyone. */\nexport interface FlagConditionSet {\n conditions: FlagCondition[];\n /** 0 to 100. */\n rollout: number;\n}\n\nexport interface FlagConfig {\n key: string;\n /** Off: everyone gets the off side. */\n on: boolean;\n /** The first set a person matches decides; none matched: off. */\n sets: FlagConditionSet[];\n /** Multivariate flags: the variants and their split in percent (control included). Missing for an on/off flag. */\n variants?: { key: string; split: number; payload?: string }[];\n /**\n * The key of the A/B test the flag measures, while it runs (0.24.0). Reading the flag then records one `$exposure`\n * per page view; `flagExposure` says which version.\n */\n experiment?: string;\n}\n\n/** What a person is for flag conditions: their properties from identify(), their id and the page they are on. */\nexport type FlagPerson = Record<string, unknown>;\n\nconst propOf = (person: FlagPerson, name: string) => {\n const want = name.trim().toLowerCase();\n for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;\n return undefined;\n};\n\n/** `\"@acme.com\"` matches every address at that domain; anything else matches the whole value, without regard to case. */\nconst same = (actual: string, value: string) => {\n const a = actual.trim().toLowerCase();\n const v = value.trim().toLowerCase();\n return v.startsWith(\"@\") ? a.endsWith(v) : a === v;\n};\n\nconst matchesCondition = (c: FlagCondition, person: FlagPerson) => {\n // Cohorts live in MRRocket; a browser cannot know them, so a cohort condition never matches here.\n if (c.op === \"in cohort\") return false;\n const raw = propOf(person, c.property);\n const actual = raw === undefined || raw === null ? \"\" : String(raw);\n if (c.op === \"≥\") {\n const a = Number(actual);\n const b = Number(c.values[0]);\n return actual !== \"\" && Number.isFinite(a) && Number.isFinite(b) && a >= b;\n }\n const hit = actual !== \"\" && c.values.some((v) => same(actual, v));\n return c.op === \"is\" || c.op === \"in\" ? hit : !hit;\n};\n\n/**\n * The flag for one person: `false` (off), `true` (on, an on/off flag) or the variant's key (a multivariate flag). The\n * bucket is a stable hash of flag and person, so a person keeps their side as the rollout grows.\n */\nexport const evaluateFlag = (flag: FlagConfig, distinctId: string, person: FlagPerson = {}): boolean | string => {\n if (!flag.on) return false;\n const subject = { id: distinctId, ...person };\n const set = flag.sets.length ? flag.sets.find((s) => s.conditions.every((c) => matchesCondition(c, subject))) : { conditions: [], rollout: 100 };\n if (!set) return false;\n if (flagUnit(`${flag.key}:rollout:${distinctId}`) * 100 >= set.rollout) return false;\n if (!flag.variants?.length) return true;\n const u = flagUnit(`${flag.key}:variant:${distinctId}`) * 100;\n let acc = 0;\n for (const v of flag.variants) {\n acc += v.split;\n if (u < acc) return v.key;\n }\n return flag.variants[flag.variants.length - 1].key;\n};\n\n/** A flag of the config for this person; an unknown flag (or no config) is off. */\nexport const flagFor = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}) => {\n const flag = config?.flags?.find((f) => f.key === key);\n return flag ? evaluateFlag(flag, distinctId, person) : false;\n};\n\n/** The version id MRRocket counts at a position: \"control\" first, then \"a\", \"b\" … (`variantIndex` on the server). */\nexport const versionAt = (i: number): VariantId => (i <= 0 ? \"control\" : String.fromCharCode(96 + Math.min(i, 26)));\n\n/**\n * What reading a flag that measures a running test exposes (0.24.0): `{ experiment, variant }` for `$exposure`, or null\n * when the flag measures none or the person is not in the test (the flag is off, the person outside its audience, or a\n * multivariate flag's rollout leaves them out). A multivariate flag's variants count by position (the first is\n * control, then \"a\", \"b\" …); an on/off flag counts its rollout: on is \"a\", off is control.\n */\nexport const flagExposure = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}): { experiment: string; variant: VariantId } | null => {\n const flag = config?.flags?.find((f) => f.key === key);\n if (!flag?.experiment || !flag.on) return null;\n const subject = { id: distinctId, ...person };\n if (flag.sets.length && !flag.sets.some((s) => s.conditions.every((c) => matchesCondition(c, subject)))) return null;\n const value = evaluateFlag(flag, distinctId, person);\n if (flag.variants?.length) {\n const i = typeof value === \"string\" ? flag.variants.findIndex((v) => v.key === value) : -1;\n return i < 0 ? null : { experiment: flag.experiment, variant: versionAt(i) };\n }\n return { experiment: flag.experiment, variant: value === true ? \"a\" : \"control\" };\n};\n\n/** One JavaScript error as it goes over the wire to `POST /api/sdk/errors`. */\nexport interface ErrorReport {\n /** \"TypeError\", \"Error\" … */\n type: string;\n message: string;\n /** The raw stack, at most 8 KB. MRRocket parses it into frames. */\n stack?: string;\n /** \"onerror\" (uncaught), \"onunhandledrejection\" (a rejected promise nobody caught) or \"manual\" (captureError). */\n mechanism: \"onerror\" | \"onunhandledrejection\" | \"manual\";\n handled: boolean;\n url: string;\n ts: number;\n /** What happened just before: pages and clicks, newest last, at most 20. */\n crumbs?: { ts: number; type: \"navigation\" | \"click\" | \"lifecycle\"; message: string }[];\n /** Your release (a version or commit), from the provider's `release` prop. */\n release?: string;\n distinctId?: string;\n sessionId?: string;\n}\n\n/**\n * Session recordings of a product, from the config. Recording also needs the visitor's own replay consent\n * (`<CockpitProvider replay>` or `setConsent({ replay: true })`); without it nothing is recorded or buffered.\n */\nexport interface ReplayConfig {\n /**\n * Share of sessions uploaded from their start, 0 to 1 (default 0.1). The others keep only the last minute in\n * memory and upload it when something goes wrong: a JS error, a rage click, a `purchase…` or `checkout…` event.\n */\n sampleRate: number;\n}\n\n/**\n * What the SDK may send and store.\n * - \"cookieless\" (default): no cookie, no localStorage. The server counts visitors with a hash of key, date, IP and\n * user agent that changes every day; since 0.24.0 the config hands that hash over as `unit`, kept in memory only, so\n * tests assign by it and events carry it.\n * - \"cookies\": a persistent `ck_id` cookie identifies the visitor across visits, `ck_sid` holds the session.\n * - \"off\": nothing is sent and nothing is stored.\n */\nexport type ConsentMode = \"cookieless\" | \"cookies\" | \"off\";\n\n/** Sent once when a signed-in person withdraws analytics consent, and stored as nothing but that fact on their record. */\nexport const CONSENT_OFF_EVENT = \"$consent_off\";\n\n/**\n * What `setConsent` takes: a mode as before, or the parts to change. `replay` is the separate consent for session\n * recordings (default false); it applies only while analytics is not \"off\".\n *\n * setConsent(\"cookies\");\n * setConsent({ replay: true });\n * setConsent({ analytics: \"cookieless\", replay: false });\n */\nexport type ConsentChoice = ConsentMode | { analytics?: ConsentMode; replay?: boolean };\n\n/** The campaign parameters the SDK reads from the landing URL. */\nexport const UTM_KEYS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"] as const;\nexport type UtmKey = (typeof UTM_KEYS)[number];\n\n/** One event as it goes over the wire to `POST /api/sdk/events`. */\nexport interface CockpitEvent {\n event: string;\n /**\n * The visitor. In \"cookieless\" mode until identify() it is the config's `unit` (0.24.0, MRRocket's own daily visitor\n * hash, held in memory), or missing before the config has one: the server then makes that hash itself.\n */\n distinctId?: string;\n /** Ends after 30 minutes without an event. */\n sessionId?: string;\n props?: Record<string, unknown>;\n /** Milliseconds since the epoch. */\n ts: number;\n url?: string;\n /** `document.referrer` on the first page of a page load, the previous in-app URL after client-side navigation. */\n referrer?: string;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_term?: string;\n utm_content?: string;\n /** The screen size in CSS pixels (points on a phone). */\n screen?: { w: number; h: number };\n /** The app that sent it (React Native only): MRRocket stores it with the event and fills OS and device from it. */\n app?: AppContext;\n}\n\n/** Where a React Native event comes from. Every field is optional except the platform; nothing identifies the person. */\nexport interface AppContext {\n /** \"ios\" or \"android\" (React Native's `Platform.OS`). */\n platform: string;\n /** The app's version, like \"1.4.0\" (`expo-application`'s `nativeApplicationVersion`). */\n appVersion?: string;\n /** The build number, like \"42\". */\n build?: string;\n /** The OS version, like \"17.4\". */\n osVersion?: string;\n /** The device model, like \"iPhone 15 Pro\" (`expo-device`). */\n deviceModel?: string;\n /** \"phone\", \"tablet\", \"desktop\" or \"tv\" when `expo-device` knows it. */\n deviceType?: string;\n /** The first preferred locale, like \"de-DE\". */\n locale?: string;\n}\n\n/** The query parameter that forces variants, for previews in Cockpit: `?ck_preview=pricing-annual:a,home-hero:control`. */\nexport const PREVIEW_PARAM = \"ck_preview\";\n/** Set when Cockpit embeds the page: nothing is tracked, so previews never count as visits. */\nexport const EMBED_PARAM = \"ck_embed\";\n/**\n * 0.26.0, preview mode: `?mrr_preview=<token>` shows a change that waits for the owner's approval in MRRocket (new copy,\n * a test's version, a rewritten page) on the real page, for the before/after pictures of a request. The SDK reads the\n * change for the token from `GET /api/sdk/preview`, applies it like a shipped winner, and marks the page\n * (`PREVIEW_ATTR`). Nothing is tracked, recorded or stored on the device while the parameter is there.\n */\nexport const PREVIEW_TOKEN_PARAM = \"mrr_preview\";\n/** With `mrr_preview`: the owner edits the page's words in place (`?mrr_preview=<edit token>&mrr_edit=1`). */\nexport const PREVIEW_EDIT_PARAM = \"mrr_edit\";\n/** On `<html>`: \"loading\" while the change is read, \"ready\" once it is on the page, \"failed\" when it could not be read. */\nexport const PREVIEW_ATTR = \"data-mrr-preview\";\n/** On `<html>` beside \"ready\": what of the change found no place on the page, as a JSON list (missing when all did). */\nexport const PREVIEW_MISSED_ATTR = \"data-mrr-preview-missed\";\n/**\n * The words of an unseen status line the SDK adds beside the attributes (`<div role=\"status\" data-mrr-preview-status>`,\n * one transparent pixel): \"mrr-preview-ready\", then what was missed. A browser that can only wait for text and read the\n * page's outline (MRRocket's screenshot browser) knows by it that the change is on the page.\n */\nexport const PREVIEW_READY_TEXT = \"mrr-preview-ready\";\n/** The cookie that keeps a visitor in the same variant across visits. Only written in \"cookies\" mode. */\nexport const ID_COOKIE = \"ck_id\";\n/**\n * The headers a customer's server sends with `GET /api/sdk/config` (and the server key) so MRRocket makes the unit of\n * the visitor it renders for, not of the server itself (0.24.0, `getCockpitConfig({ headers })`).\n */\nexport const VISITOR_IP_HEADER = \"x-mrrocket-visitor-ip\";\nexport const VISITOR_UA_HEADER = \"x-mrrocket-visitor-ua\";\n/** The cookie that holds the session id in \"cookies\" mode. */\nexport const SESSION_COOKIE = \"ck_sid\";\n/** A session ends after this long without an event. */\nexport const SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\n/** The UTM parameters from a parameter lookup (`URLSearchParams.get` in a browser). Empty values are left out. */\nexport const utmFrom = (get: (name: string) => string | null | undefined): Partial<Record<UtmKey, string>> => {\n const out: Partial<Record<UtmKey, string>> = {};\n for (const key of UTM_KEYS) {\n const value = get(key)?.trim();\n if (value) out[key] = value.slice(0, 150);\n }\n return out;\n};\n\n/** The UTM parameters of a query string, like `\"?utm_source=x\"`. Empty values are left out. */\nexport const readUtm = (search: string): Partial<Record<UtmKey, string>> => {\n const params = new URLSearchParams(search);\n return utmFrom((k) => params.get(k));\n};\n\n/**\n * The query parameters of a URL or query string, without `URLSearchParams` (React Native's is incomplete): `+` is a\n * space, values are percent-decoded, the first of a repeated name wins.\n */\nexport const parseQuery = (url: string): Record<string, string> => {\n const out: Record<string, string> = {};\n const q = url.split(\"#\")[0];\n const at = q.indexOf(\"?\");\n if (at < 0) return out;\n const dec = (s: string) => {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n };\n for (const pair of q.slice(at + 1).split(\"&\")) {\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n const k = dec(eq < 0 ? pair : pair.slice(0, eq));\n if (k && !(k in out)) out[k] = eq < 0 ? \"\" : dec(pair.slice(eq + 1));\n }\n return out;\n};\n\n/** FNV-1a, 32 bit, mapped to [0, 1). Stable across server and browser. */\nexport const hashUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0) / 4294967296;\n};\n\n/**\n * FNV-1a with murmur3's finalizer, mapped to [0, 1): ids that differ only at the end (\"user-1\", \"user-2\") still spread\n * evenly, so a 30 % rollout reaches about 30 % of people. Flags only; experiments keep `hashUnit` so nobody switches.\n */\nexport const flagUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return (h >>> 0) / 4294967296;\n};\n\nconst weightOf = (v: VariantConfig) => (typeof v.weight === \"number\" && v.weight > 0 ? v.weight : 0);\n\n/**\n * The variant a visitor sees: a shipped winner, control while the experiment does not run, else a stable bucket by\n * visitor over the cumulative weights. A version with weight 0 (stopped while its test runs) is never picked, also not\n * as the remainder when the weights add up to a little less than 1; with no weight above 0 everyone gets control.\n */\nexport const assign = (experiment: ExperimentConfig, distinctId: string): VariantId => {\n const control = experiment.variants[0]?.id ?? \"control\";\n if (experiment.winner) return experiment.winner;\n if (experiment.status !== \"running\") return control;\n const u = hashUnit(`${experiment.key}:${distinctId}`);\n let acc = 0;\n let last: VariantId | undefined;\n for (const v of experiment.variants) {\n const w = weightOf(v);\n if (!w) continue;\n acc += w;\n last = v.id;\n if (u < acc) return v.id;\n }\n return last ?? control;\n};\n\n/**\n * The first version each running test gave an id in this page load or app session (0.24.0), in memory only. When the\n * config is read again mid-session (MRRocket moves traffic to the better version while a test runs) the visitor keeps\n * what they see until the next page load or app start. A shipped winner, a stopped test or a version that is gone\n * apply at once. Keyed by test and id, so `identify()` assigns the new id afresh.\n */\nexport type KeptVariants = Map<string, VariantId>;\n\n/** `assign`, kept for the session in `kept` when one is given. */\nexport const assignKept = (experiment: ExperimentConfig, distinctId: string, kept?: KeptVariants): VariantId => {\n if (!kept || experiment.winner || experiment.status !== \"running\") return assign(experiment, distinctId);\n const mark = `${experiment.key}\\n${distinctId}`;\n const was = kept.get(mark);\n if (was !== undefined && experiment.variants.some((v) => v.id === was)) return was;\n const id = assign(experiment, distinctId);\n kept.set(mark, id);\n return id;\n};\n\n/** One change to a page that marks nothing for MRRocket (a rewritten text, a word the owner edited on the page). */\nexport type PreviewOp =\n /** The words of one element. With `from`, only when the element still reads that (or already the new words). */\n | { op: \"set\"; selector: string; text: string; from?: string }\n /** The page's own text (the element whose paragraphs carry the most words) replaced by this HTML. */\n | { op: \"body\"; html: string }\n /** The browser tab's title and the description search engines read. */\n | { op: \"meta\"; title?: string; description?: string };\n\n/** What `GET /api/sdk/preview?token=…` answers: the waiting change, in the shapes the SDK already applies. */\nexport interface PreviewPayload {\n /** The request's title and the version shown (\"Variant B\"), for the edit bar. */\n title?: string;\n version?: string;\n /** Published copy as it will read once approved, by text id (`pricing.headline`). */\n texts?: Record<string, string>;\n /** Tests that are not running yet (or are changed by the request), added to the config or replacing theirs by key. */\n experiments?: ExperimentConfig[];\n /** The version of each test this preview shows, as `ck_preview` would force it. */\n force?: Record<string, VariantId>;\n /** Other parts of the config as they will be (paywalls, onboarding). */\n config?: Partial<Pick<CockpitConfig, \"paywalls\" | \"onboarding\" | \"onboardingAccent\" | \"cancelFlow\">>;\n ops?: PreviewOp[];\n /** The text ids the request changes: checked on the page, highlighted in edit mode. */\n changed?: string[];\n /** The token may save edits (`PREVIEW_EDIT_PARAM`). */\n edit?: boolean;\n}\n\n/**\n * The config with a waiting change on top, and the versions it forces: texts over the published ones, a test by its\n * key replacing the config's or added to it. Redirects are left out: a preview stays on the page it opened.\n */\nexport const withPreview = (config: CockpitConfig | null, p: PreviewPayload): { config: CockpitConfig; force: Record<string, VariantId> } => {\n const base: CockpitConfig = config ?? { project: \"\", experiments: [] };\n const added = (p.experiments ?? []).filter((e) => e && typeof e.key === \"string\" && Array.isArray(e.variants));\n const keys = new Set(added.map((e) => e.key));\n const { redirects: _left, ...rest } = base;\n return {\n config: {\n ...rest,\n ...(p.config ?? {}),\n experiments: [...base.experiments.filter((e) => !keys.has(e.key)), ...added],\n ...(base.texts || p.texts ? { texts: { ...(base.texts ?? {}), ...(p.texts ?? {}) } } : {}),\n },\n force: { ...(p.force ?? {}) },\n };\n};\n\n/** `\"a:b,c:d\"` → `{ a: \"b\", c: \"d\" }`. Ignores anything malformed. */\nexport const parsePreview = (value: string | string[] | null | undefined): Record<string, VariantId> => {\n const raw = Array.isArray(value) ? value[0] : value;\n if (!raw) return {};\n const out: Record<string, VariantId> = {};\n for (const pair of raw.split(\",\")) {\n const [key, variant] = pair.split(\":\");\n if (key && variant) out[key.trim()] = variant.trim();\n }\n return out;\n};\n\n/** A link that shows one variant of a page, for example in Cockpit's preview frames. */\nexport const previewHref = (url: string, forced: Record<string, VariantId>, embed = true) => {\n const [path, query = \"\"] = url.split(\"?\");\n const params = new URLSearchParams(query);\n const value = Object.entries(forced)\n .map(([k, v]) => `${k}:${v}`)\n .join(\",\");\n if (value) params.set(PREVIEW_PARAM, value);\n if (embed) params.set(EMBED_PARAM, \"1\");\n return `${path}?${params.toString()}`;\n};\n\n/** Whether a test is running (not a shipped winner, not stopped). */\nconst runs = (e: ExperimentConfig) => e.status === \"running\" && !e.winner;\n\n/**\n * Running tests that change the same text (0.24.0): per text id the running tests in config order; the first wins\n * (`textChanges` applies only its words, and only it is exposed by that text). Empty when none overlap.\n */\nexport const overlaps = (config: CockpitConfig | null): { text: string; keys: string[] }[] => {\n const by = new Map<string, string[]>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const id of new Set(e.variants.flatMap((v) => Object.keys(v.changes ?? {})))) {\n const keys = by.get(id) ?? [];\n if (!keys.includes(e.key)) keys.push(e.key);\n by.set(id, keys);\n }\n }\n return [...by.entries()].filter(([, keys]) => keys.length > 1).map(([text, keys]) => ({ text, keys }));\n};\n\nconst warnedOverlaps = new Set<string>();\n\n/**\n * Tells the developer once per overlap, in the console, which running tests change the same text and which one wins.\n * The React provider calls it in a development build; core stays free of `process` so it runs on Workers and Edge.\n */\nexport const warnOverlaps = (config: CockpitConfig | null) => {\n for (const { text, keys } of overlaps(config))\n for (const other of keys.slice(1)) {\n const id = `${text}|${keys[0]}|${other}`;\n if (warnedOverlaps.has(id)) continue;\n warnedOverlaps.add(id);\n console.warn(`[MRRocket] The running tests \"${keys[0]}\" and \"${other}\" both change the text \"${text}\". \"${keys[0]}\" comes first in the config and wins; \"${other}\" leaves that text alone.`);\n }\n};\n\n/** The running test that owns each text id: the first in config order that changes it. */\nconst textOwners = (config: CockpitConfig | null) => {\n const owner = new Map<string, string>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const v of e.variants) for (const id of Object.keys(v.changes ?? {})) if (!owner.has(id)) owner.set(id, e.key);\n }\n return owner;\n};\n\n/**\n * The experiments whose variants change the text `id`: showing that text is an exposure to them. Of running tests that\n * overlap on it only the first in config order counts (`overlaps`).\n */\nexport const experimentsOfText = (config: CockpitConfig | null, id: string) => {\n const owner = textOwners(config).get(id);\n return (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes) && (!runs(e) || e.key === owner)).map((e) => e.key);\n};\n\n/**\n * The variant for one experiment, from a forced preview first, then the config. Unknown experiments get control.\n * `distinctId` null (0.24.0): the visitor's id is not known yet (a cookieless page waiting for its `unit`, a server\n * render without one): a running test shows control and should record nothing; shipped winners apply. `kept` keeps\n * versions for the session (`assignKept`).\n */\nexport const resolveVariant = (key: string, config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants): VariantId => {\n if (preview[key]) return preview[key];\n const experiment = config?.experiments.find((e) => e.key === key);\n if (!experiment) return \"control\";\n if (distinctId === null && runs(experiment)) return experiment.variants[0]?.id ?? \"control\";\n return assignKept(experiment, distinctId ?? \"\", kept);\n};\n\n/**\n * Every text change that applies to this visitor: the published texts first, then the shipped winners, then the\n * running tests, each in config order. Control keeps the published (or the page's own) words, so only a non-control\n * variant (assigned, forced in a preview, or a shipped winner) changes them further. Two running tests on one text\n * (0.24.0): the first in config order wins and the other leaves that text alone, so neither group sees the other's\n * words (a console warning in development names both). A variant forced in a preview always shows.\n */\nexport const textChanges = (config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants) => {\n const out: Record<string, string> = { ...(config?.texts ?? {}) };\n const experiments = config?.experiments ?? [];\n const owner = textOwners(config);\n const changesOf = (e: ExperimentConfig) => {\n const id = resolveVariant(e.key, config, distinctId, preview, kept);\n if (id === (e.variants[0]?.id ?? \"control\")) return {};\n return e.variants.find((v) => v.id === id)?.changes ?? {};\n };\n for (const e of experiments) if (!runs(e) && !preview[e.key]) Object.assign(out, changesOf(e));\n for (const e of experiments) {\n if (!runs(e) || preview[e.key]) continue;\n for (const [id, words] of Object.entries(changesOf(e))) if (owner.get(id) === e.key) out[id] = words;\n }\n for (const e of experiments) if (preview[e.key]) Object.assign(out, changesOf(e));\n return out;\n};\n\n/**\n * The query parameter a redirect test adds to the variant's address (`ck_x=<test>:<variant>`): the page there records\n * the exposure and takes it out of the address bar. It also keeps that page from redirecting again.\n */\nexport const EXPOSURE_PARAM = \"ck_x\";\n\n/** What `redirectFor` decided: go to `to`, and/or the redirect test this page belongs to and the visitor's variant. */\nexport interface RedirectDecision {\n /** Where to send the visitor now. Missing for control, which stays on the page. */\n to?: string;\n /** The redirect test, while it runs: record `$exposure` for it (on this page for control, on `to` otherwise). */\n experiment?: string;\n variant?: VariantId;\n}\n\nconst pathOf = (p: string) => p.replace(/\\/+$/, \"\") || \"/\";\n\n/**\n * Where a page sends the visitor, before it shows: a page redirect set in MRRocket first, else a redirect test that runs\n * on this path (the visitor's variant, by the same stable assignment as every test). Null when nothing applies.\n *\n * - The new address keeps the page's query (UTM parameters) and its hash; a running test adds `ck_x=<test>:<variant>`,\n * so the page it lands on records the exposure (and never redirects again).\n * - `distinctId` null (no stable id, as on a server without the `ck_id` cookie): running tests are left to the browser,\n * page redirects and shipped winners still apply.\n * - A redirect to the page itself is ignored.\n */\nexport const redirectFor = (\n config: CockpitConfig | null,\n href: string,\n distinctId: string | null,\n preview: Record<string, VariantId> = {},\n kept?: KeptVariants,\n): RedirectDecision | null => {\n if (!config) return null;\n let here: URL;\n try {\n here = new URL(href);\n } catch {\n return null;\n }\n if (here.searchParams.has(EXPOSURE_PARAM)) return null;\n const path = pathOf(here.pathname);\n const go = (to: string, mark?: string) => {\n let t: URL;\n try {\n t = new URL(to, here);\n } catch {\n return undefined;\n }\n if (!/^https?:$/.test(t.protocol) || (t.origin === here.origin && pathOf(t.pathname) === path)) return undefined;\n here.searchParams.forEach((v, k) => {\n if (!t.searchParams.has(k)) t.searchParams.set(k, v);\n });\n if (mark) t.searchParams.set(EXPOSURE_PARAM, mark);\n if (!t.hash) t.hash = here.hash;\n return t.href;\n };\n for (const r of config.redirects ?? []) {\n const to = r.from && pathOf(r.from) === path ? go(r.to) : undefined;\n if (to) return { to };\n }\n for (const e of config.experiments) {\n if (!e.path || pathOf(e.path) !== path) continue;\n const running = e.status === \"running\" && !e.winner;\n if (running && distinctId === null && !preview[e.key]) return null;\n const variant = resolveVariant(e.key, config, distinctId, preview, kept);\n const url = e.variants.find((v) => v.id === variant)?.url;\n const to = url ? go(url, running ? `${e.key}:${variant}` : undefined) : undefined;\n return running ? { to, experiment: e.key, variant } : to ? { to } : null;\n }\n return null;\n};\n\n/** The test and variant a redirect test's `ck_x` names, when the config has them; null otherwise. */\nexport const exposureFrom = (config: CockpitConfig | null, value: string | null | undefined) => {\n const [key, variant] = (value ?? \"\").split(\":\");\n const e = config?.experiments.find((x) => x.key === key);\n return e && e.variants.some((v) => v.id === variant) ? { experiment: key, variant } : null;\n};\n\n/**\n * The MRRocket API host from `NEXT_PUBLIC_MRROCKET_HOST`. Written as a literal property access on purpose: Next.js\n * inlines `process.env.NEXT_PUBLIC_*` at build time, in the browser bundle and in the server bundle (also on\n * Cloudflare Workers), and only replaces the literal form. Without a bundler (or a `process`) it is undefined.\n */\nexport const envHost = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_HOST || undefined;\n } catch {\n return undefined;\n }\n};\n\n/** The public key from `NEXT_PUBLIC_MRROCKET_KEY`, the default for the `apiKey` prop. Same literal-access rule as `envHost`. */\nexport const envKey = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_KEY || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Where the API lives: the `host` prop, else `NEXT_PUBLIC_MRROCKET_HOST`, else \"\" (the page's own origin, which is how\n * MRRocket's own demo pages call it). Without a trailing slash.\n */\nexport const resolveHost = (host?: string) => (host ?? envHost() ?? \"\").trim().replace(/\\/+$/, \"\");\n\n/** A random visitor id. */\nexport const newDistinctId = () =>\n typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `ck_${Math.random().toString(36).slice(2)}${Date.now().toString(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,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/core.ts"],"sourcesContent":["/**\n * The part of the SDK that runs anywhere: experiment config, variant assignment, preview links and event shapes.\n * No React, no browser APIs, so the server helper, the proxy helper and the client share it.\n */\nimport type { CancelFlowConfig, OnboardingFlow } from \"./flows\";\nimport type { PaywallConfig } from \"./paywall\";\n\nexport type VariantId = string;\n\n/** This build of the SDK. Sent with the config request so MRRocket knows what the site runs (error tracking, flags). */\nexport const SDK_VERSION = \"0.29.2\";\n\n/** One variant of an experiment. `changes` replaces texts that the page marks with `<Text id>`. */\nexport interface VariantConfig {\n id: VariantId;\n /** Share of traffic, 0 to 1. The weights of an experiment add up to 1. */\n weight: number;\n changes?: Record<string, string>;\n /**\n * A redirect test: where this variant sends the visitor instead of the test's page (a path like \"/pricing-b\" or a\n * full address). Control has none and stays. SDK 0.7.0+.\n */\n url?: string;\n}\n\nexport interface ExperimentConfig {\n /** The experiment's key, the same as in Cockpit. */\n key: string;\n status: \"running\" | \"draft\" | \"stopped\";\n /** Control first. */\n variants: VariantConfig[];\n /** A winner that shipped: everyone gets it, and nobody is assigned anymore. */\n winner?: VariantId;\n /** A redirect test: the path of the page it runs on (\"/pricing\"). Visitors there are sent to their variant's `url`. */\n path?: string;\n}\n\n/** A page redirect set in MRRocket (Conversion › Landing pages › Redirect): everyone on `from` goes to `to`. SDK 0.7.0+. */\nexport interface RedirectConfig {\n /** A path of the site, like \"/old-pricing\". */\n from: string;\n /** A path or a full address. */\n to: string;\n}\n\nexport interface CockpitConfig {\n /** The product the public key belongs to. */\n project: string;\n /** The language the server chose for the words below, like \"de\" (`lang` on the request). SDK 0.21.0+. */\n lang?: string;\n /** The SDK's own words: English source word to translation (see words.ts). Absent for English. SDK 0.21.0+. */\n words?: Record<string, string>;\n experiments: ExperimentConfig[];\n /** The product's affiliate program: how many days a partner's referral is kept. Missing without a program. */\n referral?: { cookieDays: number };\n /** Session recordings: present only while the product records (Cockpit › Sessions). See `ReplayConfig`. */\n replay?: ReplayConfig;\n /** Feature flags of the product in Production (MRRocket › Build › Feature flags), evaluated by `useFlag` and `getFlag`. */\n flags?: FlagConfig[];\n /**\n * Published copy for texts the site marks (`<Text id>`, `data-ck-text`): a landing page's headline, subheadline and\n * button (`pricing.headline` …) and a paywall's (`paywall.<placement>.headline` …) as published in MRRocket. A\n * running test's variant changes them on top. Missing when nothing is published. SDK 0.5.0+.\n */\n texts?: Record<string, string>;\n /** The product's live cancel flow (MRRocket › Churn › Cancel flow), for `cancelFlow.open()`. SDK 0.7.0+. */\n cancelFlow?: CancelFlowConfig;\n /** The in-app steps of live onboarding flows (tours, checklists, modals). SDK 0.7.0+. */\n onboarding?: OnboardingFlow[];\n /** The product's brand color (\"#rrggbb\") for the onboarding dialogs when the app passes no accent. SDK 0.18.0+. */\n onboardingAccent?: string;\n /** A live Lifecycle journey has in-app messages: signed-in people ask `/api/sdk/inapp` for theirs. SDK 0.7.0+. */\n messages?: boolean;\n /** Page redirects set in MRRocket; the SDK sends visitors on before the page shows (`redirectFor`). SDK 0.7.0+. */\n redirects?: RedirectConfig[];\n /** Published paywalls with their pages, per placement (MRRocket › Conversion › Paywalls), for `paywall.open()`. SDK 0.14.0+. */\n paywalls?: PaywallConfig[];\n /**\n * The visitor's unit for A/B tests (0.24.0): the same daily visitor hash MRRocket counts a cookieless visitor by\n * (`v_…`, from the key, the day, the address and the browser, with a server secret). Without a signed-in id or the\n * `ck_id` cookie, tests and flags assign by it, so a visitor keeps their version all day across reloads and between\n * server render and browser, and their events carry it as `distinctId`. Held in memory only, never stored on the\n * device (a React Native app leaves it out of its cached config). Missing from an older MRRocket.\n */\n unit?: string;\n}\n\n/** One condition of a flag's audience, on a property of the person (`identify(id, props)`), the id or the page. */\nexport interface FlagCondition {\n /** \"Email\", \"Plan\", \"Country\", \"id\", \"path\" … Matched against the person's properties without regard to case. */\n property: string;\n op: \"is\" | \"is not\" | \"in\" | \"not in\" | \"≥\" | \"in cohort\";\n values: string[];\n}\n\n/** Users who match every condition, of whom `rollout` percent get the flag. No conditions: everyone. */\nexport interface FlagConditionSet {\n conditions: FlagCondition[];\n /** 0 to 100. */\n rollout: number;\n}\n\nexport interface FlagConfig {\n key: string;\n /** Off: everyone gets the off side. */\n on: boolean;\n /** The first set a person matches decides; none matched: off. */\n sets: FlagConditionSet[];\n /** Multivariate flags: the variants and their split in percent (control included). Missing for an on/off flag. */\n variants?: { key: string; split: number; payload?: string }[];\n /**\n * The key of the A/B test the flag measures, while it runs (0.24.0). Reading the flag then records one `$exposure`\n * per page view; `flagExposure` says which version.\n */\n experiment?: string;\n}\n\n/** What a person is for flag conditions: their properties from identify(), their id and the page they are on. */\nexport type FlagPerson = Record<string, unknown>;\n\nconst propOf = (person: FlagPerson, name: string) => {\n const want = name.trim().toLowerCase();\n for (const [k, v] of Object.entries(person)) if (k.toLowerCase() === want) return v;\n return undefined;\n};\n\n/** `\"@acme.com\"` matches every address at that domain; anything else matches the whole value, without regard to case. */\nconst same = (actual: string, value: string) => {\n const a = actual.trim().toLowerCase();\n const v = value.trim().toLowerCase();\n return v.startsWith(\"@\") ? a.endsWith(v) : a === v;\n};\n\nconst matchesCondition = (c: FlagCondition, person: FlagPerson) => {\n // Cohorts live in MRRocket; a browser cannot know them, so a cohort condition never matches here.\n if (c.op === \"in cohort\") return false;\n const raw = propOf(person, c.property);\n const actual = raw === undefined || raw === null ? \"\" : String(raw);\n if (c.op === \"≥\") {\n const a = Number(actual);\n const b = Number(c.values[0]);\n return actual !== \"\" && Number.isFinite(a) && Number.isFinite(b) && a >= b;\n }\n const hit = actual !== \"\" && c.values.some((v) => same(actual, v));\n return c.op === \"is\" || c.op === \"in\" ? hit : !hit;\n};\n\n/**\n * The flag for one person: `false` (off), `true` (on, an on/off flag) or the variant's key (a multivariate flag). The\n * bucket is a stable hash of flag and person, so a person keeps their side as the rollout grows.\n */\nexport const evaluateFlag = (flag: FlagConfig, distinctId: string, person: FlagPerson = {}): boolean | string => {\n if (!flag.on) return false;\n const subject = { id: distinctId, ...person };\n const set = flag.sets.length ? flag.sets.find((s) => s.conditions.every((c) => matchesCondition(c, subject))) : { conditions: [], rollout: 100 };\n if (!set) return false;\n if (flagUnit(`${flag.key}:rollout:${distinctId}`) * 100 >= set.rollout) return false;\n if (!flag.variants?.length) return true;\n const u = flagUnit(`${flag.key}:variant:${distinctId}`) * 100;\n let acc = 0;\n for (const v of flag.variants) {\n acc += v.split;\n if (u < acc) return v.key;\n }\n return flag.variants[flag.variants.length - 1].key;\n};\n\n/** A flag of the config for this person; an unknown flag (or no config) is off. */\nexport const flagFor = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}) => {\n const flag = config?.flags?.find((f) => f.key === key);\n return flag ? evaluateFlag(flag, distinctId, person) : false;\n};\n\n/** The version id MRRocket counts at a position: \"control\" first, then \"a\", \"b\" … (`variantIndex` on the server). */\nexport const versionAt = (i: number): VariantId => (i <= 0 ? \"control\" : String.fromCharCode(96 + Math.min(i, 26)));\n\n/**\n * What reading a flag that measures a running test exposes (0.24.0): `{ experiment, variant }` for `$exposure`, or null\n * when the flag measures none or the person is not in the test (the flag is off, the person outside its audience, or a\n * multivariate flag's rollout leaves them out). A multivariate flag's variants count by position (the first is\n * control, then \"a\", \"b\" …); an on/off flag counts its rollout: on is \"a\", off is control.\n */\nexport const flagExposure = (key: string, config: CockpitConfig | null, distinctId: string, person: FlagPerson = {}): { experiment: string; variant: VariantId } | null => {\n const flag = config?.flags?.find((f) => f.key === key);\n if (!flag?.experiment || !flag.on) return null;\n const subject = { id: distinctId, ...person };\n if (flag.sets.length && !flag.sets.some((s) => s.conditions.every((c) => matchesCondition(c, subject)))) return null;\n const value = evaluateFlag(flag, distinctId, person);\n if (flag.variants?.length) {\n const i = typeof value === \"string\" ? flag.variants.findIndex((v) => v.key === value) : -1;\n return i < 0 ? null : { experiment: flag.experiment, variant: versionAt(i) };\n }\n return { experiment: flag.experiment, variant: value === true ? \"a\" : \"control\" };\n};\n\n/** One JavaScript error as it goes over the wire to `POST /api/sdk/errors`. */\nexport interface ErrorReport {\n /** \"TypeError\", \"Error\" … */\n type: string;\n message: string;\n /** The raw stack, at most 8 KB. MRRocket parses it into frames. */\n stack?: string;\n /** \"onerror\" (uncaught), \"onunhandledrejection\" (a rejected promise nobody caught) or \"manual\" (captureError). */\n mechanism: \"onerror\" | \"onunhandledrejection\" | \"manual\";\n handled: boolean;\n url: string;\n ts: number;\n /** What happened just before: pages and clicks, newest last, at most 20. */\n crumbs?: { ts: number; type: \"navigation\" | \"click\" | \"lifecycle\"; message: string }[];\n /** Your release (a version or commit), from the provider's `release` prop. */\n release?: string;\n distinctId?: string;\n sessionId?: string;\n}\n\n/**\n * Session recordings of a product, from the config. Recording also needs the visitor's own replay consent\n * (`<CockpitProvider replay>` or `setConsent({ replay: true })`); without it nothing is recorded or buffered.\n */\nexport interface ReplayConfig {\n /**\n * Share of sessions uploaded from their start, 0 to 1 (default 0.1). The others keep only the last minute in\n * memory and upload it when something goes wrong: a JS error, a rage click, a `purchase…` or `checkout…` event.\n */\n sampleRate: number;\n}\n\n/**\n * What the SDK may send and store.\n * - \"cookieless\" (default): no cookie, no localStorage. The server counts visitors with a hash of key, date, IP and\n * user agent that changes every day; since 0.24.0 the config hands that hash over as `unit`, kept in memory only, so\n * tests assign by it and events carry it.\n * - \"cookies\": a persistent `ck_id` cookie identifies the visitor across visits, `ck_sid` holds the session.\n * - \"off\": nothing is sent and nothing is stored.\n */\nexport type ConsentMode = \"cookieless\" | \"cookies\" | \"off\";\n\n/** Sent once when a signed-in person withdraws analytics consent, and stored as nothing but that fact on their record. */\nexport const CONSENT_OFF_EVENT = \"$consent_off\";\n\n/**\n * What `setConsent` takes: a mode as before, or the parts to change. `replay` is the separate consent for session\n * recordings (default false); it applies only while analytics is not \"off\".\n *\n * setConsent(\"cookies\");\n * setConsent({ replay: true });\n * setConsent({ analytics: \"cookieless\", replay: false });\n */\nexport type ConsentChoice = ConsentMode | { analytics?: ConsentMode; replay?: boolean };\n\n/** The campaign parameters the SDK reads from the landing URL. */\nexport const UTM_KEYS = [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"] as const;\nexport type UtmKey = (typeof UTM_KEYS)[number];\n\n/** One event as it goes over the wire to `POST /api/sdk/events`. */\nexport interface CockpitEvent {\n event: string;\n /**\n * The visitor. In \"cookieless\" mode until identify() it is the config's `unit` (0.24.0, MRRocket's own daily visitor\n * hash, held in memory), or missing before the config has one: the server then makes that hash itself.\n */\n distinctId?: string;\n /** Ends after 30 minutes without an event. */\n sessionId?: string;\n props?: Record<string, unknown>;\n /** Milliseconds since the epoch. */\n ts: number;\n url?: string;\n /** `document.referrer` on the first page of a page load, the previous in-app URL after client-side navigation. */\n referrer?: string;\n utm_source?: string;\n utm_medium?: string;\n utm_campaign?: string;\n utm_term?: string;\n utm_content?: string;\n /** The screen size in CSS pixels (points on a phone). */\n screen?: { w: number; h: number };\n /** The app that sent it (React Native only): MRRocket stores it with the event and fills OS and device from it. */\n app?: AppContext;\n}\n\n/** Where a React Native event comes from. Every field is optional except the platform; nothing identifies the person. */\nexport interface AppContext {\n /** \"ios\" or \"android\" (React Native's `Platform.OS`). */\n platform: string;\n /** The app's version, like \"1.4.0\" (`expo-application`'s `nativeApplicationVersion`). */\n appVersion?: string;\n /** The build number, like \"42\". */\n build?: string;\n /** The OS version, like \"17.4\". */\n osVersion?: string;\n /** The device model, like \"iPhone 15 Pro\" (`expo-device`). */\n deviceModel?: string;\n /** \"phone\", \"tablet\", \"desktop\" or \"tv\" when `expo-device` knows it. */\n deviceType?: string;\n /** The first preferred locale, like \"de-DE\". */\n locale?: string;\n}\n\n/** The query parameter that forces variants, for previews in Cockpit: `?ck_preview=pricing-annual:a,home-hero:control`. */\nexport const PREVIEW_PARAM = \"ck_preview\";\n/** Set when Cockpit embeds the page: nothing is tracked, so previews never count as visits. */\nexport const EMBED_PARAM = \"ck_embed\";\n/**\n * 0.26.0, preview mode: `?mrr_preview=<token>` shows a change that waits for the owner's approval in MRRocket (new copy,\n * a test's version, a rewritten page) on the real page, for the before/after pictures of a request. The SDK reads the\n * change for the token from `GET /api/sdk/preview`, applies it like a shipped winner, and marks the page\n * (`PREVIEW_ATTR`). Nothing is tracked, recorded or stored on the device while the parameter is there.\n */\nexport const PREVIEW_TOKEN_PARAM = \"mrr_preview\";\n/** With `mrr_preview`: the owner edits the page's words in place (`?mrr_preview=<edit token>&mrr_edit=1`). */\nexport const PREVIEW_EDIT_PARAM = \"mrr_edit\";\n/** On `<html>`: \"loading\" while the change is read, \"ready\" once it is on the page, \"failed\" when it could not be read. */\nexport const PREVIEW_ATTR = \"data-mrr-preview\";\n/** On `<html>` beside \"ready\": what of the change found no place on the page, as a JSON list (missing when all did). */\nexport const PREVIEW_MISSED_ATTR = \"data-mrr-preview-missed\";\n/**\n * The words of an unseen status line the SDK adds beside the attributes (`<div role=\"status\" data-mrr-preview-status>`,\n * one transparent pixel): \"mrr-preview-ready\", then what was missed. A browser that can only wait for text and read the\n * page's outline (MRRocket's screenshot browser) knows by it that the change is on the page.\n */\nexport const PREVIEW_READY_TEXT = \"mrr-preview-ready\";\n/** The cookie that keeps a visitor in the same variant across visits. Only written in \"cookies\" mode. */\nexport const ID_COOKIE = \"ck_id\";\n/**\n * The headers a customer's server sends with `GET /api/sdk/config` (and the server key) so MRRocket makes the unit of\n * the visitor it renders for, not of the server itself (0.24.0, `getCockpitConfig({ headers })`).\n */\nexport const VISITOR_IP_HEADER = \"x-mrrocket-visitor-ip\";\nexport const VISITOR_UA_HEADER = \"x-mrrocket-visitor-ua\";\n/** The cookie that holds the session id in \"cookies\" mode. */\nexport const SESSION_COOKIE = \"ck_sid\";\n/** A session ends after this long without an event. */\nexport const SESSION_TIMEOUT_MS = 30 * 60 * 1000;\n\n/** The UTM parameters from a parameter lookup (`URLSearchParams.get` in a browser). Empty values are left out. */\nexport const utmFrom = (get: (name: string) => string | null | undefined): Partial<Record<UtmKey, string>> => {\n const out: Partial<Record<UtmKey, string>> = {};\n for (const key of UTM_KEYS) {\n const value = get(key)?.trim();\n if (value) out[key] = value.slice(0, 150);\n }\n return out;\n};\n\n/** The UTM parameters of a query string, like `\"?utm_source=x\"`. Empty values are left out. */\nexport const readUtm = (search: string): Partial<Record<UtmKey, string>> => {\n const params = new URLSearchParams(search);\n return utmFrom((k) => params.get(k));\n};\n\n/**\n * The query parameters of a URL or query string, without `URLSearchParams` (React Native's is incomplete): `+` is a\n * space, values are percent-decoded, the first of a repeated name wins.\n */\nexport const parseQuery = (url: string): Record<string, string> => {\n const out: Record<string, string> = {};\n const q = url.split(\"#\")[0];\n const at = q.indexOf(\"?\");\n if (at < 0) return out;\n const dec = (s: string) => {\n try {\n return decodeURIComponent(s.replace(/\\+/g, \" \"));\n } catch {\n return s;\n }\n };\n for (const pair of q.slice(at + 1).split(\"&\")) {\n if (!pair) continue;\n const eq = pair.indexOf(\"=\");\n const k = dec(eq < 0 ? pair : pair.slice(0, eq));\n if (k && !(k in out)) out[k] = eq < 0 ? \"\" : dec(pair.slice(eq + 1));\n }\n return out;\n};\n\n/** FNV-1a, 32 bit, mapped to [0, 1). Stable across server and browser. */\nexport const hashUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0) / 4294967296;\n};\n\n/**\n * FNV-1a with murmur3's finalizer, mapped to [0, 1): ids that differ only at the end (\"user-1\", \"user-2\") still spread\n * evenly, so a 30 % rollout reaches about 30 % of people. Flags only; experiments keep `hashUnit` so nobody switches.\n */\nexport const flagUnit = (input: string) => {\n let h = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n h ^= input.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return (h >>> 0) / 4294967296;\n};\n\nconst weightOf = (v: VariantConfig) => (typeof v.weight === \"number\" && v.weight > 0 ? v.weight : 0);\n\n/**\n * The variant a visitor sees: a shipped winner, control while the experiment does not run, else a stable bucket by\n * visitor over the cumulative weights. A version with weight 0 (stopped while its test runs) is never picked, also not\n * as the remainder when the weights add up to a little less than 1; with no weight above 0 everyone gets control.\n */\nexport const assign = (experiment: ExperimentConfig, distinctId: string): VariantId => {\n const control = experiment.variants[0]?.id ?? \"control\";\n if (experiment.winner) return experiment.winner;\n if (experiment.status !== \"running\") return control;\n const u = hashUnit(`${experiment.key}:${distinctId}`);\n let acc = 0;\n let last: VariantId | undefined;\n for (const v of experiment.variants) {\n const w = weightOf(v);\n if (!w) continue;\n acc += w;\n last = v.id;\n if (u < acc) return v.id;\n }\n return last ?? control;\n};\n\n/**\n * The first version each running test gave an id in this page load or app session (0.24.0), in memory only. When the\n * config is read again mid-session (MRRocket moves traffic to the better version while a test runs) the visitor keeps\n * what they see until the next page load or app start. A shipped winner, a stopped test or a version that is gone\n * apply at once. Keyed by test and id, so `identify()` assigns the new id afresh.\n */\nexport type KeptVariants = Map<string, VariantId>;\n\n/** `assign`, kept for the session in `kept` when one is given. */\nexport const assignKept = (experiment: ExperimentConfig, distinctId: string, kept?: KeptVariants): VariantId => {\n if (!kept || experiment.winner || experiment.status !== \"running\") return assign(experiment, distinctId);\n const mark = `${experiment.key}\\n${distinctId}`;\n const was = kept.get(mark);\n if (was !== undefined && experiment.variants.some((v) => v.id === was)) return was;\n const id = assign(experiment, distinctId);\n kept.set(mark, id);\n return id;\n};\n\n/** One change to a page that marks nothing for MRRocket (a rewritten text, a word the owner edited on the page). */\nexport type PreviewOp =\n /** The words of one element. With `from`, only when the element still reads that (or already the new words). */\n | { op: \"set\"; selector: string; text: string; from?: string }\n /** The page's own text (the element whose paragraphs carry the most words) replaced by this HTML. */\n | { op: \"body\"; html: string }\n /** The browser tab's title and the description search engines read. */\n | { op: \"meta\"; title?: string; description?: string };\n\n/** What `GET /api/sdk/preview?token=…` answers: the waiting change, in the shapes the SDK already applies. */\nexport interface PreviewPayload {\n /** The request's title and the version shown (\"Variant B\"), for the edit bar. */\n title?: string;\n version?: string;\n /** Published copy as it will read once approved, by text id (`pricing.headline`). */\n texts?: Record<string, string>;\n /** Tests that are not running yet (or are changed by the request), added to the config or replacing theirs by key. */\n experiments?: ExperimentConfig[];\n /** The version of each test this preview shows, as `ck_preview` would force it. */\n force?: Record<string, VariantId>;\n /** Other parts of the config as they will be (paywalls, onboarding). */\n config?: Partial<Pick<CockpitConfig, \"paywalls\" | \"onboarding\" | \"onboardingAccent\" | \"cancelFlow\">>;\n ops?: PreviewOp[];\n /** The text ids the request changes: checked on the page, highlighted in edit mode. */\n changed?: string[];\n /** The token may save edits (`PREVIEW_EDIT_PARAM`). */\n edit?: boolean;\n}\n\n/**\n * The config with a waiting change on top, and the versions it forces: texts over the published ones, a test by its\n * key replacing the config's or added to it. Redirects are left out: a preview stays on the page it opened.\n */\nexport const withPreview = (config: CockpitConfig | null, p: PreviewPayload): { config: CockpitConfig; force: Record<string, VariantId> } => {\n const base: CockpitConfig = config ?? { project: \"\", experiments: [] };\n const added = (p.experiments ?? []).filter((e) => e && typeof e.key === \"string\" && Array.isArray(e.variants));\n const keys = new Set(added.map((e) => e.key));\n const { redirects: _left, ...rest } = base;\n return {\n config: {\n ...rest,\n ...(p.config ?? {}),\n experiments: [...base.experiments.filter((e) => !keys.has(e.key)), ...added],\n ...(base.texts || p.texts ? { texts: { ...(base.texts ?? {}), ...(p.texts ?? {}) } } : {}),\n },\n force: { ...(p.force ?? {}) },\n };\n};\n\n/** `\"a:b,c:d\"` → `{ a: \"b\", c: \"d\" }`. Ignores anything malformed. */\nexport const parsePreview = (value: string | string[] | null | undefined): Record<string, VariantId> => {\n const raw = Array.isArray(value) ? value[0] : value;\n if (!raw) return {};\n const out: Record<string, VariantId> = {};\n for (const pair of raw.split(\",\")) {\n const [key, variant] = pair.split(\":\");\n if (key && variant) out[key.trim()] = variant.trim();\n }\n return out;\n};\n\n/** A link that shows one variant of a page, for example in Cockpit's preview frames. */\nexport const previewHref = (url: string, forced: Record<string, VariantId>, embed = true) => {\n const [path, query = \"\"] = url.split(\"?\");\n const params = new URLSearchParams(query);\n const value = Object.entries(forced)\n .map(([k, v]) => `${k}:${v}`)\n .join(\",\");\n if (value) params.set(PREVIEW_PARAM, value);\n if (embed) params.set(EMBED_PARAM, \"1\");\n return `${path}?${params.toString()}`;\n};\n\n/** Whether a test is running (not a shipped winner, not stopped). */\nconst runs = (e: ExperimentConfig) => e.status === \"running\" && !e.winner;\n\n/**\n * Running tests that change the same text (0.24.0): per text id the running tests in config order; the first wins\n * (`textChanges` applies only its words, and only it is exposed by that text). Empty when none overlap.\n */\nexport const overlaps = (config: CockpitConfig | null): { text: string; keys: string[] }[] => {\n const by = new Map<string, string[]>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const id of new Set(e.variants.flatMap((v) => Object.keys(v.changes ?? {})))) {\n const keys = by.get(id) ?? [];\n if (!keys.includes(e.key)) keys.push(e.key);\n by.set(id, keys);\n }\n }\n return [...by.entries()].filter(([, keys]) => keys.length > 1).map(([text, keys]) => ({ text, keys }));\n};\n\nconst warnedOverlaps = new Set<string>();\n\n/**\n * Tells the developer once per overlap, in the console, which running tests change the same text and which one wins.\n * The React provider calls it in a development build; core stays free of `process` so it runs on Workers and Edge.\n */\nexport const warnOverlaps = (config: CockpitConfig | null) => {\n for (const { text, keys } of overlaps(config))\n for (const other of keys.slice(1)) {\n const id = `${text}|${keys[0]}|${other}`;\n if (warnedOverlaps.has(id)) continue;\n warnedOverlaps.add(id);\n console.warn(`[MRRocket] The running tests \"${keys[0]}\" and \"${other}\" both change the text \"${text}\". \"${keys[0]}\" comes first in the config and wins; \"${other}\" leaves that text alone.`);\n }\n};\n\n/** The running test that owns each text id: the first in config order that changes it. */\nconst textOwners = (config: CockpitConfig | null) => {\n const owner = new Map<string, string>();\n for (const e of config?.experiments ?? []) {\n if (!runs(e)) continue;\n for (const v of e.variants) for (const id of Object.keys(v.changes ?? {})) if (!owner.has(id)) owner.set(id, e.key);\n }\n return owner;\n};\n\n/**\n * The experiments whose variants change the text `id`: showing that text is an exposure to them. Of running tests that\n * overlap on it only the first in config order counts (`overlaps`).\n */\nexport const experimentsOfText = (config: CockpitConfig | null, id: string) => {\n const owner = textOwners(config).get(id);\n return (config?.experiments ?? []).filter((e) => e.variants.some((v) => v.changes && id in v.changes) && (!runs(e) || e.key === owner)).map((e) => e.key);\n};\n\n/**\n * The variant for one experiment, from a forced preview first, then the config. Unknown experiments get control.\n * `distinctId` null (0.24.0): the visitor's id is not known yet (a cookieless page waiting for its `unit`, a server\n * render without one): a running test shows control and should record nothing; shipped winners apply. `kept` keeps\n * versions for the session (`assignKept`).\n */\nexport const resolveVariant = (key: string, config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants): VariantId => {\n if (preview[key]) return preview[key];\n const experiment = config?.experiments.find((e) => e.key === key);\n if (!experiment) return \"control\";\n if (distinctId === null && runs(experiment)) return experiment.variants[0]?.id ?? \"control\";\n return assignKept(experiment, distinctId ?? \"\", kept);\n};\n\n/**\n * Every text change that applies to this visitor: the published texts first, then the shipped winners, then the\n * running tests, each in config order. Control keeps the published (or the page's own) words, so only a non-control\n * variant (assigned, forced in a preview, or a shipped winner) changes them further. Two running tests on one text\n * (0.24.0): the first in config order wins and the other leaves that text alone, so neither group sees the other's\n * words (a console warning in development names both). A variant forced in a preview always shows.\n */\nexport const textChanges = (config: CockpitConfig | null, distinctId: string | null, preview: Record<string, VariantId>, kept?: KeptVariants) => {\n const out: Record<string, string> = { ...(config?.texts ?? {}) };\n const experiments = config?.experiments ?? [];\n const owner = textOwners(config);\n const changesOf = (e: ExperimentConfig) => {\n const id = resolveVariant(e.key, config, distinctId, preview, kept);\n if (id === (e.variants[0]?.id ?? \"control\")) return {};\n return e.variants.find((v) => v.id === id)?.changes ?? {};\n };\n for (const e of experiments) if (!runs(e) && !preview[e.key]) Object.assign(out, changesOf(e));\n for (const e of experiments) {\n if (!runs(e) || preview[e.key]) continue;\n for (const [id, words] of Object.entries(changesOf(e))) if (owner.get(id) === e.key) out[id] = words;\n }\n for (const e of experiments) if (preview[e.key]) Object.assign(out, changesOf(e));\n return out;\n};\n\n/**\n * The query parameter a redirect test adds to the variant's address (`ck_x=<test>:<variant>`): the page there records\n * the exposure and takes it out of the address bar. It also keeps that page from redirecting again.\n */\nexport const EXPOSURE_PARAM = \"ck_x\";\n\n/** What `redirectFor` decided: go to `to`, and/or the redirect test this page belongs to and the visitor's variant. */\nexport interface RedirectDecision {\n /** Where to send the visitor now. Missing for control, which stays on the page. */\n to?: string;\n /** The redirect test, while it runs: record `$exposure` for it (on this page for control, on `to` otherwise). */\n experiment?: string;\n variant?: VariantId;\n}\n\nconst pathOf = (p: string) => p.replace(/\\/+$/, \"\") || \"/\";\n\n/**\n * Where a page sends the visitor, before it shows: a page redirect set in MRRocket first, else a redirect test that runs\n * on this path (the visitor's variant, by the same stable assignment as every test). Null when nothing applies.\n *\n * - The new address keeps the page's query (UTM parameters) and its hash; a running test adds `ck_x=<test>:<variant>`,\n * so the page it lands on records the exposure (and never redirects again).\n * - `distinctId` null (no stable id, as on a server without the `ck_id` cookie): running tests are left to the browser,\n * page redirects and shipped winners still apply.\n * - A redirect to the page itself is ignored.\n */\nexport const redirectFor = (\n config: CockpitConfig | null,\n href: string,\n distinctId: string | null,\n preview: Record<string, VariantId> = {},\n kept?: KeptVariants,\n): RedirectDecision | null => {\n if (!config) return null;\n let here: URL;\n try {\n here = new URL(href);\n } catch {\n return null;\n }\n if (here.searchParams.has(EXPOSURE_PARAM)) return null;\n const path = pathOf(here.pathname);\n const go = (to: string, mark?: string) => {\n let t: URL;\n try {\n t = new URL(to, here);\n } catch {\n return undefined;\n }\n if (!/^https?:$/.test(t.protocol) || (t.origin === here.origin && pathOf(t.pathname) === path)) return undefined;\n here.searchParams.forEach((v, k) => {\n if (!t.searchParams.has(k)) t.searchParams.set(k, v);\n });\n if (mark) t.searchParams.set(EXPOSURE_PARAM, mark);\n if (!t.hash) t.hash = here.hash;\n return t.href;\n };\n for (const r of config.redirects ?? []) {\n const to = r.from && pathOf(r.from) === path ? go(r.to) : undefined;\n if (to) return { to };\n }\n for (const e of config.experiments) {\n if (!e.path || pathOf(e.path) !== path) continue;\n const running = e.status === \"running\" && !e.winner;\n if (running && distinctId === null && !preview[e.key]) return null;\n const variant = resolveVariant(e.key, config, distinctId, preview, kept);\n const url = e.variants.find((v) => v.id === variant)?.url;\n const to = url ? go(url, running ? `${e.key}:${variant}` : undefined) : undefined;\n return running ? { to, experiment: e.key, variant } : to ? { to } : null;\n }\n return null;\n};\n\n/** The test and variant a redirect test's `ck_x` names, when the config has them; null otherwise. */\nexport const exposureFrom = (config: CockpitConfig | null, value: string | null | undefined) => {\n const [key, variant] = (value ?? \"\").split(\":\");\n const e = config?.experiments.find((x) => x.key === key);\n return e && e.variants.some((v) => v.id === variant) ? { experiment: key, variant } : null;\n};\n\n/**\n * The MRRocket API host from `NEXT_PUBLIC_MRROCKET_HOST`. Written as a literal property access on purpose: Next.js\n * inlines `process.env.NEXT_PUBLIC_*` at build time, in the browser bundle and in the server bundle (also on\n * Cloudflare Workers), and only replaces the literal form. Without a bundler (or a `process`) it is undefined.\n */\nexport const envHost = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_HOST || undefined;\n } catch {\n return undefined;\n }\n};\n\n/** The public key from `NEXT_PUBLIC_MRROCKET_KEY`, the default for the `apiKey` prop. Same literal-access rule as `envHost`. */\nexport const envKey = (): string | undefined => {\n try {\n return process.env.NEXT_PUBLIC_MRROCKET_KEY || undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Where the API lives: the `host` prop, else `NEXT_PUBLIC_MRROCKET_HOST`, else \"\" (the page's own origin, which is how\n * MRRocket's own demo pages call it). Without a trailing slash.\n */\nexport const resolveHost = (host?: string) => (host ?? envHost() ?? \"\").trim().replace(/\\/+$/, \"\");\n\n/** A random visitor id. */\nexport const newDistinctId = () =>\n typeof crypto !== \"undefined\" && \"randomUUID\" in crypto ? crypto.randomUUID() : `ck_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;\n"],"mappings":";AAUO,IAAM,cAAc;AA8G3B,IAAM,SAAS,CAAC,QAAoB,SAAiB;AACjD,QAAM,OAAO,KAAK,KAAK,EAAE,YAAY;AACrC,aAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,MAAM,EAAG,KAAI,EAAE,YAAY,MAAM,KAAM,QAAO;AAClF,SAAO;AACX;AAGA,IAAM,OAAO,CAAC,QAAgB,UAAkB;AAC5C,QAAM,IAAI,OAAO,KAAK,EAAE,YAAY;AACpC,QAAM,IAAI,MAAM,KAAK,EAAE,YAAY;AACnC,SAAO,EAAE,WAAW,GAAG,IAAI,EAAE,SAAS,CAAC,IAAI,MAAM;AACrD;AAEA,IAAM,mBAAmB,CAAC,GAAkB,WAAuB;AAE/D,MAAI,EAAE,OAAO,YAAa,QAAO;AACjC,QAAM,MAAM,OAAO,QAAQ,EAAE,QAAQ;AACrC,QAAM,SAAS,QAAQ,UAAa,QAAQ,OAAO,KAAK,OAAO,GAAG;AAClE,MAAI,EAAE,OAAO,UAAK;AACd,UAAM,IAAI,OAAO,MAAM;AACvB,UAAM,IAAI,OAAO,EAAE,OAAO,CAAC,CAAC;AAC5B,WAAO,WAAW,MAAM,OAAO,SAAS,CAAC,KAAK,OAAO,SAAS,CAAC,KAAK,KAAK;AAAA,EAC7E;AACA,QAAM,MAAM,WAAW,MAAM,EAAE,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ,CAAC,CAAC;AACjE,SAAO,EAAE,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,CAAC;AACnD;AAMO,IAAM,eAAe,CAAC,MAAkB,YAAoB,SAAqB,CAAC,MAAwB;AAC7G,MAAI,CAAC,KAAK,GAAI,QAAO;AACrB,QAAM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,QAAQ,EAAE;AAG1F,IAAM,gBAAgB,MACzB,OAAO,WAAW,eAAe,gBAAgB,SAAS,OAAO,WAAW,IAAI,MAAM,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,CAAC,CAAC,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;","names":[]}
|
package/dist/preview.js
CHANGED
|
@@ -62,10 +62,20 @@ var pageLooks = (doc, box) => {
|
|
|
62
62
|
const looks = /* @__PURE__ */ new Map();
|
|
63
63
|
const read = (root) => {
|
|
64
64
|
if (!root) return;
|
|
65
|
+
const counts = /* @__PURE__ */ new Map();
|
|
65
66
|
for (const el of below(root)) {
|
|
66
67
|
if (looks.has(el.tagName) || el.closest("header, footer, nav, aside, [data-mrr-bar]")) continue;
|
|
67
68
|
const c = el.getAttribute("class")?.trim();
|
|
68
|
-
if (c)
|
|
69
|
+
if (!c) continue;
|
|
70
|
+
const byClass = counts.get(el.tagName) ?? /* @__PURE__ */ new Map();
|
|
71
|
+
byClass.set(c, (byClass.get(c) ?? 0) + 1);
|
|
72
|
+
counts.set(el.tagName, byClass);
|
|
73
|
+
}
|
|
74
|
+
for (const [tag, byClass] of counts) {
|
|
75
|
+
let best = "";
|
|
76
|
+
let most = 0;
|
|
77
|
+
for (const [c, n] of byClass) if (n > most) [best, most] = [c, n];
|
|
78
|
+
looks.set(tag, best);
|
|
69
79
|
}
|
|
70
80
|
};
|
|
71
81
|
read(box);
|