UNPKG

khulnasoft.com

Version:

Development tools for Khulnasoft CMS integration

10 lines 245 kB
"use strict";var de=Object.create;var S=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var ye=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Se=(e,t)=>{for(var r in t)S(e,r,{get:t[r],enumerable:!0})},I=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of me(t))!he.call(e,i)&&i!==r&&S(e,i,{get:()=>t[i],enumerable:!(n=ge(t,i))||n.enumerable});return e};var f=(e,t,r)=>(r=e!=null?de(fe(e)):{},I(t||!e||!e.__esModule?S(r,"default",{value:e,enumerable:!0}):r,e)),ve=e=>I(S({},"__esModule",{value:!0}),e);var U=ye((je,L)=>{"use strict";L.exports=function(){if(process.env.npm_config_user_agent)return Ce(process.env.npm_config_user_agent)};function Ce(e){let t=e.split(" ")[0],r=t.lastIndexOf("/"),n=t.substring(0,r);return{name:n==="npminstall"?"cnpm":n,version:t.substring(r+1)}}});var Ue={};Se(Ue,{createDevToolsServer:()=>ce,version:()=>_});module.exports=ve(Ue);var b=require("node:http");var R="preview-url";var D="framework",O="platform",F="node",k="/~khulnasoft-connect",v="/~khulnasoft-connected",w="/~khulnasoft-dev-tools",N="/~khulnasoft-dev-tools.js",u="/~khulnasoft-dev-tools-close";var be=f(U(),1);async function $(e){return(await e.hash(e.getAppRootDir())).substring(0,8)}async function V(e,t){let r=await e.readFile(t.filePath);return r==null?{diagnostics:[{messageText:`Error reading: ${t.filePath}`}],code:null,output:null}:P(e,{code:r,filePath:t.filePath,compilerOptions:t.compilerOptions})}function P(e,t){let r={diagnostics:[],code:t.code,output:null};try{let n=e.ts.transpileModule(t.code,{compilerOptions:t.compilerOptions,fileName:t.filePath??"module.tsx",reportDiagnostics:!0});n.diagnostics?.forEach(i=>{r.diagnostics.push({messageText:String(i.messageText)})}),r.output=n.outputText}catch(n){console.error("transpileModule",n),r.diagnostics.push({messageText:String(n)})}return r}var c=require("node:fs/promises");var A=require("node:os"),M=f(require("node:path"),1),Te=f(require("prettier"),1),Re=f(require("typescript"),1),De=f(require("launch-editor"),1);function we(){let e=(0,A.homedir)();return M.default.join(e,".config","khulnasoft","dev-tools.json")}async function j(){let e=we();try{let t=await(0,c.readFile)(e,"utf-8");if(typeof t=="string")return JSON.parse(t)}catch(t){if(t.code==="ENOENT")return null}return null}var h={CMS:"cms",VCP:"vcp",HYBRID:"hybrid"};var K=require("node:console"),B=require("node:http"),q=require("node:https");function d(e){let t=Date.now();return new Promise((r,n)=>{let s=Pe(e.url)({protocol:e.url.protocol,host:e.url.host,port:e.url.port,path:e.url.pathname+e.url.search,method:e.method,headers:e.headers},o=>{let l="";o.on("data",a=>{l+=a}),o.on("end",()=>{if((0,K.debug)(`${e.method} ${e.url.href}, duration: ${Date.now()-t}ms`),typeof o.statusCode=="number"&&o.statusCode>=200&&o.statusCode<300)if(typeof o.headers["content-type"]!="string"||!o.headers["content-type"].includes("application/json"))n(`Response from ${e.url.href} content-type is ${o.headers["content-type"]}`);else try{r(JSON.parse(l))}catch(a){n(`Response from ${e.url.href} is not valid JSON: ${l} ${a}`)}else n(`Request to ${e.url.href} failed with status ${o.statusCode}: ${l}`)})}).on("error",o=>{n(`Error fetching ${e.url.href}, ${o}`)});e.body&&(s.setHeader("Content-Type","application/json"),s.write(e.body)),s.end()})}function Pe(e){if(e.protocol==="https:")return q.request;if(e.protocol==="http:")return B.request;throw new Error(`Unsupported protocol ${e.protocol}`)}async function H(e){let t=new URL(`https://cdn.khulnasoft.com/api/v3/query/${e.publicApiKey}/${e.model}`);return t.searchParams.set("omit","meta.componentsUsed"),t.searchParams.set("apiKey",e.publicApiKey),t.searchParams.set("userAttributes.urlPath",e.pageUrl),t.searchParams.set("options.page.model",`"${e.model}"`),t.searchParams.set("cachebust","true"),(await d({url:t,method:"GET"}))[e.model]}async function J(e,t){if(t.kind===h.VCP)return!0;let r=new URL("https://cdn.khulnasoft.com/api/v2/admin"),n={query:`query { models { id name } }`};e.debug(`Get model id for model name "${t.model}"`);let s=(await d({url:r,method:"POST",headers:{Authorization:`Bearer ${t.privateAuthKey}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)})).data.models.find(a=>a.name===t.model);if(!s)return e.debug(`No model found for model name "${t.model}"`),!1;e.debug(`Data query, modelId: "${s.id}", urlPath: "${t.pageUrl}"`);let o=new URL("https://cdn.khulnasoft.com/api/v3/data");o.searchParams.set("limit","1"),o.searchParams.set("cachebust","true"),o.searchParams.set("collection","content"),o.searchParams.set("query.published.$ne","archived"),o.searchParams.set("query.query.$elemMatch.$and[0].property","urlPath"),o.searchParams.set("query.query.$elemMatch.$and[0].operator","is"),o.searchParams.set("query.query.$elemMatch.$and[0].value",t.pageUrl),o.searchParams.set("query.modelId",s.id),o.searchParams.set("apiKey",t.publicApiKey);let l=await d({url:o,method:"GET"});return e.debug(`Data results (${l.results.length}): ${o.href}`),l.results.length>0}async function G(e,t){let r=new URL(`https://cdn.khulnasoft.com/api/v3/content/${t.model}`);r.searchParams.set("apiKey",t.publicApiKey),r.searchParams.set("cachebust","true"),r.searchParams.set("cb",Date.now().toString()),t.pageUrl&&(r.searchParams.set("url",t.pageUrl),e.debug(`get model: "${t.model}", pageUrl: "${t.pageUrl}":`,r.href)),t.id&&(r.searchParams.set("query.id",t.id),e.debug(`get model: "${t.model}", id: "${t.id}":`,r.href));let n=await d({url:r,method:"GET"});return e.debug(`get content results: ${n.results.length}`),n}async function W(e,t){let r=new URL(`https://cdn.khulnasoft.com/api/v1/write/${t.model}`);e.debug(`writing "${t.model}" content:`,r.href),await d({url:r,method:"POST",headers:{Authorization:`Bearer ${t.privateAuthKey}`},body:t.body})}var g="page",Q="integration-welcome-screens",z="8d9ee72a33344b4b867918b442ebd0af";async function Y(e,t){let r=await G(e,{model:Q,publicApiKey:z,id:t.templateContentId});if(!Array.isArray(r?.results)||r.results.length===0||!r.results[0].data?.blocks)throw new Error(`No Khulnasoft content found for id ${t.templateContentId}`);let n=JSON.stringify(r.results[0].data.blocks),i=Ae(t.publicApiKey,t.pathname,t.title,n);await W(e,{privateAuthKey:t.privateAuthKey,model:g,body:i})}function Ae(e,t,r,n){return JSON.stringify({name:r,ownerId:e,published:"published",query:[{property:"urlPath",value:[t],operator:"is"}],data:{title:r,blocksString:n}})}async function X(e,t,r,n){e.debug(`connect khulnasoft with public key: ${t}`),e.publicApiKey=t;let i=e.closeAppServer(),s=await e.setPublicApiKey({publicApiKey:t});e.debug(`set public key: process.env.${s.envKey}=${t}`),process.env[s.envKey]=t;let o=await e.khulnasoftPageOptions();e.debug(`khulnasoft model: ${g}, path: ${o.pathname}, template: ${o.templateContentId}`);let l=await J(e,{model:g,pageUrl:o.pathname,publicApiKey:t,privateAuthKey:r,kind:n});if(!l){await Y(e,{templateContentId:o.templateContentId,pathname:o.pathname,title:o.title,publicApiKey:t,privateAuthKey:r});let p=5,y=0;for(;!l&&y<p;){await new Promise(ue=>setTimeout(ue,1e3));let x=await H({model:g,pageUrl:o.pathname,publicApiKey:t,privateAuthKey:r});y++,x&&x.length>0&&(l=!0)}}await i,e.debug("ensure khulnasoft setup");let a=[];n===h.VCP?a=await e.ensureFigmaImportPage():a=await e.ensureKhulnasoftSetup(),s.modifiedType&&a.push({filePath:s.file,modifiedType:s.modifiedType}),a.forEach(p=>{p.displayFilePath=e.relative(e.getAppRootDir(),p.filePath)}),a.sort((p,y)=>p.filePath.localeCompare(y.filePath)),a.length>0?(e.debug(`modified files: ${a.map(p=>p.displayFilePath).join(", ")}`),await e.restartAppServer(),await new Promise(p=>setTimeout(p,500))):e.debug("no modified files");let T={success:!0,pathname:o.localePathname||o.pathname,modifiedFiles:a,platform:e.platform(),kind:n};return n===h.VCP&&(T.pathname="/"),e.debug(`connected khulnasoft: ${T.pathname}`),T}async function Z(e){let t=await e.khulnasoftPageOptions();e.debug(`validateKhulnasoft, pathname: ${t.pathname}, localePathname: ${t.localePathname}, isValid: ${e.isValid}`);let r={isValid:e.isValid,pathname:t.localePathname||t.pathname,platform:e.platform()};if(e.isValid)return r;let n=await e.getPublicApiKey();return n.envValue?(e.debug(`public api key: ${n.envValue}, ${n.file}`),e.publicApiKey=n.envValue,e.debug("khulnasoft connection is valid"),r.isValid=!0,e.isValid=!0,r):(e.debug("missing public api key"),r)}async function ee(e,t){let r={type:t.type};switch(t.type){case"getCache":{r.data=await e.getCache();break}case"setCache":{await e.setCache(t.data);break}case"connectKhulnasoft":{r.data=await X(e,t.data.publicApiKey,t.data.privateAuthKey,t.data.kind);break}case"enableDevTools":{r.data=xe(e,t.data.enabled);break}case"getRegistry":{r.data=await e.getRegistry(t.data);break}case"launchEditor":{r.data=await e.launchEditor(t.data);break}case"validateKhulnasoft":{r.data=await Z(e);break}case"loadComponent":{r.data=await e.loadComponent(t.data);break}case"registerComponent":{r.data=await e.registerComponent(t.data),e.serverShouldRestart=!0;break}case"setComponentInfo":{r.data=await e.setRegisteredComponentInfo(t.data),e.serverShouldRestart=!0;break}case"setComponentInput":{r.data=await e.setRegisteredComponentInput(t.data),e.serverShouldRestart=!0;break}case"unregisterComponent":{r.data=await e.unregisterComponent(t.data),e.serverShouldRestart=!0;break}case"getFrameworks":{r.data=e.getFrameworks();break}case"readdir":{E(e,t.path)?r.data=await e.readdir(t.path,!0):r.errors=[`Invalid file request: ${t.path}`];break}case"readFile":{E(e,t.path)?r.data=await e.readFile(t.path):r.errors=[`Invalid file request: ${t.path}`];break}case"writeFile":{E(e,t.path)?await e.writeFile(t.path,t.content):r.errors=[`Invalid file request: ${t.path}`];break}case"ensureFigmaImportPage":{r.data=await e.ensureFigmaImportPage();break}case"transileFile":{r.data=await V(e,t);break}case"transileModule":{r.data=P(e,t);break}case"getPastSyncInfo":{r.data=await e.getPastSyncInfo?.(t.data);break}case"resyncSnippet":{r.data=await e.resyncSnippet?.(t.data);break}case"localConfig":{r.data=await j();break}default:{r.errors=[`Unknown request type: ${JSON.stringify(t)}`];let n=t}}return r}function E(e,t){if(!t||t.includes(".."))return!1;t=t.replace(/\\/g,"/");let r=t.split("/"),n=r[r.length-1];if(n.length>0){let i=n.split(".").pop();if(i&&(i=`.${i}`.toLocaleLowerCase(),i=i.split("?")[0],!_e.includes(i)))return!1}return Ee(e,t),!1}function Ee(e,t){if(!t)return!1;t=e.normalize(e.resolve(t));let r=e.getAppRootDir();return!(!t.startsWith(r)&&!t.includes("node_modules"))}var _e=[".js",".jsx",".ts",".tsx",".json",".css",".scss",".sass",".less",".html",".htm",".xml",".svg",".png",".jpg",".jpeg",".gif",".ico",".webp",".woff",".woff2",".ttf",".eot",".mp4",".webm",".ogg",".md",".txt",".csv",".pdf"];function xe(e,t){return!t&&e.serverShouldRestart&&setTimeout(()=>{console.log(` Restarting server after Khulnasoft Devtools update... `),e.restartAppServer()},10),e.enableAppWatch(!t),{enabled:t,platform:e.platform()}}async function te(e){return ne(e,`"use strict";(()=>{var Hr=Object.defineProperty;var qr=(t,e)=>{for(var n in e)Hr(t,n,{get:e[n],enumerable:!0})};var W=(t,e)=>{bt(t);let n=t.querySelector("aside");n.dataset.view=e,n.classList.remove("section-ready"),setTimeout(()=>{n.classList.add("section-ready")},200)},pn=t=>{Array.from(t.querySelectorAll(".back-button")).forEach(e=>{e.addEventListener("click",n=>{bt(t),n.preventDefault(),n.stopPropagation();let r=n.target;W(t,r?.dataset.back||"nav-home")})})},Tt=(t,e)=>{bt(t);let n=t.querySelector("aside"),r=document.createElement("div");r.className="ui-toast",r.innerHTML=e,n.appendChild(r),setTimeout(()=>{r.classList.add("ui-toast-show"),setTimeout(()=>{r.classList.remove("ui-toast-show"),setTimeout(()=>{r.remove()},500)},4e3)},30)},bt=t=>{let e=t.querySelector("aside");Array.from(e.querySelectorAll(".ui-toast")).forEach(r=>{r.classList.remove("ui-toast-show")})},ke=()=>{let t=fn();return localStorage.getItem(t)!=="true"},It=t=>{let e=fn();t?localStorage.removeItem(e):localStorage.setItem(e,"true")},fn=()=>jr("disableEdit"),jr=t=>\`khulnasoft.__LOCAL_APP_ID__.\${t}\`,mn=()=>{let e=document.body.querySelector("[khulnasoft-content-id]")?.getAttribute("khulnasoft-content-id");return Ee(e)},Ee=(t,e)=>{let n="/content";t&&(n+="/"+t+"/edit");let r=new URL(n,"https://khulnasoft.com");t&&e&&r.searchParams.set("selectedBlock",e);let i=new URL(location.pathname,location.href);return r.searchParams.set("overridePreviewUrl",i.href),r.href},Oe="__DEV_TOOLS_URL__",A={components:[],registryPath:"",registryDisplayPath:"",frameworks:[],dependencies:[],publicApiKey:void 0,devToolsVersion:""},J=t=>{A.components=t.components,A.registryPath=t.registryPath,A.registryDisplayPath=t.registryDisplayPath,A.dependencies=t.dependencies,A.publicApiKey=t.publicApiKey};function vn(t){let e=null,n=document.querySelector("khulnasoft-dev-tools-menu"),r=()=>{t.hide()},i=u=>{let c=u.target;if(!c){r();return}if(c.closest("khulnasoft-dev-tools-edit"))return;let a=c.closest("[khulnasoft-content-id]"),l=c.closest("[khulnasoft-id]");if(!a||!l){t.hide();return}let d=t.show(a,l);!d||d===e||(n.highlightOpener(),e=d)};document.addEventListener("pointerover",i,{passive:!0}),document.addEventListener("pointerleave",r,{passive:!0}),document.addEventListener("pointercancel",r,{passive:!0}),document.addEventListener("visibilitychange",r,{passive:!0}),window.addEventListener("popstate",r,{passive:!0});let o=history.pushState;history.pushState=function(...u){t.hide(),o.apply(this,u)};let s=history.replaceState;history.replaceState=function(...u){t.hide(),s.apply(this,u)}}var Ue=class extends HTMLElement{openInKhulnasoft=null;block=null;constructor(){super()}connectedCallback(){this.setAttribute("aria-hidden","true");let e=this.attachShadow({mode:"open"});e.innerHTML='<style>*,*:before,*:after{box-sizing:border-box}:host{--background-color: rgba(40, 40, 40, 1);--primary-color: rgba(72, 161, 255, 1);--primary-color-subdued: rgb(72, 161, 255, .6);--primary-color-highlight: rgb(126, 188, 255);--primary-contrast-color: white;--edit-color: #1d74e2;--edit-color-highlight: #1c6bd1;--edit-color-alpha: rgb(72, 161, 255, .15);--error-color: #ff2b55;--text-color: white;--text-color-highlight: white;--border-color: #454545;--button-background-color-hover: rgba(255, 255, 255, .1);--menu-width: 320px;--transition-time: .15s;--font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";font-family:var(--font-family);line-height:1.6}button{cursor:pointer;color:var(--text-color);-webkit-tap-highlight-color:transparent}input,select,button{font-family:var(--font-family)}:host{display:none;position:absolute;top:0;left:0;width:100%;height:100%;z-index:2147483646;user-select:none;pointer-events:none;color:var(--text-color)}#content-highlight,#block{position:absolute}#content-highlight{border:3px solid var(--primary-color);background-color:var(--primary-color-alpha)}a{position:absolute;top:-33px;left:0;display:block;padding:5px 10px 8px;pointer-events:auto;z-index:100;text-decoration:none}a:hover{text-decoration:none}a span{display:block;padding:3px 6px;font-size:10px;font-weight:300;border-radius:3px;text-align:center;text-decoration:none;pointer-events:none;background-color:var(--edit-color);color:var(--text-color);white-space:nowrap}a:hover span{background-color:var(--edit-color-highlight)}a:hover~.outline{border-color:var(--edit-color-highlight)}#open-in-editor{display:none}.outline{position:absolute;top:0;left:0;width:100%;height:100%;border:1px solid var(--edit-color);background-color:var(--edit-color-alpha)}</style><div id="block"> <a id="open-in-khulnasoft" target="khulnasoft"><span>Open In Khulnasoft</span></a> <a id="open-in-editor" href="#open-in-editor"><span>Open In Editor</span></a> <div class="outline"></div> </div>',this.openInKhulnasoft=e.getElementById("open-in-khulnasoft"),this.block=e.getElementById("block"),vn(this)}show(e,n){if(!ke())return this.hide(),null;let r=e.getAttribute("khulnasoft-content-id"),i=n.getAttribute("khulnasoft-id");if(!r||!i)return this.hide(),null;let o=this.block,s=this.openInKhulnasoft,u=n.getBoundingClientRect();o.style.top=u.top+window.scrollY-1+"px",o.style.left=u.left+window.scrollX+"px",o.style.width=u.width+"px",o.style.height=u.height+1+"px";let c=s.getBoundingClientRect();if(c.width>u.width){let a=c.width-u.width;s.style.left=a/2*-1+"px"}else s.style.left="";return s.href=Ee(r,i),this.style.display="block",i}hide(){this.style.display=""}};var gn="preview-url";var hn="_b-uid";var yn="/~khulnasoft-connect";var _n="/~khulnasoft-dev-tools";var En="https://cdn.khulnasoft.com/api/v1/proxy-api?url=https://api2.amplitude.com/2/httpapi";var Tn=()=>$({type:"validateKhulnasoft"}),ve=t=>$({type:"launchEditor",data:t}),bn=t=>$({type:"getRegistry",data:t}),In=t=>$({type:"loadComponent",data:t}),Sn=t=>$({type:"registerComponent",data:t}),xn=t=>$({type:"setComponentInfo",data:t}),Me=t=>$({type:"setComponentInput",data:t}),Ln=t=>$({type:"unregisterComponent",data:t}),wn=t=>$({type:"enableDevTools",data:{enabled:t}}),Cn=()=>$({type:"localConfig"}),$=async t=>{let e=new URL(_n,Oe),n;try{n=await fetch(e,{method:"POST",body:JSON.stringify(t)})}catch(i){throw console.error(\`Devtools Fetch Error, \${e.href}\`,i),new Error("Khulnasoft Devtools Fetch Error")}if((n.headers.get("content-type")||"").includes("application/json")){let i=await n.json();if(n.ok)return i.data;if(Array.isArray(i.errors)&&i.errors.length>0)throw i.errors.forEach(o=>console.error(o)),new Error(\`Khulnasoft Devtools Fetch Error: \${i.errors[0]}\`)}throw new Error(\`Khulnasoft Devtools Fetch Error: \${n.status}, \${await n.text()}\`)};var Pn=[{value:"boolean",text:"boolean"},{value:"color",text:"color (provides a color in hex or rgb)"},{value:"date",text:"date (same format as the Date constructor)"},{value:"email",text:"email"},{value:"file",text:"file (uploads a file and provides a url)"},{value:"list",text:"list (collection of items)"},{value:"longText",text:"longText (multiline text editor)"},{value:"number",text:"number"},{value:"object",text:"object (set of specific names and values)"},{value:"richText",text:"richText (provides value as html)"},{value:"string",text:"string"}],Ne=["color","date","email","file","longText","richText","string"],Be=["number"],Fe=["boolean"],Ve=["list"],He=["object"];function qe(t){return Ne.includes(t)?"string":Be.includes(t)?"number":Fe.includes(t)?"boolean":Ve.includes(t)?"array":He.includes(t)?"object":"string"}var $i=new Set(["about","accessKey","accessKeyLabel","asChild","autoCapitalize","autoCorrect","autoFocus","autoSave","blur","contentEditable","contextMenu","dangerouslySetInnerHTML","datatype","defaultChecked","defaultValue","dir","draggable","enterKeyHint","focus","form","formAction","formEncType","formMethod","formNoValidate","formTarget","inlist","innerText","inputMode","is","isContentEditable","itemID","itemProp","itemRef","itemScope","itemType","lang","nonce","offsetHeight","offsetLeft","offsetTop","offsetWidth","outerText","prefix","property","radioGroup","rel","resource","results","rev","role","security","slot","spellCheck","suppressContentEditableWarning","suppressHydrationWarning","tabIndex","translate","typeof","unselectable","vocab"].map(t=>t.toLowerCase()));var St=function(t,e){return St=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i])},St(t,e)};function V(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");St(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var v=function(){return v=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},v.apply(this,arguments)};function Te(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function p(t,e,n,r){function i(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,s){function u(l){try{a(r.next(l))}catch(d){s(d)}}function c(l){try{a(r.throw(l))}catch(d){s(d)}}function a(l){l.done?o(l.value):i(l.value).then(u,c)}a((r=r.apply(t,e||[])).next())})}function f(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,s;return s={next:u(0),throw:u(1),return:u(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function u(a){return function(l){return c([a,l])}}function c(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(n=0)),n;)try{if(r=1,i&&(o=a[0]&2?i.return:a[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,a[1])).done)return o;switch(i=0,o&&(a=[a[0]&2,o.value]),a[0]){case 0:case 1:o=a;break;case 4:return n.label++,{value:a[1],done:!1};case 5:n.label++,i=a[1],a=[0];continue;case 7:a=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(a[0]===6||a[0]===2)){n=0;continue}if(a[0]===3&&(!o||a[1]>o[0]&&a[1]<o[3])){n.label=a[1];break}if(a[0]===6&&n.label<o[1]){n.label=o[1],o=a;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(a);break}o[2]&&n.ops.pop(),n.trys.pop();continue}a=e.call(t,n)}catch(l){a=[6,l],i=0}finally{r=o=0}if(a[0]&5)throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}}function Y(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function L(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(u){s={error:u}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function q(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,o;r<i;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}var Rn="Event tracked successfully",Dn="Unexpected error occurred",An="Event rejected due to exceeded retry count",kn="Event skipped due to optOut config",On="Event rejected due to missing API key",Un="Invalid API key",Mn="Client not initialized";var Ge={};qr(Ge,{IdentifyOperation:()=>w,LogLevel:()=>M,OfflineDisabled:()=>Ke,RevenueProperty:()=>Q,ServerZone:()=>je,SpecialEventType:()=>ee,Status:()=>x});var w;(function(t){t.SET="$set",t.SET_ONCE="$setOnce",t.ADD="$add",t.APPEND="$append",t.PREPEND="$prepend",t.REMOVE="$remove",t.PREINSERT="$preInsert",t.POSTINSERT="$postInsert",t.UNSET="$unset",t.CLEAR_ALL="$clearAll"})(w||(w={}));var Q;(function(t){t.REVENUE_PRODUCT_ID="$productId",t.REVENUE_QUANTITY="$quantity",t.REVENUE_PRICE="$price",t.REVENUE_TYPE="$revenueType",t.REVENUE="$revenue"})(Q||(Q={}));var ee;(function(t){t.IDENTIFY="$identify",t.GROUP_IDENTIFY="$groupidentify",t.REVENUE="revenue_amount"})(ee||(ee={}));var M;(function(t){t[t.None=0]="None",t[t.Error=1]="Error",t[t.Warn=2]="Warn",t[t.Verbose=3]="Verbose",t[t.Debug=4]="Debug"})(M||(M={}));var je;(function(t){t.US="US",t.EU="EU"})(je||(je={}));var x;(function(t){t.Unknown="unknown",t.Skipped="skipped",t.Success="success",t.RateLimit="rate_limit",t.PayloadTooLarge="payload_too_large",t.Invalid="invalid",t.Failed="failed",t.Timeout="Timeout",t.SystemError="SystemError"})(x||(x={}));var Ke=null;var te=function(t,e,n){return e===void 0&&(e=0),n===void 0&&(n=x.Unknown),{event:t,code:e,message:n}};var X=function(t){return t?(t^Math.random()*16>>t/4).toString(16):(String(1e7)+String(-1e3)+String(-4e3)+String(-8e3)+String(-1e11)).replace(/[018]/g,X)};var Nn=function(){function t(e){this.client=e,this.queue=[],this.applying=!1,this.plugins=[]}return t.prototype.register=function(e,n){var r,i,o;return p(this,void 0,void 0,function(){return f(this,function(s){switch(s.label){case 0:return e.name=(r=e.name)!==null&&r!==void 0?r:X(),e.type=(i=e.type)!==null&&i!==void 0?i:"enrichment",[4,(o=e.setup)===null||o===void 0?void 0:o.call(e,n,this.client)];case 1:return s.sent(),this.plugins.push(e),[2]}})})},t.prototype.deregister=function(e){var n;return p(this,void 0,void 0,function(){var r,i;return f(this,function(o){switch(o.label){case 0:return r=this.plugins.findIndex(function(s){return s.name===e}),i=this.plugins[r],this.plugins.splice(r,1),[4,(n=i.teardown)===null||n===void 0?void 0:n.call(i)];case 1:return o.sent(),[2]}})})},t.prototype.reset=function(e){this.applying=!1;var n=this.plugins;n.map(function(r){var i;return(i=r.teardown)===null||i===void 0?void 0:i.call(r)}),this.plugins=[],this.client=e},t.prototype.push=function(e){var n=this;return new Promise(function(r){n.queue.push([e,r]),n.scheduleApply(0)})},t.prototype.scheduleApply=function(e){var n=this;this.applying||(this.applying=!0,setTimeout(function(){n.apply(n.queue.shift()).then(function(){n.applying=!1,n.queue.length>0&&n.scheduleApply(0)})},e))},t.prototype.apply=function(e){return p(this,void 0,void 0,function(){var n,r,i,o,s,u,c,y,g,a,l,d,m,y,g,T,h,_,U,b,k,F;return f(this,function(I){switch(I.label){case 0:if(!e)return[2];n=L(e,1),r=n[0],i=L(e,2),o=i[1],s=this.plugins.filter(function(S){return S.type==="before"}),I.label=1;case 1:I.trys.push([1,6,7,8]),u=Y(s),c=u.next(),I.label=2;case 2:return c.done?[3,5]:(y=c.value,y.execute?[4,y.execute(v({},r))]:[3,4]);case 3:if(g=I.sent(),g===null)return o({event:r,code:0,message:""}),[2];r=g,I.label=4;case 4:return c=u.next(),[3,2];case 5:return[3,8];case 6:return a=I.sent(),U={error:a},[3,8];case 7:try{c&&!c.done&&(b=u.return)&&b.call(u)}finally{if(U)throw U.error}return[7];case 8:l=this.plugins.filter(function(S){return S.type==="enrichment"||S.type===void 0}),I.label=9;case 9:I.trys.push([9,14,15,16]),d=Y(l),m=d.next(),I.label=10;case 10:return m.done?[3,13]:(y=m.value,y.execute?[4,y.execute(v({},r))]:[3,12]);case 11:if(g=I.sent(),g===null)return o({event:r,code:0,message:""}),[2];r=g,I.label=12;case 12:return m=d.next(),[3,10];case 13:return[3,16];case 14:return T=I.sent(),k={error:T},[3,16];case 15:try{m&&!m.done&&(F=d.return)&&F.call(d)}finally{if(k)throw k.error}return[7];case 16:return h=this.plugins.filter(function(S){return S.type==="destination"}),_=h.map(function(S){var O=v({},r);return S.execute(O).catch(function(B){return te(O,0,String(B))})}),Promise.all(_).then(function(S){var O=L(S,1),B=O[0],Z=B||te(r,100,"Event not tracked, no destination plugins on the instance");o(Z)}),[2]}})})},t.prototype.flush=function(){return p(this,void 0,void 0,function(){var e,n,r,i=this;return f(this,function(o){switch(o.label){case 0:return e=this.queue,this.queue=[],[4,Promise.all(e.map(function(s){return i.apply(s)}))];case 1:return o.sent(),n=this.plugins.filter(function(s){return s.type==="destination"}),r=n.map(function(s){return s.flush&&s.flush()}),[4,Promise.all(r)];case 2:return o.sent(),[2]}})})},t}();var xt="-",de="AMP",Lt="".concat(de,"_unsent"),wt="https://api2.amplitude.com/2/httpapi",Bn="https://api.eu.amplitude.com/2/httpapi",Fn="https://api2.amplitude.com/batch",Vn="https://api.eu.amplitude.com/batch";var Kr=1e3,We=function(t){if(Object.keys(t).length>Kr)return!1;for(var e in t){var n=t[e];if(!Ct(e,n))return!1}return!0},Ct=function(t,e){var n,r;if(typeof t!="string")return!1;if(Array.isArray(e)){var i=!0;try{for(var o=Y(e),s=o.next();!s.done;s=o.next()){var u=s.value;if(Array.isArray(u))return!1;if(typeof u=="object")i=i&&We(u);else if(!["number","string"].includes(typeof u))return!1;if(!i)return!1}}catch(c){n={error:c}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}}else{if(e==null)return!1;if(typeof e=="object")return We(e);if(!["number","string","boolean"].includes(typeof e))return!1}return!0};var G=function(){function t(){this._propertySet=new Set,this._properties={}}return t.prototype.getUserProperties=function(){return v({},this._properties)},t.prototype.set=function(e,n){return this._safeSet(w.SET,e,n),this},t.prototype.setOnce=function(e,n){return this._safeSet(w.SET_ONCE,e,n),this},t.prototype.append=function(e,n){return this._safeSet(w.APPEND,e,n),this},t.prototype.prepend=function(e,n){return this._safeSet(w.PREPEND,e,n),this},t.prototype.postInsert=function(e,n){return this._safeSet(w.POSTINSERT,e,n),this},t.prototype.preInsert=function(e,n){return this._safeSet(w.PREINSERT,e,n),this},t.prototype.remove=function(e,n){return this._safeSet(w.REMOVE,e,n),this},t.prototype.add=function(e,n){return this._safeSet(w.ADD,e,n),this},t.prototype.unset=function(e){return this._safeSet(w.UNSET,e,xt),this},t.prototype.clearAll=function(){return this._properties={},this._properties[w.CLEAR_ALL]=xt,this},t.prototype._safeSet=function(e,n,r){if(this._validate(e,n,r)){var i=this._properties[e];return i===void 0&&(i={},this._properties[e]=i),i[n]=r,this._propertySet.add(n),!0}return!1},t.prototype._validate=function(e,n,r){return this._properties[w.CLEAR_ALL]!==void 0||this._propertySet.has(n)?!1:e===w.ADD?typeof r=="number":e!==w.UNSET&&e!==w.REMOVE?Ct(n,r):!0},t}();var Hn=function(t,e,n){var r=typeof t=="string"?{event_type:t}:t;return v(v(v({},r),n),e&&{event_properties:e})},be=function(t,e){var n=v(v({},e),{event_type:ee.IDENTIFY,user_properties:t.getUserProperties()});return n},qn=function(t,e,n,r){var i,o=v(v({},r),{event_type:ee.GROUP_IDENTIFY,group_properties:n.getUserProperties(),groups:(i={},i[t]=e,i)});return o},jn=function(t,e,n){var r,i=new G;i.set(t,e);var o=v(v({},n),{event_type:ee.IDENTIFY,user_properties:i.getUserProperties(),groups:(r={},r[t]=e,r)});return o},Kn=function(t,e){return v(v({},e),{event_type:ee.REVENUE,event_properties:t.getEventProperties()})};var H=function(t){return{promise:t||Promise.resolve()}};var Pt=function(){function t(e){e===void 0&&(e="$default"),this.initializing=!1,this.q=[],this.dispatchQ=[],this.logEvent=this.track.bind(this),this.timeline=new Nn(this),this.name=e}return t.prototype._init=function(e){return p(this,void 0,void 0,function(){return f(this,function(n){switch(n.label){case 0:return this.config=e,this.timeline.reset(this),[4,this.runQueuedFunctions("q")];case 1:return n.sent(),[2]}})})},t.prototype.runQueuedFunctions=function(e){return p(this,void 0,void 0,function(){var n,r,i,o,s,u,c;return f(this,function(a){switch(a.label){case 0:n=this[e],this[e]=[],a.label=1;case 1:a.trys.push([1,6,7,8]),r=Y(n),i=r.next(),a.label=2;case 2:return i.done?[3,5]:(o=i.value,[4,o()]);case 3:a.sent(),a.label=4;case 4:return i=r.next(),[3,2];case 5:return[3,8];case 6:return s=a.sent(),u={error:s},[3,8];case 7:try{i&&!i.done&&(c=r.return)&&c.call(r)}finally{if(u)throw u.error}return[7];case 8:return[2]}})})},t.prototype.track=function(e,n,r){var i=Hn(e,n,r);return H(this.dispatch(i))},t.prototype.identify=function(e,n){var r=be(e,n);return H(this.dispatch(r))},t.prototype.groupIdentify=function(e,n,r,i){var o=qn(e,n,r,i);return H(this.dispatch(o))},t.prototype.setGroup=function(e,n,r){var i=jn(e,n,r);return H(this.dispatch(i))},t.prototype.revenue=function(e,n){var r=Kn(e,n);return H(this.dispatch(r))},t.prototype.add=function(e){return this.config?H(this.timeline.register(e,this.config)):(this.q.push(this.add.bind(this,e)),H())},t.prototype.remove=function(e){return this.config?H(this.timeline.deregister(e)):(this.q.push(this.remove.bind(this,e)),H())},t.prototype.dispatchWithCallback=function(e,n){if(!this.config)return n(te(e,0,Mn));this.process(e).then(n)},t.prototype.dispatch=function(e){return p(this,void 0,void 0,function(){var n=this;return f(this,function(r){return this.config?[2,this.process(e)]:[2,new Promise(function(i){n.dispatchQ.push(n.dispatchWithCallback.bind(n,e,i))})]})})},t.prototype.process=function(e){return p(this,void 0,void 0,function(){var i,n,r,i;return f(this,function(o){switch(o.label){case 0:return o.trys.push([0,2,,3]),this.config.optOut?[2,te(e,0,kn)]:[4,this.timeline.push(e)];case 1:return i=o.sent(),i.code===200?this.config.loggerProvider.log(i.message):i.code===100?this.config.loggerProvider.warn(i.message):this.config.loggerProvider.error(i.message),[2,i];case 2:return n=o.sent(),r=String(n),this.config.loggerProvider.error(r),i=te(e,0,r),[2,i];case 3:return[2]}})})},t.prototype.setOptOut=function(e){if(!this.config){this.q.push(this.setOptOut.bind(this,!!e));return}this.config.optOut=!!e},t.prototype.flush=function(){return H(this.timeline.flush())},t}();var $e=function(){function t(){this.productId="",this.quantity=1,this.price=0}return t.prototype.setProductId=function(e){return this.productId=e,this},t.prototype.setQuantity=function(e){return e>0&&(this.quantity=e),this},t.prototype.setPrice=function(e){return this.price=e,this},t.prototype.setRevenueType=function(e){return this.revenueType=e,this},t.prototype.setRevenue=function(e){return this.revenue=e,this},t.prototype.setEventProperties=function(e){return We(e)&&(this.properties=e),this},t.prototype.getEventProperties=function(){var e=this.properties?v({},this.properties):{};return e[Q.REVENUE_PRODUCT_ID]=this.productId,e[Q.REVENUE_QUANTITY]=this.quantity,e[Q.REVENUE_PRICE]=this.price,e[Q.REVENUE_TYPE]=this.revenueType,e[Q.REVENUE]=this.revenue,e},t}();var Gn=function(t,e){var n=Math.max(e,1);return t.reduce(function(r,i,o){var s=Math.floor(o/n);return r[s]||(r[s]=[]),r[s].push(i),r},[])};var Ye="Amplitude Logger ",Ie=function(){function t(){this.logLevel=M.None}return t.prototype.disable=function(){this.logLevel=M.None},t.prototype.enable=function(e){e===void 0&&(e=M.Warn),this.logLevel=e},t.prototype.log=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.logLevel<M.Verbose||console.log("".concat(Ye,"[Log]: ").concat(e.join(" ")))},t.prototype.warn=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.logLevel<M.Warn||console.warn("".concat(Ye,"[Warn]: ").concat(e.join(" ")))},t.prototype.error=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.logLevel<M.Error||console.error("".concat(Ye,"[Error]: ").concat(e.join(" ")))},t.prototype.debug=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];this.logLevel<M.Debug||console.log("".concat(Ye,"[Debug]: ").concat(e.join(" ")))},t}();var Qe=function(){return{flushMaxRetries:12,flushQueueSize:200,flushIntervalMillis:1e4,instanceName:"$default_instance",logLevel:M.Warn,loggerProvider:new Ie,offline:!1,optOut:!1,serverUrl:wt,serverZone:"US",useBatch:!1}},Rt=function(){function t(e){var n,r,i,o;this._optOut=!1;var s=Qe();this.apiKey=e.apiKey,this.flushIntervalMillis=(n=e.flushIntervalMillis)!==null&&n!==void 0?n:s.flushIntervalMillis,this.flushMaxRetries=e.flushMaxRetries||s.flushMaxRetries,this.flushQueueSize=e.flushQueueSize||s.flushQueueSize,this.instanceName=e.instanceName||s.instanceName,this.loggerProvider=e.loggerProvider||s.loggerProvider,this.logLevel=(r=e.logLevel)!==null&&r!==void 0?r:s.logLevel,this.minIdLength=e.minIdLength,this.plan=e.plan,this.ingestionMetadata=e.ingestionMetadata,this.offline=e.offline!==void 0?e.offline:s.offline,this.optOut=(i=e.optOut)!==null&&i!==void 0?i:s.optOut,this.serverUrl=e.serverUrl,this.serverZone=e.serverZone||s.serverZone,this.storageProvider=e.storageProvider,this.transportProvider=e.transportProvider,this.useBatch=(o=e.useBatch)!==null&&o!==void 0?o:s.useBatch,this.loggerProvider.enable(this.logLevel);var u=Dt(e.serverUrl,e.serverZone,e.useBatch);this.serverZone=u.serverZone,this.serverUrl=u.serverUrl}return Object.defineProperty(t.prototype,"optOut",{get:function(){return this._optOut},set:function(e){this._optOut=e},enumerable:!1,configurable:!0}),t}();var Gr=function(t,e){return t==="EU"?e?Vn:Bn:e?Fn:wt},Dt=function(t,e,n){if(t===void 0&&(t=""),e===void 0&&(e=Qe().serverZone),n===void 0&&(n=Qe().useBatch),t)return{serverUrl:t,serverZone:void 0};var r=["US","EU"].includes(e)?e:Qe().serverZone;return{serverZone:r,serverUrl:Gr(r,n)}};function Wr(t){return t instanceof Error?t.message:String(t)}function Xe(t){var e="";try{"body"in t&&(e=JSON.stringify(t.body,null,2))}catch{}return e}var At=function(){function t(){this.name="amplitude",this.type="destination",this.retryTimeout=1e3,this.throttleTimeout=3e4,this.storageKey="",this.scheduled=null,this.queue=[]}return t.prototype.setup=function(e){var n;return p(this,void 0,void 0,function(){var r,i=this;return f(this,function(o){switch(o.label){case 0:return this.config=e,this.storageKey="".concat(Lt,"_").concat(this.config.apiKey.substring(0,10)),[4,(n=this.config.storageProvider)===null||n===void 0?void 0:n.get(this.storageKey)];case 1:return r=o.sent(),this.saveEvents(),r&&r.length>0&&Promise.all(r.map(function(s){return i.execute(s)})).catch(),[2,Promise.resolve(void 0)]}})})},t.prototype.execute=function(e){var n=this;return new Promise(function(r){var i={event:e,attempts:0,callback:function(o){return r(o)},timeout:0};n.addToQueue(i)})},t.prototype.addToQueue=function(){for(var e=this,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=n.filter(function(o){return o.attempts<e.config.flushMaxRetries?(o.attempts+=1,!0):(e.fulfillRequest([o],500,An),!1)});i.forEach(function(o){if(e.queue=e.queue.concat(o),o.timeout===0){e.schedule(e.config.flushIntervalMillis);return}setTimeout(function(){o.timeout=0,e.schedule(0)},o.timeout)}),this.saveEvents()},t.prototype.schedule=function(e){var n=this;this.scheduled||this.config.offline||(this.scheduled=setTimeout(function(){n.flush(!0).then(function(){n.queue.length>0&&n.schedule(e)})},e))},t.prototype.flush=function(e){return e===void 0&&(e=!1),p(this,void 0,void 0,function(){var n,r,i,o=this;return f(this,function(s){switch(s.label){case 0:return this.config.offline?(this.config.loggerProvider.debug("Skipping flush while offline."),[2]):(n=[],r=[],this.queue.forEach(function(u){return u.timeout===0?n.push(u):r.push(u)}),this.queue=r,this.scheduled&&(clearTimeout(this.scheduled),this.scheduled=null),i=Gn(n,this.config.flushQueueSize),[4,Promise.all(i.map(function(u){return o.send(u,e)}))]);case 1:return s.sent(),[2]}})})},t.prototype.send=function(e,n){return n===void 0&&(n=!0),p(this,void 0,void 0,function(){var r,i,o,s,u;return f(this,function(c){switch(c.label){case 0:if(!this.config.apiKey)return[2,this.fulfillRequest(e,400,On)];r={api_key:this.config.apiKey,events:e.map(function(a){var l=a.event,d=l.extra,m=Te(l,["extra"]);return m}),options:{min_id_length:this.config.minIdLength},client_upload_time:new Date().toISOString()},c.label=1;case 1:return c.trys.push([1,3,,4]),i=Dt(this.config.serverUrl,this.config.serverZone,this.config.useBatch).serverUrl,[4,this.config.transportProvider.send(i,r)];case 2:return o=c.sent(),o===null?(this.fulfillRequest(e,0,Dn),[2]):n?(this.handleResponse(o,e),[3,4]):("body"in o?this.fulfillRequest(e,o.statusCode,"".concat(o.status,": ").concat(Xe(o))):this.fulfillRequest(e,o.statusCode,o.status),[2]);case 3:return s=c.sent(),u=Wr(s),this.config.loggerProvider.error(u),this.fulfillRequest(e,0,u),[3,4];case 4:return[2]}})})},t.prototype.handleResponse=function(e,n){var r=e.status;switch(r){case x.Success:{this.handleSuccessResponse(e,n);break}case x.Invalid:{this.handleInvalidResponse(e,n);break}case x.PayloadTooLarge:{this.handlePayloadTooLargeResponse(e,n);break}case x.RateLimit:{this.handleRateLimitResponse(e,n);break}default:{this.config.loggerProvider.warn(\`{code: 0, error: "Status '\`.concat(r,"' provided for ").concat(n.length,' events"}')),this.handleOtherResponse(n);break}}},t.prototype.handleSuccessResponse=function(e,n){this.fulfillRequest(n,e.statusCode,Rn)},t.prototype.handleInvalidResponse=function(e,n){var r=this;if(e.body.missingField||e.body.error.startsWith(Un)){this.fulfillRequest(n,e.statusCode,e.body.error);return}var i=q(q(q(q([],L(Object.values(e.body.eventsWithInvalidFields)),!1),L(Object.values(e.body.eventsWithMissingFields)),!1),L(Object.values(e.body.eventsWithInvalidIdLengths)),!1),L(e.body.silencedEvents),!1).flat(),o=new Set(i),s=n.filter(function(u,c){if(o.has(c)){r.fulfillRequest([u],e.statusCode,e.body.error);return}return!0});s.length>0&&this.config.loggerProvider.warn(Xe(e)),this.addToQueue.apply(this,q([],L(s),!1))},t.prototype.handlePayloadTooLargeResponse=function(e,n){if(n.length===1){this.fulfillRequest(n,e.statusCode,e.body.error);return}this.config.loggerProvider.warn(Xe(e)),this.config.flushQueueSize/=2,this.addToQueue.apply(this,q([],L(n),!1))},t.prototype.handleRateLimitResponse=function(e,n){var r=this,i=Object.keys(e.body.exceededDailyQuotaUsers),o=Object.keys(e.body.exceededDailyQuotaDevices),s=e.body.throttledEvents,u=new Set(i),c=new Set(o),a=new Set(s),l=n.filter(function(d,m){if(d.event.user_id&&u.has(d.event.user_id)||d.event.device_id&&c.has(d.event.device_id)){r.fulfillRequest([d],e.statusCode,e.body.error);return}return a.has(m)&&(d.timeout=r.throttleTimeout),!0});l.length>0&&this.config.loggerProvider.warn(Xe(e)),this.addToQueue.apply(this,q([],L(l),!1))},t.prototype.handleOtherResponse=function(e){var n=this;this.addToQueue.apply(this,q([],L(e.map(function(r){return r.timeout=r.attempts*n.retryTimeout,r})),!1))},t.prototype.fulfillRequest=function(e,n,r){this.saveEvents(),e.forEach(function(i){return i.callback(te(i.event,n,r))})},t.prototype.saveEvents=function(){if(this.config.storageProvider){var e=Array.from(this.queue.map(function(n){return n.event}));this.config.storageProvider.set(this.storageKey,e)}},t}();var $r=function(t){t===void 0&&(t=0);var e=new Error().stack||"";return e.split(\` \`).slice(2+t).map(function(n){return n.trim()})},C=function(t){return function(){var e=v({},t.config),n=e.loggerProvider,r=e.logLevel;return{logger:n,logLevel:r}}},Yr=function(t,e){var n,r;e=e.replace(/\\[(\\w+)\\]/g,".$1"),e=e.replace(/^\\./,"");try{for(var i=Y(e.split(".")),o=i.next();!o.done;o=i.next()){var s=o.value;if(s in t)t=t[s];else return}}catch(u){n={error:u}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return t},P=function(t,e){return function(){var n,r,i={};try{for(var o=Y(e),s=o.next();!s.done;s=o.next()){var u=s.value;i[u]=Yr(t,u)}}catch(c){n={error:c}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return i}},R=function(t,e,n,r,i){return i===void 0&&(i=null),function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var u=n(),c=u.logger,a=u.logLevel;if(a&&a<M.Debug||!a||!c)return t.apply(i,o);var l={type:"invoke public method",name:e,args:o,stacktrace:$r(1),time:{start:new Date().toISOString()},states:{}};r&&l.states&&(l.states.before=r());var d=t.apply(i,o);return d&&d.promise?d.promise.then(function(){r&&l.states&&(l.states.after=r()),l.time&&(l.time.end=new Date().toISOString()),c.debug(JSON.stringify(l,null,2))}):(r&&l.states&&(l.states.after=r()),l.time&&(l.time.end=new Date().toISOString()),c.debug(JSON.stringify(l,null,2))),d}};var ze=function(){function t(){this.memoryStorage=new Map}return t.prototype.isEnabled=function(){return p(this,void 0,void 0,function(){return f(this,function(e){return[2,!0]})})},t.prototype.get=function(e){return p(this,void 0,void 0,function(){return f(this,function(n){return[2,this.memoryStorage.get(e)]})})},t.prototype.getRaw=function(e){return p(this,void 0,void 0,function(){var n;return f(this,function(r){switch(r.label){case 0:return[4,this.get(e)];case 1:return n=r.sent(),[2,n?JSON.stringify(n):void 0]}})})},t.prototype.set=function(e,n){return p(this,void 0,void 0,function(){return f(this,function(r){return this.memoryStorage.set(e,n),[2]})})},t.prototype.remove=function(e){return p(this,void 0,void 0,function(){return f(this,function(n){return this.memoryStorage.delete(e),[2]})})},t.prototype.reset=function(){return p(this,void 0,void 0,function(){return f(this,function(e){return this.memoryStorage.clear(),[2]})})},t}();var pe=function(){function t(){}return t.prototype.send=function(e,n){return Promise.resolve(null)},t.prototype.buildResponse=function(e){var n,r,i,o,s,u,c,a,l,d,m,y,g,T,h,_,U,b,k,F,I,S;if(typeof e!="object")return null;var O=e.code||0,B=this.buildStatus(O);switch(B){case x.Success:return{status:B,statusCode:O,body:{eventsIngested:(n=e.events_ingested)!==null&&n!==void 0?n:0,payloadSizeBytes:(r=e.payload_size_bytes)!==null&&r!==void 0?r:0,serverUploadTime:(i=e.server_upload_time)!==null&&i!==void 0?i:0}};case x.Invalid:return{status:B,statusCode:O,body:{error:(o=e.error)!==null&&o!==void 0?o:"",missingField:(s=e.missing_field)!==null&&s!==void 0?s:"",eventsWithInvalidFields:(u=e.events_with_invalid_fields)!==null&&u!==void 0?u:{},eventsWithMissingFields:(c=e.events_with_missing_fields)!==null&&c!==void 0?c:{},eventsWithInvalidIdLengths:(a=e.events_with_invalid_id_lengths)!==null&&a!==void 0?a:{},epsThreshold:(l=e.eps_threshold)!==null&&l!==void 0?l:0,exceededDailyQuotaDevices:(d=e.exceeded_daily_quota_devices)!==null&&d!==void 0?d:{},silencedDevices:(m=e.silenced_devices)!==null&&m!==void 0?m:[],silencedEvents:(y=e.silenced_events)!==null&&y!==void 0?y:[],throttledDevices:(g=e.throttled_devices)!==null&&g!==void 0?g:{},throttledEvents:(T=e.throttled_events)!==null&&T!==void 0?T:[]}};case x.PayloadTooLarge:return{status:B,statusCode:O,body:{error:(h=e.error)!==null&&h!==void 0?h:""}};case x.RateLimit:return{status:B,statusCode:O,body:{error:(_=e.error)!==null&&_!==void 0?_:"",epsThreshold:(U=e.eps_threshold)!==null&&U!==void 0?U:0,throttledDevices:(b=e.throttled_devices)!==null&&b!==void 0?b:{},throttledUsers:(k=e.throttled_users)!==null&&k!==void 0?k:{},exceededDailyQuotaDevices:(F=e.exceeded_daily_quota_devices)!==null&&F!==void 0?F:{},exceededDailyQuotaUsers:(I=e.exceeded_daily_quota_users)!==null&&I!==void 0?I:{},throttledEvents:(S=e.throttled_events)!==null&&S!==void 0?S:[]}};case x.Timeout:default:return{status:B,statusCode:O}}},t.prototype.buildStatus=function(e){return e>=200&&e<300?x.Success:e===429?x.RateLimit:e===413?x.PayloadTooLarge:e===408?x.Timeout:e>=400&&e<500?x.Invalid:e>=500?x.Failed:x.Unknown},t}();var N=function(){if(typeof globalThis<"u")return globalThis;if(typeof window<"u")return window;if(typeof self<"u")return self;if(typeof global<"u")return global};var ge=function(){var t,e=N();if(!(!((t=e?.location)===null||t===void 0)&&t.search))return{};var n=e.location.search.substring(1).split("&").filter(Boolean),r=n.reduce(function(i,o){var s=o.split("=",2),u=Wn(s[0]),c=Wn(s[1]);return c&&(i[u]=c),i},{});return r},Wn=function(t){t===void 0&&(t="");try{return decodeURIComponent(t)}catch{return""}};var $n="utm_campaign",Yn="utm_content",Qn="utm_id",Xn="utm_medium",zn="utm_source",Zn="utm_term",kt="dclid",Ot="fbclid",Ut="gbraid",Mt="gclid",Nt="ko_click_id",Bt="li_fat_id",Ft="msclkid",Vt="rtd_cid",Ht="ttclid",qt="twclid",jt="wbraid";var fe={utm_campaign:void 0,utm_content:void 0,utm_id:void 0,utm_medium:void 0,utm_source:void 0,utm_term:void 0,referrer:void 0,referring_domain:void 0,dclid:void 0,gbraid:void 0,gclid:void 0,fbclid:void 0,ko_click_id:void 0,li_fat_id:void 0,msclkid:void 0,rtd_cid:void 0,ttclid:void 0,twclid:void 0,wbraid:void 0};var Se=function(){function t(){}return t.prototype.parse=function(){return p(this,void 0,void 0,function(){return f(this,function(e){return[2,v(v(v(v({},fe),this.getUtmParam()),this.getReferrer()),this.getClickIds())]})})},t.prototype.getUtmParam=function(){var e=ge(),n=e[$n],r=e[Yn],i=e[Qn],o=e[Xn],s=e[zn],u=e[Zn];return{utm_campaign:n,utm_content:r,utm_id:i,utm_medium:o,utm_source:s,utm_term:u}},t.prototype.getReferrer=function(){var e,n,r={referrer:void 0,referring_domain:void 0};try{r.referrer=document.referrer||void 0,r.referring_domain=(n=(e=r.referrer)===null||e===void 0?void 0:e.split("/")[2])!==null&&n!==void 0?n:void 0}catch{}return r},t.prototype.getClickIds=function(){var e,n=ge();return e={},e[kt]=n[kt],e[Ot]=n[Ot],e[Ut]=n[Ut],e[Mt]=n[Mt],e[Nt]=n[Nt],e[Bt]=n[Bt],e[Ft]=n[Ft],e[Vt]=n[Vt],e[Ht]=n[Ht],e[qt]=n[qt],e[jt]=n[jt],e},t}();var Ze=function(t,e,n){return e===void 0&&(e=""),n===void 0&&(n=10),[de,e,t.substring(0,n)].filter(Boolean).join("_")},Kt=function(t){return"".concat(de.toLowerCase(),"_").concat(t.substring(0,6))};var xe=function(t,e){e===void 0&&(e=Date.now());var n=Date.now(),r=n-e;return r>t};var Le=function(){function t(e){this.options=v({},e)}return t.prototype.isEnabled=function(){return p(this,void 0,void 0,function(){var e,n,r,i;return f(this,function(o){switch(o.label){case 0:if(!N())return[2,!1];t.testValue=String(Date.now()),e=new t(this.options),n="AMP_TEST",o.label=1;case 1:return o.trys.push([1,4,5,7]),[4,e.set(n,t.testValue)];case 2:return o.sent(),[4,e.get(n)];case 3:return r=o.sent(),[2,r===t.testValue];case 4:return i=o.sent(),[2,!1];case 5:return[4,e.remove(n)];case 6:return o.sent(),[7];case 7:return[2]}})})},t.prototype.get=function(e){return p(this,void 0,void 0,function(){var n;return f(this,function(r){switch(r.label){case 0:return[4,this.getRaw(e)];case 1:if(n=r.sent(),!n)return[2,void 0];try{try{n=decodeURIComponent(atob(n))}catch{}return[2,JSON.parse(n)]}catch{return[2,void 0]}return[2]}})})},t.prototype.getRaw=function(e){var n,r;return p(this,void 0,void 0,function(){var i,o,s;return f(this,function(u){return i=N(),o=(r=(n=i?.document)===null||n===void 0?void 0:n.cookie.split("; "))!==null&&r!==void 0?r:[],s=o.find(function(c){return c.indexOf(e+"=")===0}),s?[2,s.substring(e.length+1)]:[2,void 0]})})},t.prototype.set=function(e,n){var r;return p(this,void 0,void 0,function(){var i,o,s,u,c,a;return f(this,function(l){try{i=(r=this.options.expirationDays)!==nu