@sprig-technologies/sprig-browser
Version:
npm package for the sprig web sdk
2 lines (1 loc) • 12.1 kB
JavaScript
"use strict";var Y=Object.defineProperty;var j=(e,t,r)=>t in e?Y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var l=(e,t,r)=>j(e,typeof t!="symbol"?t+"":t,r);var U=(e=>(e.Closed="close.click",e.Complete="survey.completed",e.FeedbackClosed="feedback.closed",e.PageChange="page.change",e.API="api",e.Override="override",e))(U||{}),A=(e=>(e.ReplayCapture="replay.capture",e.ReplayPaused="replay.paused",e.ReplayResumed="replay.resumed",e.FeedbackButtonLoaded="feedback.button.loaded",e.SDKReady="sdk.ready",e.SurveyAppeared="survey.appeared",e.SurveyCloseRequested="survey.closeRequested",e.SurveyClosed="survey.closed",e.SurveyDimensions="survey.dimensions",e.SurveyFadingOut="survey.fadingOut",e.SurveyHeight="survey.height",e.SurveyPresented="survey.presented",e.SurveyLifeCycle="survey.lifeCycle",e.SurveyWidth="survey.width",e.SurveyWillClose="survey.willClose",e.SurveyWillPresent="survey.will.present",e.CloseSurveyOnOverlayClick="close.survey.overlayClick",e.VisitorIDUpdated="visitor.id.updated",e.QuestionAnswered="question.answered",e))(A||{});let m;const F=new Uint8Array(16);function H(){if(!m&&(m=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!m))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return m(F)}const o=[];for(let e=0;e<256;++e)o.push((e+256).toString(16).slice(1));const w={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},b=new class{constructor(){l(this,"breadcrumbs",[])}getTimeStamp(){return new Date().toISOString()}addBreadcrumb(e){this.breadcrumbs.push(e),this.breadcrumbs.length>300&&this.breadcrumbs.shift()}debug(e,t="debug"){this.addBreadcrumb({category:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"debug"})}error(e,t={}){this.addBreadcrumb({category:"error",data:t,level:"error",message:e,timestamp:this.getTimeStamp(),type:"error"})}http(e,t){this.addBreadcrumb({category:"xhr",data:t,message:e,timestamp:this.getTimeStamp(),type:"http"})}info(e,t={}){this.addBreadcrumb({category:"info",data:t,level:"info",message:e,timestamp:this.getTimeStamp(),type:"info"})}navigation(e,t){this.addBreadcrumb({category:"navigation",data:t,message:e,timestamp:this.getTimeStamp(),type:"navigation"})}};var q=class extends Error{constructor(e,t,r){super(`Possible EventEmitter memory leak detected. ${r} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`),this.emitter=e,this.type=t,this.count=r,this.name="MaxListenersExceededWarning"}},C=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map,this.maxListeners=C.defaultMaxListeners,this.hasWarnedAboutPotentialMemoryLeak=!1}_emitInternalEvent(e,t,r){this.emit(e,t,r)}_getListeners(e){return Array.prototype.concat.apply([],this.events.get(e))||[]}_removeListener(e,t){const r=e.indexOf(t);return r>-1&&e.splice(r,1),[]}_wrapOnceListener(e,t){const r=(...s)=>(this.removeListener(e,r),t.apply(this,s));return Object.defineProperty(r,"name",{value:t.name}),r}setMaxListeners(e){return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const r=this._getListeners(e);return r.forEach(s=>{s.apply(this,t)}),r.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const r=this._getListeners(e).concat(t);if(this.events.set(e,r),this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=!0;const s=new q(this,e,this.listenerCount(e));console.warn(s)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const r=this._getListeners(e);if(r.length>0){const s=[t].concat(r);this.events.set(e,s)}else this.events.set(e,r.concat(t));return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const r=this._getListeners(e);return r.length>0&&(this._removeListener(r,t),this.events.set(e,r),this._emitInternalEvent("removeListener",e,t)),this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){return e?this.events.delete(e):this.events.clear(),this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}},D=C;D.defaultMaxListeners=10;const B=new D,S=async e=>{await new Promise(t=>{setTimeout(t,e)})};class x{constructor(t){l(this,"storage");l(this,"tempStorage",{});l(this,"isStorageAvailable");try{this.storage=window[t];const r="__storage_test__";this.storage.setItem(r,r),this.storage.removeItem(r),this.isStorageAvailable=!0}catch{this.isStorageAvailable=!1}}setItem(t,r){this.isStorageAvailable&&this.storage?this.storage.setItem(t,r):this.tempStorage[t]=r}setItemObject(t,r){try{this.setItem(t,JSON.stringify(r))}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to save to local storage",s))}}getItem(t){return this.isStorageAvailable&&this.storage?this.storage.getItem(t):this.tempStorage[t]}getItemObject(t){const r=this.getItem(t);if(r)try{return JSON.parse(r)}catch(s){s instanceof Error&&(s.stack=t+": "+r,window.UserLeap.reportError("Failed to parse local storage",s))}return{}}removeItem(t){this.isStorageAvailable&&this.storage?this.storage.removeItem(t):delete this.tempStorage[t]}clear(){this.isStorageAvailable&&this.storage?this.storage.clear():this.tempStorage={}}}const J=new x("sessionStorage"),$=new x("localStorage");class K{constructor(t){l(this,"payload");l(this,"promise");l(this,"reject",()=>{});l(this,"resolve",()=>{});this.payload=t,this.promise=new Promise((r,s)=>{this.reject=s,this.resolve=r})}resolveRequest(t){this.resolve(t)}}const E={replay:null},G=()=>{const e=[];return E.replay&&e.push("replay"),e.join(",")},z=10;let T=!1,M="",g=!1,P=!1,y=[];const Q=e=>e._config&&e._config.installationMethod?e._config.installationMethod:e._gtm?"web-gtm":e._segment?"web-segment":"web-snippet",N=(e="")=>{T=!0,M=e},R=async({shouldDropOnRateLimit:e,...t})=>{if(e)return{status:429};{const r=new K(t);return y.push(r),r.promise}},v=async(e,t)=>{const{retries:r=0,shouldDropOnRateLimit:s=!1,shouldRetryRequest:n=!1,...i}=t,d={url:e,options:i,retries:r,shouldDropOnRateLimit:s};if(g&&!n)return R(d);const u={ok:!1,reportError:!1};if(T)return console.info(`UserLeap - ${M}`),u;try{const c=await fetch(e,i);if(c.status===429){if(!g&&!s||n){g=!0;const a=c.headers.has("ratelimit-reset")?Number(c.headers.get("ratelimit-reset")):z;return await S(1e3*a),v(e,{...i,shouldDropOnRateLimit:s,shouldRetryRequest:!0})}return R(d)}if(g=!1,y.length&&(y.map(a=>{const h=a.payload;v(h.url,{...h.options,retries:h.retries,shouldDropOnRateLimit:h.shouldDropOnRateLimit}).then(W=>{a.resolveRequest(W)})}),y=[]),c.ok){if(c.status===249)return N(),u;const a=await c.text();try{return a&&a!=="OK"&&(c.json=JSON.parse(a)),c}catch{return{ok:!1,reportError:!1,error:new Error(`failed parsing response json for ${e} - ${a}`)}}}return c}catch(c){const a=r+1;return a>5||P?{ok:!1,reportError:!1,error:c}:(await S(1e3*Math.pow(2,r)),v(e,{...i,retries:a}))}},I=Object.freeze({contains:(e,t)=>t.includes(e),notContains:(e,t)=>!t.includes(e),exactly:(e,t)=>t===e,notExactly:(e,t)=>t!==e,startsWith:(e,t)=>t.startsWith(e),endsWith:(e,t)=>t.endsWith(e),regex:(e,t)=>new RegExp(e).test(t),legacy:(e,t)=>new RegExp(e,"i").test(t)});function k(e,t){const{matchType:r,pattern:s}=e,n=r?I[r]:I.legacy;let i=!1;try{i=n(s,t)}catch(d){const u=`[Sprig] (ERR-445) Failed to check url match with pattern ${s}`;d instanceof Error&&(console.warn(u,d),d.stack=JSON.stringify(e),window.UserLeap.reportError(u,d))}return i}let V=!0,f=!1;const X=["sdk_event_queue_latency_seconds","sdk_replay_add_event_batch_seconds","sdk_replay_cleanup_seconds","sdk_replay_compression_seconds","sdk_replay_get_events_between_seconds","sdk_replay_snapshot_seconds","sdk_mutations_nodes_added","sdk_mutations_nodes_removed","sdk_mutations_attributes_changed","sdk_mutations_character_data","sdk_dom_nodes_count","sdk_page_html_characters"];let L,p={};class Z{constructor(t){l(this,"_values",[]);l(this,"_isWebMetric");this.name=t,this._isWebMetric=X.includes(this.name)}report(t){if(V&&this._values.push({time:Date.now(),value:t}),f||!this._isWebMetric)return;const r=this.findExceededThreshold(t);r&&L&&L(t,r)}collect(){const t=this._values;return this._values=[],t}findExceededThreshold(t){const r=p[this.name];if(r)return r.find(s=>this.valueExceedsThreshold(t,s))}valueExceedsThreshold(t,r){return r.type==="max"?t>r.value:r.type==="min"&&t<r.value}}const _={},O=e=>{const t=new Z(e);return _[e]=t,t};exports.DismissReason=U,exports.EVENTS={FEEDBACK_BUTTON_LOADED:"feedback.button.loaded",SDK_READY:"sdk.ready",SURVEY_APPEARED:"survey.appeared",SURVEY_CLOSED:"survey.closed",SURVEY_DIMENSIONS:"survey.dimensions",SURVEY_FADING_OUT:"survey.fadingOut",SURVEY_HEIGHT:"survey.height",SURVEY_WIDTH:"survey.width",SURVEY_PRESENTED:"survey.presented",SURVEY_LIFE_CYCLE:"survey.lifeCycle",SURVEY_WILL_CLOSE:"survey.willClose",SURVEY_WILL_PRESENT:"survey.will.present",QUESTION_ANSWERED:"question.answered",REPLAY_CAPTURE:"replay.capture",CLOSE_SURVEY_ON_OVERLAY_CLICK:"close.survey.overlayClick",VISITOR_ID_UPDATED:"visitor.id.updated",DATA:{DISMISS_REASONS:{API:"api",CLOSED:"close.click",COMPLETE:"survey.completed",PAGE_CHANGE:"page.change",OVERRIDE:"override"},SURVEY_ID:"survey.id"}},exports.PerformanceMetrics=_,exports.SprigEvent=A,exports.breadcrumbsLogger=b,exports.checkUrlMatch=k,exports.checkUrlStillMatching=e=>{const{pageUrlEvents:t}=window.UserLeap._config,r=t==null?void 0:t.find(s=>s.id===e);return!!r&&k(r,window.location.href)},exports.cspViolationHandler=e=>{var t;(t=e==null?void 0:e.blockedURI)!=null&&t.includes(window.UserLeap._API_URL)&&(P=!0,console.warn(`[Sprig] ${e.blockedURI} is blocked by Content-Security-Policy`))},exports.delay=S,exports.disableThresholdChecking=()=>f=!0,exports.eventEmitter=B,exports.getHttpHeaders=function(e={}){const t={"Content-Type":"application/json","userleap-platform":"web","x-ul-sdk-version":"2.35.0","x-ul-installation-method":Q(e),"sprig-modules":G()};if(e.envId&&(t["x-ul-environment-id"]=e.envId),e.token&&(t.Authorization="Bearer "+e.token),e.userId&&(t["x-ul-user-id"]=e.userId),e.visitorId&&(t["x-ul-visitor-id"]=e.visitorId),e.partnerAnonymousId&&(t["x-ul-anonymous-id"]=e.partnerAnonymousId),e.mobileHeadersJSON){const r=JSON.parse(e.mobileHeadersJSON);Object.assign(t,r)}return e.locale&&(t["accept-language"]=e.locale),window.previewMode&&(t["x-ul-preview-mode"]="1"),t},exports.groupCards=(e,t)=>{const r=[e[t]],s=e[t].groupId;return s?e.slice(t).reduce((n,i)=>(i.groupId===s&&n.push(i),n),[]):r},exports.initPerformanceReporting=({reportingIntervalSeconds:e,postMetrics:t})=>{e?setInterval(()=>{(async r=>{const s=Object.values(_).map(n=>({name:n.name,values:n.collect()}));if(s.some(n=>n.values.length))try{await r(JSON.stringify(s))}catch(n){n instanceof Error&&b.error("MetricsErr",{error:{message:n.message,name:n.name}})}})(t)},1e3*e):V=!1},exports.isLongFormSurvey=e=>e==="longFormSurvey",exports.killNetworkRequests=N,exports.localStorageHelper=$,exports.modules=E,exports.registerMetric=O,exports.registerReplay=e=>{E.replay=e},exports.registerThresholds=(e,t)=>{p={},f=!1,e==null||e.forEach(r=>{var s;r.metric in p||(p[r.metric]=[]),(s=p[r.metric])==null||s.push(r)}),L=t},exports.reportAndRegister=(e,t)=>{let r=_[e];return r||(r=O(e)),r.report(t)},exports.sessionStorageHelper=J,exports.shouldDirectEmbed=({"userleap-platform":e})=>{var t;return((t=window.UserLeap)==null?void 0:t.forceDirectEmbed)||e!=="web"},exports.sprigFetch=v,exports.v4=function(e,t,r){if(w.randomUUID&&!e)return w.randomUUID();const s=(e=e||{}).random||(e.rng||H)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(n,i=0){return o[n[i+0]]+o[n[i+1]]+o[n[i+2]]+o[n[i+3]]+"-"+o[n[i+4]]+o[n[i+5]]+"-"+o[n[i+6]]+o[n[i+7]]+"-"+o[n[i+8]]+o[n[i+9]]+"-"+o[n[i+10]]+o[n[i+11]]+o[n[i+12]]+o[n[i+13]]+o[n[i+14]]+o[n[i+15]]}(s)};