Socket
Socket
Sign inDemoInstall

@datadog/browser-logs

Package Overview
Dependencies
Maintainers
1
Versions
256
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@datadog/browser-logs - npm Package Compare versions

Comparing version 4.1.0 to 4.2.0

2

bundle/datadog-logs.js

@@ -1,1 +0,1 @@

!function(){"use strict";var e=function(){return(e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function t(e,t){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}}function n(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),i=0;for(t=0;t<n;t++)for(var o=arguments[t],s=0,u=o.length;s<u;s++,i++)r[i]=o[s];return r}var r={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},i="?";function o(e,t){var n,r=void 0===t?0:+t;try{if(n=function(e){var t=a(e,"stacktrace");if(!t)return;for(var n,r=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,o=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\((.*)\))? in (.*):\s*$/i,s=t.split("\n"),u=[],c=0;c<s.length;c+=2){var f=void 0;r.exec(s[c])?f={args:[],column:void 0,func:(n=r.exec(s[c]))[3],line:+n[1],url:n[2]}:o.exec(s[c])&&(f={args:(n=o.exec(s[c]))[5]?n[5].split(","):[],column:+n[2],func:n[3]||n[4],line:+n[1],url:n[6]}),f&&(!f.func&&f.line&&(f.func=i),f.context=[s[c+1]],u.push(f))}if(!u.length)return;return{stack:u,message:a(e,"message"),name:a(e,"name")}}(e))return n}catch(e){if(s)throw e}try{if(n=function(e){var t=a(e,"stack");if(!t)return;for(var n,r,o,s,u=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,c=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,l=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,d=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,p=/\((\S*)(?::(\d+))(?::(\d+))\)/,v=t.split("\n"),h=[],g=0,m=v.length;g<m;g+=1){if(u.exec(v[g])){var y=(o=u.exec(v[g]))[2]&&0===o[2].indexOf("native");n=o[2]&&0===o[2].indexOf("eval"),r=p.exec(o[2]),n&&r&&(o[2]=r[1],o[3]=r[2],o[4]=r[3]),s={args:y?[o[2]]:[],column:o[4]?+o[4]:void 0,func:o[1]||i,line:o[3]?+o[3]:void 0,url:y?void 0:o[2]}}else if(l.exec(v[g]))s={args:[],column:(o=l.exec(v[g]))[4]?+o[4]:void 0,func:o[1]||i,line:+o[3],url:o[2]};else{if(!c.exec(v[g]))continue;n=(o=c.exec(v[g]))[3]&&o[3].indexOf(" > eval")>-1,r=d.exec(o[3]),n&&r?(o[3]=r[1],o[4]=r[2],o[5]=void 0):0!==g||o[5]||f(e.columnNumber)||(h[0].column=e.columnNumber+1),s={args:o[2]?o[2].split(","):[],column:o[5]?+o[5]:void 0,func:o[1]||i,line:o[4]?+o[4]:void 0,url:o[3]}}!s.func&&s.line&&(s.func=i),h.push(s)}if(!h.length)return;return{stack:h,message:a(e,"message"),name:a(e,"name")}}(e))return n}catch(e){if(s)throw e}try{if(n=function(e){var t=a(e,"message");if(!t)return;var n=t.split("\n");if(n.length<4)return;var r,o=/^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,s=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,u=/^\s*Line (\d+) of function script\s*$/i,f=[],l=window&&window.document&&window.document.getElementsByTagName("script"),d=[];for(var p in l)c(l,p)&&!l[p].src&&d.push(l[p]);for(var v=2;v<n.length;v+=2){var h=void 0;if(o.exec(n[v]))h={args:[],column:void 0,func:(r=o.exec(n[v]))[3],line:+r[1],url:r[2]};else if(s.exec(n[v]))h={args:[],column:void 0,func:(r=s.exec(n[v]))[4],line:+r[1],url:r[3]};else if(u.exec(n[v])){r=u.exec(n[v]),h={url:window.location.href.replace(/#.*$/,""),args:[],column:void 0,func:"",line:+r[1]}}h&&(h.func||(h.func=i),h.context=[n[v+1]],f.push(h))}if(!f.length)return;return{stack:f,message:n[0],name:a(e,"name")}}(e))return n}catch(e){if(s)throw e}try{if(n=u(e,r+1))return n}catch(e){if(s)throw e}return{message:a(e,"message"),name:a(e,"name"),stack:[]}}var s=!1;function u(e,t){for(var n,r,s=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,c=[],f={},l=!1,d=u.caller;d&&!l;d=d.caller)d!==o&&(r={args:[],column:void 0,func:i,line:void 0,url:void 0},n=s.exec(d.toString()),d.name?r.func=d.name:n&&(r.func=n[1]),void 0===r.func&&(r.func=n?n.input.substring(0,n.input.indexOf("{")):void 0),f[d.toString()]?l=!0:f[d.toString()]=!0,c.push(r));t&&c.splice(0,t);var p={stack:c,message:a(e,"message"),name:a(e,"name")};return function(e,t,n){var r={url:t,line:n?+n:void 0};if(r.url&&r.line){e.incomplete=!1;var i=e.stack;if(i.length>0&&i[0].url===r.url){if(i[0].line===r.line)return!1;if(!i[0].line&&i[0].func===r.func)return i[0].line=r.line,i[0].context=r.context,!1}return i.unshift(r),e.partial=!0,!0}e.incomplete=!0}(p,a(e,"sourceURL")||a(e,"fileName"),a(e,"line")||a(e,"lineNumber")),p}function a(e,t){if("object"==typeof e&&e&&t in e){var n=e[t];return"string"==typeof n?n:void 0}}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function f(e){return void 0===e}var l,d,p=1e3,v=6e4;function h(e,t,n){var r,i,o=!n||void 0===n.leading||n.leading,s=!n||void 0===n.trailing||n.trailing,u=!1;return{throttled:function(){for(var n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];u?r=n:(o?e.apply(void 0,n):r=n,u=!0,i=setTimeout((function(){s&&r&&e.apply(void 0,r),u=!1,r=void 0}),t))},cancel:function(){clearTimeout(i),u=!1,r=void 0}}}function g(e){return e?(parseInt(e,10)^16*Math.random()>>parseInt(e,10)/4).toString(16):"10000000-1000-4000-8000-100000000000".replace(/[018]/g,g)}function m(){}function y(e,t,n){if(null==e)return JSON.stringify(e);var r=[!1,void 0];b(e)&&(r=[!0,e.toJSON],delete e.toJSON);var i,o,s=[!1,void 0];"object"==typeof e&&b(i=Object.getPrototypeOf(e))&&(s=[!0,i.toJSON],delete i.toJSON);try{o=JSON.stringify(e,t,n)}catch(e){o="<error: unable to serialize object>"}finally{r[0]&&(e.toJSON=r[1]),s[0]&&(i.toJSON=s[1])}return o}function b(e){return"object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(e,"toJSON")}function w(e,t){return-1!==e.indexOf(t)}function x(e){return Object.keys(e).map((function(t){return e[t]}))}function S(e,t,n,r){return k(e,[t],n,r)}function k(e,t,n,r){var i=void 0===r?{}:r,o=i.once,s=i.capture,u=i.passive,a=V(o?function(e){f(),n(e)}:n),c=u?{capture:s,passive:u}:s;t.forEach((function(t){return e.addEventListener(t,a,c)}));var f=function(){return t.forEach((function(t){return e.removeEventListener(t,a,c)}))};return{stop:f}}function E(e,t,n){if(void 0===n&&(n=function(){if("undefined"!=typeof WeakSet){var e=new WeakSet;return{hasAlreadyBeenSeen:function(t){var n=e.has(t);return n||e.add(t),n}}}var t=[];return{hasAlreadyBeenSeen:function(e){var n=t.indexOf(e)>=0;return n||t.push(e),n}}}()),void 0===t)return e;if("object"!=typeof t||null===t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){var r=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,r)}if(!n.hasAlreadyBeenSeen(t)){if(Array.isArray(t)){for(var i=Array.isArray(e)?e:[],o=0;o<t.length;++o)i[o]=E(i[o],t[o],n);return i}var s,u="object"==(null===(s=e)?"null":Array.isArray(s)?"array":typeof s)?e:{};for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(u[a]=E(u[a],t[a],n));return u}}function T(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var o=i[r];null!=o&&(e=E(e,o))}return e}!function(e){e.DOCUMENT="document",e.XHR="xhr",e.BEACON="beacon",e.FETCH="fetch",e.CSS="css",e.JS="js",e.IMAGE="image",e.FONT="font",e.MEDIA="media",e.OTHER="other"}(l||(l={})),function(e){e.FETCH="fetch",e.XHR="xhr"}(d||(d={}));var O,C,R="agent",L="console",M="logger",B="network",A="source";function N(e){var t=D(e);return e.stack.forEach((function(e){var n="?"===e.func?"<anonymous>":e.func,r=e.args&&e.args.length>0?"("+e.args.join(", ")+")":"",i=e.line?":"+e.line:"",o=e.line&&e.column?":"+e.column:"";t+="\n at "+n+r+" @ "+e.url+i+o})),t}function D(e){return(e.name||"Error")+": "+e.message}function I(){var e,t=new Error;if(!t.stack)try{throw t}catch(e){}return Y((function(){var n=o(t);n.stack=n.stack.slice(2),e=N(n)})),e}function _(e){return!!C&&C.has(e)}function j(){var e=_("event-bridge")?window.DatadogEventBridge:null;if(e)return{getAllowedWebViewHosts:function(){return JSON.parse(e.getAllowedWebViewHosts())},send:function(t,n){e.send(JSON.stringify({eventType:t,event:n}))}}}function z(){var e=j();return!!e&&w(e.getAllowedWebViewHosts(),window.location.hostname)}!function(e){e.HANDLED="handled",e.UNHANDLED="unhandled"}(O||(O={}));var U,P=/[^\u0000-\u007F]/,H=function(){function e(e,t,n,r,i,o){void 0===o&&(o=m),this.request=e,this.maxSize=t,this.bytesLimit=n,this.maxMessageSize=r,this.flushTimeout=i,this.beforeUnloadCallback=o,this.pushOnlyBuffer=[],this.upsertBuffer={},this.bufferBytesSize=0,this.bufferMessageCount=0,this.flushOnVisibilityHidden(),this.flushPeriodically()}return e.prototype.add=function(e){this.addOrUpdate(e)},e.prototype.upsert=function(e,t){this.addOrUpdate(e,t)},e.prototype.flush=function(e){if(0!==this.bufferMessageCount){var t=n(this.pushOnlyBuffer,x(this.upsertBuffer));this.request.send(t.join("\n"),this.bufferBytesSize,e),this.pushOnlyBuffer=[],this.upsertBuffer={},this.bufferBytesSize=0,this.bufferMessageCount=0}},e.prototype.sizeInBytes=function(e){return P.test(e)?void 0!==window.TextEncoder?(new TextEncoder).encode(e).length:new Blob([e]).size:e.length},e.prototype.addOrUpdate=function(e,t){var n=this.process(e),i=n.processedMessage,o=n.messageBytesSize;o>=this.maxMessageSize?r.warn("Discarded a message whose size was bigger than the maximum allowed size "+this.maxMessageSize+"KB."):(this.hasMessageFor(t)&&this.remove(t),this.willReachedBytesLimitWith(o)&&this.flush("willReachedBytesLimitWith"),this.push(i,o,t),this.isFull()&&this.flush("isFull"))},e.prototype.process=function(e){var t=y(e);return{processedMessage:t,messageBytesSize:this.sizeInBytes(t)}},e.prototype.push=function(e,t,n){this.bufferMessageCount>0&&(this.bufferBytesSize+=1),void 0!==n?this.upsertBuffer[n]=e:this.pushOnlyBuffer.push(e),this.bufferBytesSize+=t,this.bufferMessageCount+=1},e.prototype.remove=function(e){var t=this.upsertBuffer[e];delete this.upsertBuffer[e];var n=this.sizeInBytes(t);this.bufferBytesSize-=n,this.bufferMessageCount-=1,this.bufferMessageCount>0&&(this.bufferBytesSize-=1)},e.prototype.hasMessageFor=function(e){return void 0!==e&&void 0!==this.upsertBuffer[e]},e.prototype.willReachedBytesLimitWith=function(e){return this.bufferBytesSize+e+1>=this.bytesLimit},e.prototype.isFull=function(){return this.bufferMessageCount===this.maxSize||this.bufferBytesSize>=this.bytesLimit},e.prototype.flushPeriodically=function(){var e=this;setTimeout(V((function(){e.flush("flushPeriodically"),e.flushPeriodically()})),this.flushTimeout)},e.prototype.flushOnVisibilityHidden=function(){var e=this;navigator.sendBeacon&&(S(window,"beforeunload",this.beforeUnloadCallback),S(document,"visibilitychange",(function(){"hidden"===document.visibilityState&&e.flush("visibilitychange")})),S(window,"beforeunload",(function(){return e.flush("beforeunload")})))},e}(),F=!1,q=function(){function e(e,t){this.endpointBuilder=e,this.bytesLimit=t}return e.prototype.send=function(e,t,n){var r=this.endpointBuilder.build(),i=!!navigator.sendBeacon&&t<this.bytesLimit;if(i)try{if(navigator.sendBeacon(r,e))return}catch(e){!function(e){$||($=!0,Q(e))}(e)}var o=new XMLHttpRequest;o.addEventListener("loadend",V((function(e){return function(e){var o=null==e?void 0:e.currentTarget;o.status>=200&&o.status<300||F||(F=!0,Z("XHR fallback failed",{on_line:navigator.onLine,size:t,url:r,try_beacon:i,flush_reason:n,event:{is_trusted:e.isTrusted,total:e.total,loaded:e.loaded},request:{status:o.status,ready_state:o.readyState,response_text:o.responseText.slice(0,512)}}))}(e)}))),o.open("POST",r,!0),o.send(e)},e}(),$=!1;!function(e){e.info="info",e.error="error"}(U||(U={}));var G,K,J={maxMessagesPerPage:0,sentMessageCount:0};function X(e){var t;if(z()){var n=j();G=function(e){return n.send("internal_log",i(e))}}else if(e.internalMonitoringEndpointBuilder){var r=function(e){var t,n=r(e.internalMonitoringEndpointBuilder);function r(t){return new H(new q(t,e.batchBytesLimit),e.maxBatchSize,e.batchBytesLimit,e.maxMessageSize,e.flushTimeout)}return void 0!==e.replica&&(t=r(e.replica.internalMonitoringEndpointBuilder)),{add:function(e){n.add(e),t&&t.add(e)}}}(e);G=function(e){return r.add(i(e))}}function i(e){return T({date:(new Date).getTime()},void 0!==t?t():{},e)}return function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];t.forEach((function(t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}))}(J,{maxMessagesPerPage:e.maxInternalMonitoringMessagesPerPage,sentMessageCount:0}),{setExternalContextProvider:function(e){t=e}}}function W(e,t,n){var r=n.value;n.value=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=G?V(r):r;return n.apply(this,e)}}function V(e){return function(){return Y(e,this,arguments)}}function Y(e,t,n){try{return e.apply(t,n)}catch(e){ne(e);try{Q(e)}catch(e){ne(e)}}}function Z(t,n){!function(e,t){J.debugMode&&r.log("[MONITORING MESSAGE]",e,t)}(t,n),ee(e(e({message:t},n),{status:U.info}))}function Q(t){ee(e(e({},function(e){if(e instanceof Error){var t=o(e);return{error:{kind:t.name,stack:N(t)},message:t.message}}return{error:{stack:"Not an instance of error"},message:"Uncaught "+y(e)}}(t)),{status:U.error}))}function ee(e){G&&J.sentMessageCount<J.maxMessagesPerPage&&(J.sentMessageCount+=1,G(e))}function te(e){J.debugMode=e}function ne(e){J.debugMode&&r.error("[INTERNAL ERROR]",e)}function re(e,t){return function(){for(var n=[],i=0;i<arguments.length;i++)n[i]=arguments[i];try{return e.apply(void 0,n)}catch(e){r.error(t,e)}}}function ie(){var e={};return{get:function(){return e},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},set:function(t){e=t}}}!function(e){e.RELEASE="release",e.CANARY="canary",e.E2E_TEST="e2e-test"}(K||(K={}));var oe,se,ue,ae=function(){function e(){this.buffer=[]}return e.prototype.add=function(e){this.buffer.push(e)>500&&this.buffer.splice(0,1)},e.prototype.drain=function(){this.buffer.forEach((function(e){return e()})),this.buffer.length=0},e}();function ce(e,t,n,r){var i=new Date;i.setTime(i.getTime()+n);var o="expires="+i.toUTCString(),s=r&&r.crossSite?"none":"strict",u=r&&r.domain?";domain="+r.domain:"",a=r&&r.secure?";secure":"";document.cookie=e+"="+t+";"+o+";path=/;samesite="+s+u+a}function fe(e){return function(e,t){var n=new RegExp("(?:^|;)\\s*"+t+"\\s*=\\s*([^;]+)").exec(e);return n?n[1]:void 0}(document.cookie,e)}function le(e,t){ce(e,"",0,t)}function de(){return Date.now()}function pe(){return performance.now()}function ve(){return{relative:pe(),timeStamp:de()}}function he(e,t){return t-e}function ge(){return void 0===se&&(se=performance.timing.navigationStart),se}function me(e){return ye(e,function(e){if(e.origin)return e.origin;var t=e.host.replace(/(:80|:443)$/,"");return e.protocol+"//"+t}(window.location)).href}function ye(e,t){if(function(){if(void 0!==ue)return ue;try{var e=new URL("http://test/path");return ue="http://test/path"===e.href}catch(e){ue=!1}return ue}())return void 0!==t?new URL(e,t):new URL(e);if(void 0===t&&!/:/.test(e))throw new Error("Invalid URL: '"+e+"'");var n=document,r=n.createElement("a");if(void 0!==t){var i=(n=document.implementation.createHTMLDocument("")).createElement("base");i.href=t,n.head.appendChild(i),n.body.appendChild(r)}return r.href=e,r}var be={logs:"logs",rum:"rum",sessionReplay:"session-replay"},we={logs:"logs",rum:"rum",sessionReplay:"replay"},xe="datadoghq.com";function Se(e,t,n,r,i){var o=e.site,s=void 0===o?xe:o,u=e.clientToken,a=s.split("."),c=a.pop(),f="https://"+(be[n]+".browser-intake-"+a.join("-")+"."+c)+"/api/v2/"+we[n],l=e.proxyUrl&&me(e.proxyUrl);return{build:function(){var e="ddsource="+(i||"browser")+"&ddtags="+encodeURIComponent(["sdk_version:"+t.sdkVersion].concat(r).join(","))+"&dd-api-key="+u+"&dd-evp-origin-version="+encodeURIComponent(t.sdkVersion)+"&dd-evp-origin=browser&dd-request-id="+g();"rum"===n&&(e+="&batch_time="+de());var o=f+"?"+e;return l?l+"?ddforward="+encodeURIComponent(o):o},buildIntakeUrl:function(){return l?l+"?ddforward":f}}}var ke=/[^a-z0-9_:./-]/;function Ee(e,t){var n=200-e.length-1;return(t.length>n||ke.test(t))&&r.warn(e+" value doesn't meet tag requirements and will be sanitized"),e+":"+t.replace(/,/g,"_")}function Te(t,n){var r=function(e){var t=e.env,n=e.service,r=e.version,i=e.datacenter,o=[];return t&&o.push(Ee("env",t)),n&&o.push(Ee("service",n)),r&&o.push(Ee("version",r)),i&&o.push(Ee("datacenter",i)),o}(t),i=function(t,n,r){if(n.buildMode===K.E2E_TEST){var i=function(e){return{build:function(){return e},buildIntakeUrl:function(){return e}}};return{logsEndpointBuilder:i("<<< E2E LOGS ENDPOINT >>>"),rumEndpointBuilder:i("<<< E2E RUM ENDPOINT >>>"),sessionReplayEndpointBuilder:i("<<< E2E SESSION REPLAY ENDPOINT >>>"),internalMonitoringEndpointBuilder:i("<<< E2E INTERNAL MONITORING ENDPOINT >>>")}}var o={logsEndpointBuilder:Se(t,n,"logs",r),rumEndpointBuilder:Se(t,n,"rum",r),sessionReplayEndpointBuilder:Se(t,n,"sessionReplay",r)};if(t.internalMonitoringApiKey)return e(e({},o),{internalMonitoringEndpointBuilder:Se(e(e({},t),{clientToken:t.internalMonitoringApiKey}),n,"logs",r,"browser-agent-internal-monitoring")});return o}(t,n,r),o=x(i).map((function(e){return e.buildIntakeUrl()})),s=function(t,n,r,i){if(!t.replica)return;var o=e(e({},t),{site:xe,clientToken:t.replica.clientToken}),s={logsEndpointBuilder:Se(o,n,"logs",i),rumEndpointBuilder:Se(o,n,"rum",i),internalMonitoringEndpointBuilder:Se(o,n,"logs",i,"browser-agent-internal-monitoring")};return r.push.apply(r,x(s).map((function(e){return e.buildIntakeUrl()}))),e({applicationId:t.replica.applicationId},s)}(t,n,o,r);return e(e({isIntakeUrl:function(e){return o.some((function(t){return 0===e.indexOf(t)}))}},i),{replica:s})}function Oe(t,n){var i;if(t&&t.clientToken){var o,s;if(void 0===t.sampleRate||function(e){return"number"==typeof e}(o=t.sampleRate)&&o>=0&&o<=100)return s=t.enableExperimentalFeatures,Array.isArray(s)&&(C||(C=new Set(s)),s.filter((function(e){return"string"==typeof e})).forEach((function(e){C.add(e)}))),e(e({},Te(t,n)),{beforeSend:t.beforeSend&&re(t.beforeSend,"beforeSend threw an error:"),cookieOptions:Ce(t),sampleRate:null!==(i=t.sampleRate)&&void 0!==i?i:100,service:t.service,silentMultipleInit:!!t.silentMultipleInit,batchBytesLimit:16384,eventRateLimiterThreshold:3e3,maxInternalMonitoringMessagesPerPage:15,requestErrorResponseLengthLimit:32768,flushTimeout:3e4,maxBatchSize:50,maxMessageSize:262144});r.error("Sample Rate should be a number between 0 and 100")}else r.error("Client Token is not configured, we will not send any data.")}function Ce(e){var t={};return t.secure=function(e){return!!e.useSecureSessionCookie||!!e.useCrossSiteSessionCookie}(e),t.crossSite=!!e.useCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=function(){if(void 0===oe){for(var e="dd_site_test_"+g(),t=window.location.hostname.split("."),n=t.pop();t.length&&!fe(e);)n=t.pop()+"."+n,ce(e,"test",p,{domain:n});le(e,{domain:n}),oe=n}return oe}()),t}var Re,Le={buildMode:"release",sdkVersion:"4.1.0"};var Me={debug:"debug",error:"error",info:"info",warn:"warn"},Be=((Re={})[Me.debug]=0,Re[Me.info]=1,Re[Me.warn]=2,Re[Me.error]=3,Re),Ae=(Object.keys(Me),"console"),Ne="http",De=function(){function t(e,t,n,r){void 0===t&&(t=Ne),void 0===n&&(n=Me.debug),void 0===r&&(r={}),this.sendLog=e,this.handlerType=t,this.level=n,this.contextManager=ie(),this.contextManager.set(r)}return t.prototype.log=function(t,n,i){if(void 0===i&&(i=Me.info),Be[i]>=Be[this.level]){var o=Array.isArray(this.handlerType)?this.handlerType:[this.handlerType];w(o,Ne)&&this.sendLog(e({message:t,status:i},T(this.contextManager.get(),n))),w(o,Ae)&&r.log(i+": "+t,T(this.contextManager.get(),n))}},t.prototype.debug=function(e,t){this.log(e,t,Me.debug)},t.prototype.info=function(e,t){this.log(e,t,Me.info)},t.prototype.warn=function(e,t){this.log(e,t,Me.warn)},t.prototype.error=function(e,t){var n={error:{origin:M}};this.log(e,T(n,t),Me.error)},t.prototype.setContext=function(e){this.contextManager.set(e)},t.prototype.addContext=function(e,t){this.contextManager.add(e,t)},t.prototype.removeContext=function(e){this.contextManager.remove(e)},t.prototype.setHandler=function(e){this.handlerType=e},t.prototype.setLevel=function(e){this.level=e},function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var u=e.length-1;u>=0;u--)(i=e[u])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);o>3&&s&&Object.defineProperty(t,n,s)}([W],t.prototype,"log",null),t}();var Ie,_e,je=function(){function e(e){this.onFirstSubscribe=e,this.observers=[]}return e.prototype.subscribe=function(e){var t=this;return!this.observers.length&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe()||void 0),this.observers.push(e),{unsubscribe:function(){t.observers=t.observers.filter((function(t){return e!==t})),!t.observers.length&&t.onLastUnsubscribe&&t.onLastUnsubscribe()}}},e.prototype.notify=function(e){this.observers.forEach((function(t){return t(e)}))},e}();function ze(t){(function(){_e||(_e=new je,Ie=console.error,console.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=I();Y((function(){Ie.apply(console,t);var n=e(e({},Ue(t,r)),{source:L,startClocks:ve(),handling:O.HANDLED});_e.notify(n)}))});return _e})().subscribe((function(e){return t.notify(e)}))}function Ue(e,t){var r=function(e,t){for(var n=0;n<e.length;n+=1){var r=e[n];if(t(r,n,e))return r}}(e,(function(e){return e instanceof Error}));return{message:n(["console error:"],e).map((function(e){return function(e){if("string"==typeof e)return e;if(e instanceof Error)return D(o(e));return y(e,void 0,2)}(e)})).join(" "),stack:r?N(o(r)):void 0,handlingStack:t}}function Pe(e,t,n){var r=e[t],i=n(r),o=function(){return i.apply(this,arguments)};return e[t]=o,{stop:function(){e[t]===o?e[t]=r:i=r}}}function He(e,t,n){var r=n.before,i=n.after;return Pe(e,t,(function(e){return function(){var t,n=arguments;return r&&Y(r,this,n),"function"==typeof e&&(t=e.apply(this,n)),i&&Y(i,this,n),t}}))}var Fe,qe=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;function $e(e){var t=function(e){return He(window,"onerror",{before:function(t,n,r,i,s){var u;if(s)u=o(s),e(u,s);else{var a,c={url:n,column:i,line:r},f=t;if("[object String]"==={}.toString.call(t)){var l=qe.exec(f);l&&(a=l[1],f=l[2])}e(u={name:a,message:"string"==typeof f?f:void 0,stack:[c]},t)}}})}(e).stop,n=function(e){return He(window,"onunhandledrejection",{before:function(t){var n=t.reason||"Empty reason",r=o(n);e(r,n)}})}(e).stop;return{stop:function(){t(),n()}}}function Ge(e){return $e((function(t,n){var r=function(e,t,n,r){return e&&(void 0!==e.message||t instanceof Error)?{message:e.message||"Empty message",stack:N(e),handlingStack:r,type:e.name}:{message:n+" "+y(t),stack:"No stack, consider using an instance of Error",handlingStack:r,type:e&&e.name}}(t,n,"Uncaught"),i=r.stack,o=r.message,s=r.type;e.notify({message:o,stack:i,type:s,source:A,startClocks:ve(),originalError:n,handling:O.UNHANDLED})}))}function Ke(e,t,n){var r=0,i=!1;return{isLimitReached:function(){if(0===r&&setTimeout((function(){r=0}),v),(r+=1)<=t||i)return i=!1,!1;if(r===t+1){i=!0;try{n({message:"Reached max number of "+e+"s by minute: "+t,source:R,startClocks:ve()})}finally{i=!1}}return!0}}}var Je,Xe=new WeakMap;function We(){var e;return Fe||(e=new je((function(){var t=He(XMLHttpRequest.prototype,"open",{before:Ve}).stop,n=He(XMLHttpRequest.prototype,"send",{before:function(){Ye.call(this,e)}}).stop,r=He(XMLHttpRequest.prototype,"abort",{before:Ze}).stop;return function(){t(),n(),r()}})),Fe=e),Fe}function Ve(e,t){Xe.set(this,{state:"open",method:e,url:me(t)})}function Ye(t){var n=this,r=Xe.get(this);if(r){var i=r;i.state="start",i.startTime=pe(),i.startClocks=ve(),i.isAborted=!1,i.xhr=this;var o=!1,s=He(this,"onreadystatechange",{before:function(){this.readyState===XMLHttpRequest.DONE&&u()}}).stop,u=V((function(){if(n.removeEventListener("loadend",u),s(),!o){o=!0;var a=r;a.state="complete",a.duration=he(i.startClocks.timeStamp,de()),a.responseText=n.response,a.status=n.status,t.notify(e({},a))}}));this.addEventListener("loadend",u),t.notify(i)}}function Ze(){var e=Xe.get(this);e&&(e.isAborted=!0)}function Qe(){var e;return Je||(e=new je((function(){if(window.fetch)return Pe(window,"fetch",(function(t){return function(n,r){var i,o=Y(et,null,[e,n,r]);return o?(i=t.call(this,o.input,o.init),Y(tt,null,[e,i,o])):i=t.call(this,n,r),i}})).stop})),Je=e),Je}function et(e,t,n){var r=n&&n.method||"object"==typeof t&&t.method||"GET",i=me("object"==typeof t&&t.url||t),o={state:"start",init:n,input:t,method:r,startClocks:ve(),url:i};return e.notify(o),o}function tt(e,n,r){var i=this,s=function(n){return s=i,u=void 0,c=function(){var i,s,u;return t(this,(function(t){switch(t.label){case 0:return(i=r).state="complete",i.duration=he(i.startClocks.timeStamp,de()),"stack"in n||n instanceof Error?(i.status=0,i.responseText=N(o(n)),i.isAborted=n instanceof DOMException&&n.code===DOMException.ABORT_ERR,i.error=n,e.notify(i),[3,6]):[3,1];case 1:if(!("status"in n))return[3,6];s=void 0,t.label=2;case 2:return t.trys.push([2,4,,5]),[4,n.clone().text()];case 3:return s=t.sent(),[3,5];case 4:return u=t.sent(),s="Unable to retrieve response: "+u,[3,5];case 5:i.response=n,i.responseText=s,i.responseType=n.type,i.status=n.status,i.isAborted=!1,e.notify(i),t.label=6;case 6:return[2]}}))},new((a=void 0)||(a=Promise))((function(e,t){function n(e){try{i(c.next(e))}catch(e){t(e)}}function r(e){try{i(c.throw(e))}catch(e){t(e)}}function i(t){t.done?e(t.value):new a((function(e){e(t.value)})).then(n,r)}i((c=c.apply(s,u||[])).next())}));var s,u,a,c};n.then(V(s),V(s))}function nt(e,t){return e&&e.length>t.requestErrorResponseLengthLimit?e.substring(0,t.requestErrorResponseLengthLimit)+"...":e}function rt(e){return d.XHR===e?"XHR":"Fetch"}var it=function(){function e(e){var t=this;this.expireDelay=e,this.previousContexts=[],this.clearOldContextsInterval=setInterval((function(){return t.clearOldContexts()}),6e4)}return e.prototype.find=function(e){if(void 0===e||void 0!==this.current&&void 0!==this.currentStart&&e>=this.currentStart)return this.current;for(var t=0,n=this.previousContexts;t<n.length;t++){var r=n[t];if(e>r.endTime)break;if(e>=r.startTime)return r.context}},e.prototype.setCurrent=function(e,t){this.current=e,this.currentStart=t},e.prototype.getCurrent=function(){return this.current},e.prototype.clearCurrent=function(){this.current=void 0,this.currentStart=void 0},e.prototype.closeCurrent=function(e){void 0!==this.current&&void 0!==this.currentStart&&(this.previousContexts.unshift({endTime:e,context:this.current,startTime:this.currentStart}),this.clearCurrent())},e.prototype.clearOldContexts=function(){for(var e=pe()-this.expireDelay;this.previousContexts.length>0&&this.previousContexts[this.previousContexts.length-1].startTime<e;)this.previousContexts.pop()},e.prototype.reset=function(){this.clearCurrent(),this.previousContexts=[]},e.prototype.stop=function(){clearInterval(this.clearOldContextsInterval)},e}(),ot=9e5,st=144e5;function ut(e,t,n){var r=new je,i=new je,o=setInterval(V((function(){pt({options:e,process:function(e){return f(e)?void 0:{}},after:u})})),1e3),s=function(){var e=yt();if(f(e))return e;return{}}();function u(e){return f(e)||(e={}),a()&&(!function(e){if(s.id!==e.id)return e.id&&f(s)&&c(e,"different id"),!0;if(s[t]!==e[t])return c(e,"different tracking type"),!0;return!1}(e)?s=e:(s={},i.notify())),e}function a(){return void 0!==s[t]}function c(e,n){Z("Session inconsistencies detected",{debug:{productKey:t,sessionCache:s,cookieSession:e,cause:n}})}function f(e){return(void 0===e.created||Date.now()-Number(e.created)<st)&&(void 0===e.expire||Date.now()<Number(e.expire))}return{expandOrRenewSession:h(V((function(){var i;pt({options:e,process:function(e){var r=u(e);return i=function(e){var r=n(e[t]),i=r.trackingType,o=r.isTracked;e[t]=i,o&&!e.id&&(e.id=g(),e.created=String(Date.now()));return o}(r),r},after:function(e){i&&!a()&&function(e){s=e,r.notify()}(e),s=e}})})),1e3).throttled,expandSession:function(){pt({options:e,process:function(e){return a()?u(e):void 0}})},getSession:function(){return s},renewObservable:r,expireObservable:i,stop:function(){clearInterval(o)}}}var at,ct=/^([a-z]+)=([a-z0-9-]+)$/,ft="&",lt="_dd_s",dt=[];function pt(e,t){var n;if(void 0===t&&(t=0),at||(at=e),e===at){if(t>=50)return Z("Reach max lock retry"),void ht();var r,i=yt();if(_("cookie-lock")){if(i.lock)return void vt(e,t);if(r=g(),i.lock=r,mt(i,e.options),(i=yt()).lock!==r)return void vt(e,t)}var o=e.process(i);if(_("cookie-lock")&&(i=yt()).lock!==r)vt(e,t);else{if(o&&gt(o,e.options),_("cookie-lock")&&(!o||!bt(o))){if((i=yt()).lock!==r)return void vt(e,t);delete i.lock,mt(i,e.options),o=i}null===(n=e.after)||void 0===n||n.call(e,o||i),ht()}}else dt.push(e)}function vt(e,t){setTimeout(V((function(){pt(e,t+1)})),10)}function ht(){at=void 0;var e=dt.shift();e&&pt(e)}function gt(e,t){bt(e)?function(e){ce(lt,"",0,e)}(t):(e.expire=String(Date.now()+ot),mt(e,t))}function mt(e,t){ce(lt,function(e){return(t=e,Object.keys(t).map((function(e){return[e,t[e]]}))).map((function(e){return e[0]+"="+e[1]})).join(ft);var t}(e),ot,t)}function yt(){var e=fe(lt),t={};return function(e){return void 0!==e&&(-1!==e.indexOf(ft)||ct.test(e))}(e)&&e.split(ft).forEach((function(e){var n=ct.exec(e);if(null!==n){var r=n[1],i=n[2];t[r]=i}})),t}function bt(e){return t=e,0===Object.keys(t).length;var t}var wt=[];function xt(e,t,n){!function(e){var t=fe(lt),n=fe("_dd"),r=fe("_dd_r"),i=fe("_dd_l");if(!t){var o={};n&&(o.id=n),i&&/^[01]$/.test(i)&&(o.logs=i),r&&/^[012]$/.test(r)&&(o.rum=r),gt(o,e)}}(e);var r=ut(e,t,n);wt.push((function(){return r.stop()}));var i,o=new it(144e5);function s(){return{id:r.getSession().id,trackingType:r.getSession()[t]}}return wt.push((function(){return o.stop()})),r.renewObservable.subscribe((function(){o.setCurrent(s(),pe())})),r.expireObservable.subscribe((function(){o.closeCurrent(pe())})),r.expandOrRenewSession(),o.setCurrent(s(),[0,ge()][0]),i=k(window,["click","touchstart","keydown","scroll"],(function(){return r.expandOrRenewSession()}),{capture:!0,passive:!0}).stop,wt.push(i),function(e){var t=V((function(){"visible"===document.visibilityState&&e()})),n=S(document,"visibilitychange",t).stop;wt.push(n);var r=setInterval(t,6e4);wt.push((function(){clearInterval(r)}))}((function(){return r.expandSession()})),{findActiveSession:function(e){return o.find(e)},renewObservable:r.renewObservable,expireObservable:r.expireObservable}}var St;function kt(e){var t=xt(e.cookieOptions,"logs",(function(t){return function(e,t){var n=function(e){return e===St.NOT_TRACKED||e===St.TRACKED}(t)?t:Et(e);return{trackingType:n,isTracked:n===St.TRACKED}}(e,t)}));return{findTrackedSession:function(e){var n=t.findActiveSession(e);return n&&n.trackingType===St.TRACKED?{id:n.id}:void 0}}}function Et(e){return 0!==(t=e.sampleRate)&&100*Math.random()<=t?St.TRACKED:St.NOT_TRACKED;var t}function Tt(e){var t=window.DD_RUM;return t&&t.getInternalContext?t.getInternalContext(e):void 0}!function(e){e.NOT_TRACKED="0",e.TRACKED="1"}(St||(St={}));var Ot,Ct,Rt,Lt,Mt=function(t){var n,i,o=!1,s=ie(),u={},a=new ae,c=function(e,t){a.add((function(){return c(e,t)}))},f=function(){},l=new De(d);return n={logger:l,init:V((function(n){if(z()&&(n=function(t){return e(e({},t),{clientToken:"empty"})}(n)),function(e){return!o||(e.silentMultipleInit||r.error("DD_LOGS is already initialized."),!1)}(n)){var i=function(t){var n=Oe(t,Le);if(n)return e(e({},n),{forwardErrorsToLogs:!!t.forwardErrorsToLogs})}(n);i&&(c=t(i,l),f=function(){return E(void 0,n)},a.drain(),o=!0)}})),getLoggerGlobalContext:V(s.get),setLoggerGlobalContext:V(s.set),addLoggerGlobalContext:V(s.add),removeLoggerGlobalContext:V(s.remove),createLogger:V((function(t,n){return void 0===n&&(n={}),u[t]=new De(d,n.handler,n.level,e(e({},n.context),{logger:{name:t}})),u[t]})),getLogger:V((function(e){return u[e]})),getInitConfiguration:V((function(){return f()}))},i=e(e({},n),{onReady:function(e){e()}}),Object.defineProperty(i,"_setDebug",{get:function(){return te},enumerable:!1}),i;function d(e){c(e,T({date:Date.now(),view:{referrer:document.referrer,url:window.location.href}},s.get()))}}((function(e,t){var n=X(e),i=new je;return e.forwardErrorsToLogs&&(ze(i),Ge(i),function(e,t){var n=We().subscribe((function(e){"complete"===e.state&&i(d.XHR,e)})),r=Qe().subscribe((function(e){"complete"===e.state&&i(d.FETCH,e)}));function i(n,r){e.isIntakeUrl(r.url)||!function(e){return 0===e.status&&"opaque"!==e.responseType}(r)&&!function(e){return e.status>=500}(r)||t.notify({message:rt(n)+" error "+r.method+" "+r.url,resource:{method:r.method,statusCode:r.status,url:r.url},source:B,stack:nt(r.responseText,e)||"Failed to load",startClocks:r.startClocks})}}(e,i)),function(e,t,n,r,i){n.setExternalContextProvider((function(){var e;return T({session_id:null===(e=r.findTrackedSession())||void 0===e?void 0:e.id},Tt(),{view:{name:null,url:null,referrer:null}})}));var o,s=function(e,t,n){var r,i=((r={})[Me.error]=Ke(Me.error,t.eventRateLimiterThreshold,n),r[Me.warn]=Ke(Me.warn,t.eventRateLimiterThreshold,n),r[Me.info]=Ke(Me.info,t.eventRateLimiterThreshold,n),r[Me.debug]=Ke(Me.debug,t.eventRateLimiterThreshold,n),r.custom=Ke("custom",t.eventRateLimiterThreshold,n),r);return function(n,r){var o,s,u=n.date?n.date-ge():void 0,a=e.findTrackedSession(u);if(a){var c=T({service:t.service,session_id:a.id},r,Tt(u),n);if(!1!==(null===(o=t.beforeSend)||void 0===o?void 0:o.call(t,c))&&!(null!==(s=i[c.status])&&void 0!==s?s:i.custom).isLimitReached())return c}}}(r,e,c);if(z()){var u=j();o=function(e){return u.send("log",e)}}else{var a=function(e){var t,n=r(e.logsEndpointBuilder);function r(t){return new H(new q(t,e.batchBytesLimit),e.maxBatchSize,e.batchBytesLimit,e.maxMessageSize,e.flushTimeout)}return void 0!==e.replica&&(t=r(e.replica.logsEndpointBuilder)),{add:function(e){n.add(e),t&&t.add(e)}}}(e);o=function(e){return a.add(e)}}function c(e){i.error(e.message,T({date:e.startClocks.timeStamp,error:{kind:e.type,origin:e.source,stack:e.stack}},e.resource?{http:{method:e.resource.method,status_code:e.resource.statusCode,url:e.resource.url}}:void 0))}return t.subscribe(c),function(e,t){var n=s(e,t);n&&o(n)}}(e,i,n,function(e){if(void 0===document.cookie||null===document.cookie)return!1;try{var t="dd_cookie_test_"+g(),n="test";ce(t,n,p,e);var i=fe(t)===n;return le(t,e),i}catch(e){return r.error(e),!1}}(e.cookieOptions)&&!z()?kt(e):function(e){var t=Et(e)===St.TRACKED?{}:void 0;return{findTrackedSession:function(){return t}}}(e),t)}));Ot=function(){if("object"==typeof globalThis)return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get:function(){return this},configurable:!0});var e=_dd_temp_;return delete Object.prototype._dd_temp_,"object"!=typeof e&&(e="object"==typeof self?self:"object"==typeof window?window:{}),e}(),Rt=Mt,Lt=Ot[Ct="DD_LOGS"],Ot[Ct]=Rt,Lt&&Lt.q&&Lt.q.forEach((function(e){return re(e,"onReady callback threw an error:")()}))}();
!function(){"use strict";var e=function(){return(e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function t(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),i=0;for(t=0;t<n;t++)for(var o=arguments[t],s=0,u=o.length;s<u;s++,i++)r[i]=o[s];return r}var n={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)},r="?";function i(e,t){var n,i=void 0===t?0:+t;try{if(n=function(e){var t=u(e,"stacktrace");if(!t)return;for(var n,i=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,o=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\((.*)\))? in (.*):\s*$/i,s=t.split("\n"),a=[],c=0;c<s.length;c+=2){var f=void 0;i.exec(s[c])?f={args:[],column:void 0,func:(n=i.exec(s[c]))[3],line:+n[1],url:n[2]}:o.exec(s[c])&&(f={args:(n=o.exec(s[c]))[5]?n[5].split(","):[],column:+n[2],func:n[3]||n[4],line:+n[1],url:n[6]}),f&&(!f.func&&f.line&&(f.func=r),f.context=[s[c+1]],a.push(f))}if(!a.length)return;return{stack:a,message:u(e,"message"),name:u(e,"name")}}(e))return n}catch(e){if(o)throw e}try{if(n=function(e){var t=u(e,"stack");if(!t)return;for(var n,i,o,s,a=/^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\/).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,f=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|resource|capacitor|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i,l=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,d=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,p=/\((\S*)(?::(\d+))(?::(\d+))\)/,v=t.split("\n"),h=[],g=0,m=v.length;g<m;g+=1){if(a.exec(v[g])){var y=(o=a.exec(v[g]))[2]&&0===o[2].indexOf("native");n=o[2]&&0===o[2].indexOf("eval"),i=p.exec(o[2]),n&&i&&(o[2]=i[1],o[3]=i[2],o[4]=i[3]),s={args:y?[o[2]]:[],column:o[4]?+o[4]:void 0,func:o[1]||r,line:o[3]?+o[3]:void 0,url:y?void 0:o[2]}}else if(l.exec(v[g]))s={args:[],column:(o=l.exec(v[g]))[4]?+o[4]:void 0,func:o[1]||r,line:+o[3],url:o[2]};else{if(!f.exec(v[g]))continue;n=(o=f.exec(v[g]))[3]&&o[3].indexOf(" > eval")>-1,i=d.exec(o[3]),n&&i?(o[3]=i[1],o[4]=i[2],o[5]=void 0):0!==g||o[5]||c(e.columnNumber)||(h[0].column=e.columnNumber+1),s={args:o[2]?o[2].split(","):[],column:o[5]?+o[5]:void 0,func:o[1]||r,line:o[4]?+o[4]:void 0,url:o[3]}}!s.func&&s.line&&(s.func=r),h.push(s)}if(!h.length)return;return{stack:h,message:u(e,"message"),name:u(e,"name")}}(e))return n}catch(e){if(o)throw e}try{if(n=function(e){var t=u(e,"message");if(!t)return;var n=t.split("\n");if(n.length<4)return;var i,o=/^\s*Line (\d+) of linked script ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,s=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|https?|blob)\S+)(?:: in function (\S+))?\s*$/i,c=/^\s*Line (\d+) of function script\s*$/i,f=[],l=window&&window.document&&window.document.getElementsByTagName("script"),d=[];for(var p in l)a(l,p)&&!l[p].src&&d.push(l[p]);for(var v=2;v<n.length;v+=2){var h=void 0;if(o.exec(n[v]))h={args:[],column:void 0,func:(i=o.exec(n[v]))[3],line:+i[1],url:i[2]};else if(s.exec(n[v]))h={args:[],column:void 0,func:(i=s.exec(n[v]))[4],line:+i[1],url:i[3]};else if(c.exec(n[v])){i=c.exec(n[v]),h={url:window.location.href.replace(/#.*$/,""),args:[],column:void 0,func:"",line:+i[1]}}h&&(h.func||(h.func=r),h.context=[n[v+1]],f.push(h))}if(!f.length)return;return{stack:f,message:n[0],name:u(e,"name")}}(e))return n}catch(e){if(o)throw e}try{if(n=s(e,i+1))return n}catch(e){if(o)throw e}return{message:u(e,"message"),name:u(e,"name"),stack:[]}}var o=!1;function s(e,t){for(var n,o,a=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,c=[],f={},l=!1,d=s.caller;d&&!l;d=d.caller)d!==i&&(o={args:[],column:void 0,func:r,line:void 0,url:void 0},n=a.exec(d.toString()),d.name?o.func=d.name:n&&(o.func=n[1]),void 0===o.func&&(o.func=n?n.input.substring(0,n.input.indexOf("{")):void 0),f[d.toString()]?l=!0:f[d.toString()]=!0,c.push(o));t&&c.splice(0,t);var p={stack:c,message:u(e,"message"),name:u(e,"name")};return function(e,t,n){var r={url:t,line:n?+n:void 0};if(r.url&&r.line){e.incomplete=!1;var i=e.stack;if(i.length>0&&i[0].url===r.url){if(i[0].line===r.line)return!1;if(!i[0].line&&i[0].func===r.func)return i[0].line=r.line,i[0].context=r.context,!1}return i.unshift(r),e.partial=!0,!0}e.incomplete=!0}(p,u(e,"sourceURL")||u(e,"fileName"),u(e,"line")||u(e,"lineNumber")),p}function u(e,t){if("object"==typeof e&&e&&t in e){var n=e[t];return"string"==typeof n?n:void 0}}function a(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function c(e){return void 0===e}var f,l,d=1e3,p=6e4;function v(e,t,n){var r,i,o=!n||void 0===n.leading||n.leading,s=!n||void 0===n.trailing||n.trailing,u=!1;return{throttled:function(){for(var n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];u?r=n:(o?e.apply(void 0,n):r=n,u=!0,i=setTimeout((function(){s&&r&&e.apply(void 0,r),u=!1,r=void 0}),t))},cancel:function(){clearTimeout(i),u=!1,r=void 0}}}function h(e){return e?(parseInt(e,10)^16*Math.random()>>parseInt(e,10)/4).toString(16):"10000000-1000-4000-8000-100000000000".replace(/[018]/g,h)}function g(){}function m(e,t,n){if(null==e)return JSON.stringify(e);var r=[!1,void 0];y(e)&&(r=[!0,e.toJSON],delete e.toJSON);var i,o,s=[!1,void 0];"object"==typeof e&&y(i=Object.getPrototypeOf(e))&&(s=[!0,i.toJSON],delete i.toJSON);try{o=JSON.stringify(e,t,n)}catch(e){o="<error: unable to serialize object>"}finally{r[0]&&(e.toJSON=r[1]),s[0]&&(i.toJSON=s[1])}return o}function y(e){return"object"==typeof e&&null!==e&&Object.prototype.hasOwnProperty.call(e,"toJSON")}function b(e,t){return-1!==e.indexOf(t)}function w(e){return Object.keys(e).map((function(t){return e[t]}))}function x(e,t,n,r){return S(e,[t],n,r)}function S(e,t,n,r){var i=void 0===r?{}:r,o=i.once,s=i.capture,u=i.passive,a=W(o?function(e){f(),n(e)}:n),c=u?{capture:s,passive:u}:s;t.forEach((function(t){return e.addEventListener(t,a,c)}));var f=function(){return t.forEach((function(t){return e.removeEventListener(t,a,c)}))};return{stop:f}}function E(e,t,n){if(void 0===n&&(n=function(){if("undefined"!=typeof WeakSet){var e=new WeakSet;return{hasAlreadyBeenSeen:function(t){var n=e.has(t);return n||e.add(t),n}}}var t=[];return{hasAlreadyBeenSeen:function(e){var n=t.indexOf(e)>=0;return n||t.push(e),n}}}()),void 0===t)return e;if("object"!=typeof t||null===t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){var r=t.flags||[t.global?"g":"",t.ignoreCase?"i":"",t.multiline?"m":"",t.sticky?"y":"",t.unicode?"u":""].join("");return new RegExp(t.source,r)}if(!n.hasAlreadyBeenSeen(t)){if(Array.isArray(t)){for(var i=Array.isArray(e)?e:[],o=0;o<t.length;++o)i[o]=E(i[o],t[o],n);return i}var s,u="object"==(null===(s=e)?"null":Array.isArray(s)?"array":typeof s)?e:{};for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&(u[a]=E(u[a],t[a],n));return u}}function k(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var o=i[r];null!=o&&(e=E(e,o))}return e}!function(e){e.DOCUMENT="document",e.XHR="xhr",e.BEACON="beacon",e.FETCH="fetch",e.CSS="css",e.JS="js",e.IMAGE="image",e.FONT="font",e.MEDIA="media",e.OTHER="other"}(f||(f={})),function(e){e.FETCH="fetch",e.XHR="xhr"}(l||(l={}));var T,O,C="agent",R="console",L="logger",M="network",B="source";function A(e){var t=D(e);return e.stack.forEach((function(e){var n="?"===e.func?"<anonymous>":e.func,r=e.args&&e.args.length>0?"("+e.args.join(", ")+")":"",i=e.line?":"+e.line:"",o=e.line&&e.column?":"+e.column:"";t+="\n at "+n+r+" @ "+e.url+i+o})),t}function D(e){return(e.name||"Error")+": "+e.message}function N(){var e,t=new Error;if(!t.stack)try{throw t}catch(e){}return V((function(){var n=i(t);n.stack=n.stack.slice(2),e=A(n)})),e}function I(e){return!!O&&O.has(e)}function _(){var e=I("event-bridge")?window.DatadogEventBridge:null;if(e)return{getAllowedWebViewHosts:function(){return JSON.parse(e.getAllowedWebViewHosts())},send:function(t,n){e.send(JSON.stringify({eventType:t,event:n}))}}}function j(){var e=_();return!!e&&b(e.getAllowedWebViewHosts(),window.location.hostname)}!function(e){e.HANDLED="handled",e.UNHANDLED="unhandled"}(T||(T={}));var z,U=/[^\u0000-\u007F]/,P=function(){function e(e,t,n,r,i,o){void 0===o&&(o=g),this.request=e,this.maxSize=t,this.bytesLimit=n,this.maxMessageSize=r,this.flushTimeout=i,this.beforeUnloadCallback=o,this.pushOnlyBuffer=[],this.upsertBuffer={},this.bufferBytesSize=0,this.bufferMessageCount=0,this.flushOnVisibilityHidden(),this.flushPeriodically()}return e.prototype.add=function(e){this.addOrUpdate(e)},e.prototype.upsert=function(e,t){this.addOrUpdate(e,t)},e.prototype.flush=function(e){if(0!==this.bufferMessageCount){var n=t(this.pushOnlyBuffer,w(this.upsertBuffer));this.request.send(n.join("\n"),this.bufferBytesSize,e),this.pushOnlyBuffer=[],this.upsertBuffer={},this.bufferBytesSize=0,this.bufferMessageCount=0}},e.prototype.sizeInBytes=function(e){return U.test(e)?void 0!==window.TextEncoder?(new TextEncoder).encode(e).length:new Blob([e]).size:e.length},e.prototype.addOrUpdate=function(e,t){var r=this.process(e),i=r.processedMessage,o=r.messageBytesSize;o>=this.maxMessageSize?n.warn("Discarded a message whose size was bigger than the maximum allowed size "+this.maxMessageSize+"KB."):(this.hasMessageFor(t)&&this.remove(t),this.willReachedBytesLimitWith(o)&&this.flush("willReachedBytesLimitWith"),this.push(i,o,t),this.isFull()&&this.flush("isFull"))},e.prototype.process=function(e){var t=m(e);return{processedMessage:t,messageBytesSize:this.sizeInBytes(t)}},e.prototype.push=function(e,t,n){this.bufferMessageCount>0&&(this.bufferBytesSize+=1),void 0!==n?this.upsertBuffer[n]=e:this.pushOnlyBuffer.push(e),this.bufferBytesSize+=t,this.bufferMessageCount+=1},e.prototype.remove=function(e){var t=this.upsertBuffer[e];delete this.upsertBuffer[e];var n=this.sizeInBytes(t);this.bufferBytesSize-=n,this.bufferMessageCount-=1,this.bufferMessageCount>0&&(this.bufferBytesSize-=1)},e.prototype.hasMessageFor=function(e){return void 0!==e&&void 0!==this.upsertBuffer[e]},e.prototype.willReachedBytesLimitWith=function(e){return this.bufferBytesSize+e+1>=this.bytesLimit},e.prototype.isFull=function(){return this.bufferMessageCount===this.maxSize||this.bufferBytesSize>=this.bytesLimit},e.prototype.flushPeriodically=function(){var e=this;setTimeout(W((function(){e.flush("flushPeriodically"),e.flushPeriodically()})),this.flushTimeout)},e.prototype.flushOnVisibilityHidden=function(){var e=this;navigator.sendBeacon&&(x(window,"beforeunload",this.beforeUnloadCallback),x(document,"visibilitychange",(function(){"hidden"===document.visibilityState&&e.flush("visibilitychange")})),x(window,"beforeunload",(function(){return e.flush("beforeunload")})))},e}(),H=!1,F=function(){function e(e,t){this.endpointBuilder=e,this.bytesLimit=t}return e.prototype.send=function(e,t,n){var r=this.endpointBuilder.build(),i=!!navigator.sendBeacon&&t<this.bytesLimit;if(i)try{if(navigator.sendBeacon(r,e))return}catch(e){!function(e){q||(q=!0,Z(e))}(e)}var o=new XMLHttpRequest;o.addEventListener("loadend",W((function(e){return function(e){var o=null==e?void 0:e.currentTarget;o.status>=200&&o.status<300||H||(H=!0,Y("XHR fallback failed",{on_line:navigator.onLine,size:t,url:r,try_beacon:i,flush_reason:n,event:{is_trusted:e.isTrusted,total:e.total,loaded:e.loaded},request:{status:o.status,ready_state:o.readyState,response_text:o.responseText.slice(0,512)}}))}(e)}))),o.open("POST",r,!0),o.send(e)},e}(),q=!1;!function(e){e.info="info",e.error="error"}(z||(z={}));var $,K,G={maxMessagesPerPage:0,sentMessageCount:0};function J(e){var t;if(j()){var n=_();$=function(e){return n.send("internal_log",i(e))}}else if(e.internalMonitoringEndpointBuilder){var r=function(e){var t,n=r(e.internalMonitoringEndpointBuilder);function r(t){return new P(new F(t,e.batchBytesLimit),e.maxBatchSize,e.batchBytesLimit,e.maxMessageSize,e.flushTimeout)}return void 0!==e.replica&&(t=r(e.replica.internalMonitoringEndpointBuilder)),{add:function(e){n.add(e),t&&t.add(e)}}}(e);$=function(e){return r.add(i(e))}}function i(e){return k({date:(new Date).getTime()},void 0!==t?t():{},e)}return function(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];t.forEach((function(t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}))}(G,{maxMessagesPerPage:e.maxInternalMonitoringMessagesPerPage,sentMessageCount:0}),{setExternalContextProvider:function(e){t=e}}}function X(e,t,n){var r=n.value;n.value=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=$?W(r):r;return n.apply(this,e)}}function W(e){return function(){return V(e,this,arguments)}}function V(e,t,n){try{return e.apply(t,n)}catch(e){te(e);try{Z(e)}catch(e){te(e)}}}function Y(t,r){!function(e,t){G.debugMode&&n.log("[MONITORING MESSAGE]",e,t)}(t,r),Q(e(e({message:t},r),{status:z.info}))}function Z(t){Q(e(e({},function(e){if(e instanceof Error){var t=i(e);return{error:{kind:t.name,stack:A(t)},message:t.message}}return{error:{stack:"Not an instance of error"},message:"Uncaught "+m(e)}}(t)),{status:z.error}))}function Q(e){$&&G.sentMessageCount<G.maxMessagesPerPage&&(G.sentMessageCount+=1,$(e))}function ee(e){G.debugMode=e}function te(e){G.debugMode&&n.error("[INTERNAL ERROR]",e)}function ne(e,t){return function(){for(var r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];try{return e.apply(void 0,r)}catch(e){n.error(t,e)}}}function re(){var e={};return{get:function(){return e},add:function(t,n){e[t]=n},remove:function(t){delete e[t]},set:function(t){e=t}}}!function(e){e.RELEASE="release",e.CANARY="canary",e.E2E_TEST="e2e-test"}(K||(K={}));var ie,oe,se,ue=function(){function e(){this.buffer=[]}return e.prototype.add=function(e){this.buffer.push(e)>500&&this.buffer.splice(0,1)},e.prototype.drain=function(){this.buffer.forEach((function(e){return e()})),this.buffer.length=0},e}();function ae(e,t,n,r){var i=new Date;i.setTime(i.getTime()+n);var o="expires="+i.toUTCString(),s=r&&r.crossSite?"none":"strict",u=r&&r.domain?";domain="+r.domain:"",a=r&&r.secure?";secure":"";document.cookie=e+"="+t+";"+o+";path=/;samesite="+s+u+a}function ce(e){return function(e,t){var n=new RegExp("(?:^|;)\\s*"+t+"\\s*=\\s*([^;]+)").exec(e);return n?n[1]:void 0}(document.cookie,e)}function fe(e,t){ae(e,"",0,t)}function le(){return Date.now()}function de(){return performance.now()}function pe(){return{relative:de(),timeStamp:le()}}function ve(e,t){return t-e}function he(){return void 0===oe&&(oe=performance.timing.navigationStart),oe}function ge(e){return me(e,function(e){if(e.origin)return e.origin;var t=e.host.replace(/(:80|:443)$/,"");return e.protocol+"//"+t}(window.location)).href}function me(e,t){if(function(){if(void 0!==se)return se;try{var e=new URL("http://test/path");return se="http://test/path"===e.href}catch(e){se=!1}return se}())return void 0!==t?new URL(e,t):new URL(e);if(void 0===t&&!/:/.test(e))throw new Error("Invalid URL: '"+e+"'");var n=document,r=n.createElement("a");if(void 0!==t){var i=(n=document.implementation.createHTMLDocument("")).createElement("base");i.href=t,n.head.appendChild(i),n.body.appendChild(r)}return r.href=e,r}var ye={logs:"logs",rum:"rum",sessionReplay:"session-replay"},be={logs:"logs",rum:"rum",sessionReplay:"replay"},we="datadoghq.com";function xe(e,t,n,r,i){var o=e.site,s=void 0===o?we:o,u=e.clientToken,a=s.split("."),c=a.pop(),f="https://"+(ye[n]+".browser-intake-"+a.join("-")+"."+c)+"/api/v2/"+be[n],l=e.proxyUrl&&ge(e.proxyUrl);return{build:function(){var e="ddsource="+(i||"browser")+"&ddtags="+encodeURIComponent(["sdk_version:"+t.sdkVersion].concat(r).join(","))+"&dd-api-key="+u+"&dd-evp-origin-version="+encodeURIComponent(t.sdkVersion)+"&dd-evp-origin=browser&dd-request-id="+h();"rum"===n&&(e+="&batch_time="+le());var o=f+"?"+e;return l?l+"?ddforward="+encodeURIComponent(o):o},buildIntakeUrl:function(){return l?l+"?ddforward":f}}}var Se=/[^a-z0-9_:./-]/;function Ee(e,t){var r=200-e.length-1;return(t.length>r||Se.test(t))&&n.warn(e+" value doesn't meet tag requirements and will be sanitized"),e+":"+t.replace(/,/g,"_")}function ke(t,n){var r=function(e){var t=e.env,n=e.service,r=e.version,i=e.datacenter,o=[];return t&&o.push(Ee("env",t)),n&&o.push(Ee("service",n)),r&&o.push(Ee("version",r)),i&&o.push(Ee("datacenter",i)),o}(t),i=function(t,n,r){if(n.buildMode===K.E2E_TEST){var i=function(e){return{build:function(){return e},buildIntakeUrl:function(){return e}}};return{logsEndpointBuilder:i("<<< E2E LOGS ENDPOINT >>>"),rumEndpointBuilder:i("<<< E2E RUM ENDPOINT >>>"),sessionReplayEndpointBuilder:i("<<< E2E SESSION REPLAY ENDPOINT >>>"),internalMonitoringEndpointBuilder:i("<<< E2E INTERNAL MONITORING ENDPOINT >>>")}}var o={logsEndpointBuilder:xe(t,n,"logs",r),rumEndpointBuilder:xe(t,n,"rum",r),sessionReplayEndpointBuilder:xe(t,n,"sessionReplay",r)};if(t.internalMonitoringApiKey)return e(e({},o),{internalMonitoringEndpointBuilder:xe(e(e({},t),{clientToken:t.internalMonitoringApiKey}),n,"logs",r,"browser-agent-internal-monitoring")});return o}(t,n,r),o=w(i).map((function(e){return e.buildIntakeUrl()})),s=function(t,n,r,i){if(!t.replica)return;var o=e(e({},t),{site:we,clientToken:t.replica.clientToken}),s={logsEndpointBuilder:xe(o,n,"logs",i),rumEndpointBuilder:xe(o,n,"rum",i),internalMonitoringEndpointBuilder:xe(o,n,"logs",i,"browser-agent-internal-monitoring")};return r.push.apply(r,w(s).map((function(e){return e.buildIntakeUrl()}))),e({applicationId:t.replica.applicationId},s)}(t,n,o,r);return e(e({isIntakeUrl:function(e){return o.some((function(t){return 0===e.indexOf(t)}))}},i),{replica:s})}function Te(t,r){var i;if(t&&t.clientToken){var o,s;if(void 0===t.sampleRate||function(e){return"number"==typeof e}(o=t.sampleRate)&&o>=0&&o<=100)return s=t.enableExperimentalFeatures,Array.isArray(s)&&(O||(O=new Set(s)),s.filter((function(e){return"string"==typeof e})).forEach((function(e){O.add(e)}))),e(e({},ke(t,r)),{beforeSend:t.beforeSend&&ne(t.beforeSend,"beforeSend threw an error:"),cookieOptions:Oe(t),sampleRate:null!==(i=t.sampleRate)&&void 0!==i?i:100,service:t.service,silentMultipleInit:!!t.silentMultipleInit,batchBytesLimit:16384,eventRateLimiterThreshold:3e3,maxInternalMonitoringMessagesPerPage:15,flushTimeout:3e4,maxBatchSize:50,maxMessageSize:262144});n.error("Sample Rate should be a number between 0 and 100")}else n.error("Client Token is not configured, we will not send any data.")}function Oe(e){var t={};return t.secure=function(e){return!!e.useSecureSessionCookie||!!e.useCrossSiteSessionCookie}(e),t.crossSite=!!e.useCrossSiteSessionCookie,e.trackSessionAcrossSubdomains&&(t.domain=function(){if(void 0===ie){for(var e="dd_site_test_"+h(),t=window.location.hostname.split("."),n=t.pop();t.length&&!ce(e);)n=t.pop()+"."+n,ae(e,"test",d,{domain:n});fe(e,{domain:n}),ie=n}return ie}()),t}var Ce,Re={buildMode:"release",sdkVersion:"4.2.0"};var Le={debug:"debug",error:"error",info:"info",warn:"warn"},Me=((Ce={})[Le.debug]=0,Ce[Le.info]=1,Ce[Le.warn]=2,Ce[Le.error]=3,Ce),Be=(Object.keys(Le),"console"),Ae="http",De=function(){function t(e,t,n,r){void 0===t&&(t=Ae),void 0===n&&(n=Le.debug),void 0===r&&(r={}),this.sendLog=e,this.handlerType=t,this.level=n,this.contextManager=re(),this.contextManager.set(r)}return t.prototype.log=function(t,r,i){if(void 0===i&&(i=Le.info),Me[i]>=Me[this.level]){var o=Array.isArray(this.handlerType)?this.handlerType:[this.handlerType];b(o,Ae)&&this.sendLog(e({message:t,status:i},k(this.contextManager.get(),r))),b(o,Be)&&n.log(i+": "+t,k(this.contextManager.get(),r))}},t.prototype.debug=function(e,t){this.log(e,t,Le.debug)},t.prototype.info=function(e,t){this.log(e,t,Le.info)},t.prototype.warn=function(e,t){this.log(e,t,Le.warn)},t.prototype.error=function(e,t){var n={error:{origin:L}};this.log(e,k(n,t),Le.error)},t.prototype.setContext=function(e){this.contextManager.set(e)},t.prototype.addContext=function(e,t){this.contextManager.add(e,t)},t.prototype.removeContext=function(e){this.contextManager.remove(e)},t.prototype.setHandler=function(e){this.handlerType=e},t.prototype.setLevel=function(e){this.level=e},function(e,t,n,r){var i,o=arguments.length,s=o<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,n,r);else for(var u=e.length-1;u>=0;u--)(i=e[u])&&(s=(o<3?i(s):o>3?i(t,n,s):i(t,n))||s);o>3&&s&&Object.defineProperty(t,n,s)}([X],t.prototype,"log",null),t}();var Ne,Ie,_e=function(){function e(e){this.onFirstSubscribe=e,this.observers=[]}return e.prototype.subscribe=function(e){var t=this;return!this.observers.length&&this.onFirstSubscribe&&(this.onLastUnsubscribe=this.onFirstSubscribe()||void 0),this.observers.push(e),{unsubscribe:function(){t.observers=t.observers.filter((function(t){return e!==t})),!t.observers.length&&t.onLastUnsubscribe&&t.onLastUnsubscribe()}}},e.prototype.notify=function(e){this.observers.forEach((function(t){return t(e)}))},e}();function je(t){(function(){Ie||(Ie=new _e,Ne=console.error,console.error=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];var r=N();V((function(){Ne.apply(console,t);var n=e(e({},ze(t,r)),{source:R,startClocks:pe(),handling:T.HANDLED});Ie.notify(n)}))});return Ie})().subscribe((function(e){return t.notify(e)}))}function ze(e,n){var r=function(e,t){for(var n=0;n<e.length;n+=1){var r=e[n];if(t(r,n,e))return r}}(e,(function(e){return e instanceof Error}));return{message:t(["console error:"],e).map((function(e){return function(e){if("string"==typeof e)return e;if(e instanceof Error)return D(i(e));return m(e,void 0,2)}(e)})).join(" "),stack:r?A(i(r)):void 0,handlingStack:n}}function Ue(e,t,n){var r=e[t],i=n(r),o=function(){return i.apply(this,arguments)};return e[t]=o,{stop:function(){e[t]===o?e[t]=r:i=r}}}function Pe(e,t,n){var r=n.before,i=n.after;return Ue(e,t,(function(e){return function(){var t,n=arguments;return r&&V(r,this,n),"function"==typeof e&&(t=e.apply(this,n)),i&&V(i,this,n),t}}))}var He,Fe=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/;function qe(e){var t=function(e){return Pe(window,"onerror",{before:function(t,n,r,o,s){var u;if(s)u=i(s),e(u,s);else{var a,c={url:n,column:o,line:r},f=t;if("[object String]"==={}.toString.call(t)){var l=Fe.exec(f);l&&(a=l[1],f=l[2])}e(u={name:a,message:"string"==typeof f?f:void 0,stack:[c]},t)}}})}(e).stop,n=function(e){return Pe(window,"onunhandledrejection",{before:function(t){var n=t.reason||"Empty reason",r=i(n);e(r,n)}})}(e).stop;return{stop:function(){t(),n()}}}function $e(e){return qe((function(t,n){var r=function(e,t,n,r){return e&&(void 0!==e.message||t instanceof Error)?{message:e.message||"Empty message",stack:A(e),handlingStack:r,type:e.name}:{message:n+" "+m(t),stack:"No stack, consider using an instance of Error",handlingStack:r,type:e&&e.name}}(t,n,"Uncaught"),i=r.stack,o=r.message,s=r.type;e.notify({message:o,stack:i,type:s,source:B,startClocks:pe(),originalError:n,handling:T.UNHANDLED})}))}function Ke(e,t,n){var r=0,i=!1;return{isLimitReached:function(){if(0===r&&setTimeout((function(){r=0}),p),(r+=1)<=t||i)return i=!1,!1;if(r===t+1){i=!0;try{n({message:"Reached max number of "+e+"s by minute: "+t,source:C,startClocks:pe()})}finally{i=!1}}return!0}}}var Ge,Je=new WeakMap;function Xe(){var e;return He||(e=new _e((function(){var t=Pe(XMLHttpRequest.prototype,"open",{before:We}).stop,n=Pe(XMLHttpRequest.prototype,"send",{before:function(){Ve.call(this,e)}}).stop,r=Pe(XMLHttpRequest.prototype,"abort",{before:Ye}).stop;return function(){t(),n(),r()}})),He=e),He}function We(e,t){Je.set(this,{state:"open",method:e,url:ge(t)})}function Ve(t){var n=this,r=Je.get(this);if(r){var i=r;i.state="start",i.startTime=de(),i.startClocks=pe(),i.isAborted=!1,i.xhr=this;var o=!1,s=Pe(this,"onreadystatechange",{before:function(){this.readyState===XMLHttpRequest.DONE&&u()}}).stop,u=W((function(){if(n.removeEventListener("loadend",u),s(),!o){o=!0;var a=r;a.state="complete",a.duration=ve(i.startClocks.timeStamp,le()),a.status=n.status,t.notify(e({},a))}}));this.addEventListener("loadend",u),t.notify(i)}}function Ye(){var e=Je.get(this);e&&(e.isAborted=!0)}function Ze(){var e;return Ge||(e=new _e((function(){if(window.fetch)return Ue(window,"fetch",(function(t){return function(n,r){var i,o=V(Qe,null,[e,n,r]);return o?(i=t.call(this,o.input,o.init),V(et,null,[e,i,o])):i=t.call(this,n,r),i}})).stop})),Ge=e),Ge}function Qe(e,t,n){var r=n&&n.method||"object"==typeof t&&t.method||"GET",i=ge("object"==typeof t&&t.url||t),o={state:"start",init:n,input:t,method:r,startClocks:pe(),url:i};return e.notify(o),o}function et(e,t,n){var r=function(t){var r=n;r.state="complete",r.duration=ve(r.startClocks.timeStamp,le()),"stack"in t||t instanceof Error?(r.status=0,r.isAborted=t instanceof DOMException&&t.code===DOMException.ABORT_ERR,r.error=t,e.notify(r)):"status"in t&&(r.response=t,r.responseType=t.type,r.status=t.status,r.isAborted=!1,e.notify(r))};t.then(W(r),W(r))}function tt(e,t){var n=Xe().subscribe((function(e){"complete"===e.state&&o(l.XHR,e)})),r=Ze().subscribe((function(e){"complete"===e.state&&o(l.FETCH,e)}));function o(n,r){function o(e){t.notify({message:rt(n)+" error "+r.method+" "+r.url,resource:{method:r.method,statusCode:r.status,url:r.url},source:M,stack:e||"Failed to load",startClocks:r.startClocks})}e.isIntakeUrl(r.url)||!function(e){return 0===e.status&&"opaque"!==e.responseType}(r)&&!function(e){return e.status>=500}(r)||("xhr"in r?function(e,t,n){"string"==typeof e.response?n(nt(e.response,t)):n(e.response)}(r.xhr,e,o):r.response?function(e,t,n){window.TextDecoder?e.body?function(e,t,n){!function(e,t,n){var r=e.getReader(),i=[],o=0;function s(){r.read().then(W((function(e){e.done?u():(i.push(e.value),(o+=e.value.length)>t?u():s())})),W((function(e){return n(e)})))}function u(){var e;if(r.cancel().catch(g),1===i.length)e=i[0];else{e=new Uint8Array(o);var s=0;i.forEach((function(t){e.set(t,s),s+=t.length}))}n(void 0,e.slice(0,t),e.length>t)}s()}(e,t,(function(e,t,r){if(e)n(e);else{var i=(new TextDecoder).decode(t);r&&(i+="..."),n(void 0,i)}}))}(e.clone().body,t.requestErrorResponseLengthLimit,(function(e,t){n(e?"Unable to retrieve response: "+e:t)})):n():e.clone().text().then(W((function(e){return n(nt(e,t))})),W((function(e){return n("Unable to retrieve response: "+e)})))}(r.response,e,o):r.error&&function(e,t,n){n(nt(A(i(e)),t))}(r.error,e,o))}return{stop:function(){n.unsubscribe(),r.unsubscribe()}}}function nt(e,t){return e.length>t.requestErrorResponseLengthLimit?e.substring(0,t.requestErrorResponseLengthLimit)+"...":e}function rt(e){return l.XHR===e?"XHR":"Fetch"}var it=function(){function e(e){var t=this;this.expireDelay=e,this.previousContexts=[],this.clearOldContextsInterval=setInterval((function(){return t.clearOldContexts()}),6e4)}return e.prototype.find=function(e){if(void 0===e||void 0!==this.current&&void 0!==this.currentStart&&e>=this.currentStart)return this.current;for(var t=0,n=this.previousContexts;t<n.length;t++){var r=n[t];if(e>r.endTime)break;if(e>=r.startTime)return r.context}},e.prototype.setCurrent=function(e,t){this.current=e,this.currentStart=t},e.prototype.getCurrent=function(){return this.current},e.prototype.clearCurrent=function(){this.current=void 0,this.currentStart=void 0},e.prototype.closeCurrent=function(e){void 0!==this.current&&void 0!==this.currentStart&&(this.previousContexts.unshift({endTime:e,context:this.current,startTime:this.currentStart}),this.clearCurrent())},e.prototype.clearOldContexts=function(){for(var e=de()-this.expireDelay;this.previousContexts.length>0&&this.previousContexts[this.previousContexts.length-1].startTime<e;)this.previousContexts.pop()},e.prototype.reset=function(){this.clearCurrent(),this.previousContexts=[]},e.prototype.stop=function(){clearInterval(this.clearOldContextsInterval)},e}(),ot=9e5,st=144e5;function ut(e,t,n){var r=new _e,i=new _e,o=setInterval(W((function(){pt({options:e,process:function(e){return f(e)?void 0:{}},after:u})})),1e3),s=function(){var e=yt();if(f(e))return e;return{}}();function u(e){return f(e)||(e={}),a()&&(!function(e){if(s.id!==e.id)return e.id&&f(s)&&c(e,"different id"),!0;if(s[t]!==e[t])return c(e,"different tracking type"),!0;return!1}(e)?s=e:(s={},i.notify())),e}function a(){return void 0!==s[t]}function c(e,n){Y("Session inconsistencies detected",{debug:{productKey:t,sessionCache:s,cookieSession:e,cause:n}})}function f(e){return(void 0===e.created||Date.now()-Number(e.created)<st)&&(void 0===e.expire||Date.now()<Number(e.expire))}return{expandOrRenewSession:v(W((function(){var i;pt({options:e,process:function(e){var r=u(e);return i=function(e){var r=n(e[t]),i=r.trackingType,o=r.isTracked;e[t]=i,o&&!e.id&&(e.id=h(),e.created=String(Date.now()));return o}(r),r},after:function(e){i&&!a()&&function(e){s=e,r.notify()}(e),s=e}})})),1e3).throttled,expandSession:function(){pt({options:e,process:function(e){return a()?u(e):void 0}})},getSession:function(){return s},renewObservable:r,expireObservable:i,stop:function(){clearInterval(o)}}}var at,ct=/^([a-z]+)=([a-z0-9-]+)$/,ft="&",lt="_dd_s",dt=[];function pt(e,t){var n;if(void 0===t&&(t=0),at||(at=e),e===at){if(t>=100)return Y("Reach max lock retry"),void ht();var r,i=yt();if(I("cookie-lock")){if(i.lock)return void vt(e,t);if(r=h(),i.lock=r,mt(i,e.options),(i=yt()).lock!==r)return void vt(e,t)}var o=e.process(i);if(I("cookie-lock")&&(i=yt()).lock!==r)vt(e,t);else{if(o&&gt(o,e.options),I("cookie-lock")&&(!o||!bt(o))){if((i=yt()).lock!==r)return void vt(e,t);delete i.lock,mt(i,e.options),o=i}null===(n=e.after)||void 0===n||n.call(e,o||i),ht()}}else dt.push(e)}function vt(e,t){setTimeout(W((function(){pt(e,t+1)})),10)}function ht(){at=void 0;var e=dt.shift();e&&pt(e)}function gt(e,t){bt(e)?function(e){ae(lt,"",0,e)}(t):(e.expire=String(Date.now()+ot),mt(e,t))}function mt(e,t){ae(lt,function(e){return(t=e,Object.keys(t).map((function(e){return[e,t[e]]}))).map((function(e){return e[0]+"="+e[1]})).join(ft);var t}(e),ot,t)}function yt(){var e=ce(lt),t={};return function(e){return void 0!==e&&(-1!==e.indexOf(ft)||ct.test(e))}(e)&&e.split(ft).forEach((function(e){var n=ct.exec(e);if(null!==n){var r=n[1],i=n[2];t[r]=i}})),t}function bt(e){return t=e,0===Object.keys(t).length;var t}var wt=[];function xt(e,t,n){!function(e){var t=ce(lt),n=ce("_dd"),r=ce("_dd_r"),i=ce("_dd_l");if(!t){var o={};n&&(o.id=n),i&&/^[01]$/.test(i)&&(o.logs=i),r&&/^[012]$/.test(r)&&(o.rum=r),gt(o,e)}}(e);var r=ut(e,t,n);wt.push((function(){return r.stop()}));var i,o=new it(144e5);function s(){return{id:r.getSession().id,trackingType:r.getSession()[t]}}return wt.push((function(){return o.stop()})),r.renewObservable.subscribe((function(){o.setCurrent(s(),de())})),r.expireObservable.subscribe((function(){o.closeCurrent(de())})),r.expandOrRenewSession(),o.setCurrent(s(),[0,he()][0]),i=S(window,["click","touchstart","keydown","scroll"],(function(){return r.expandOrRenewSession()}),{capture:!0,passive:!0}).stop,wt.push(i),function(e){var t=W((function(){"visible"===document.visibilityState&&e()})),n=x(document,"visibilitychange",t).stop;wt.push(n);var r=setInterval(t,6e4);wt.push((function(){clearInterval(r)}))}((function(){return r.expandSession()})),{findActiveSession:function(e){return o.find(e)},renewObservable:r.renewObservable,expireObservable:r.expireObservable}}var St;function Et(e){var t=xt(e.cookieOptions,"logs",(function(t){return function(e,t){var n=function(e){return e===St.NOT_TRACKED||e===St.TRACKED}(t)?t:kt(e);return{trackingType:n,isTracked:n===St.TRACKED}}(e,t)}));return{findTrackedSession:function(e){var n=t.findActiveSession(e);return n&&n.trackingType===St.TRACKED?{id:n.id}:void 0}}}function kt(e){return 0!==(t=e.sampleRate)&&100*Math.random()<=t?St.TRACKED:St.NOT_TRACKED;var t}function Tt(e){var t=window.DD_RUM;return t&&t.getInternalContext?t.getInternalContext(e):void 0}!function(e){e.NOT_TRACKED="0",e.TRACKED="1"}(St||(St={}));var Ot,Ct,Rt,Lt,Mt=function(t){var r,i,o=!1,s=re(),u={},a=new ue,c=function(e,t){a.add((function(){return c(e,t)}))},f=function(){},l=new De(d);return r={logger:l,init:W((function(r){if(j()&&(r=function(t){return e(e({},t),{clientToken:"empty"})}(r)),function(e){return!o||(e.silentMultipleInit||n.error("DD_LOGS is already initialized."),!1)}(r)){var i=function(t){var n=Te(t,Re);if(n)return e(e({},n),{forwardErrorsToLogs:!!t.forwardErrorsToLogs,requestErrorResponseLengthLimit:32768})}(r);i&&(c=t(i,l),f=function(){return E(void 0,r)},a.drain(),o=!0)}})),getLoggerGlobalContext:W(s.get),setLoggerGlobalContext:W(s.set),addLoggerGlobalContext:W(s.add),removeLoggerGlobalContext:W(s.remove),createLogger:W((function(t,n){return void 0===n&&(n={}),u[t]=new De(d,n.handler,n.level,e(e({},n.context),{logger:{name:t}})),u[t]})),getLogger:W((function(e){return u[e]})),getInitConfiguration:W((function(){return f()}))},i=e(e({},r),{onReady:function(e){e()}}),Object.defineProperty(i,"_setDebug",{get:function(){return ee},enumerable:!1}),i;function d(e){c(e,k({date:Date.now(),view:{referrer:document.referrer,url:window.location.href}},s.get()))}}((function(e,t){var r=J(e),i=new _e;return e.forwardErrorsToLogs&&(je(i),$e(i),tt(e,i)),function(e,t,n,r,i){n.setExternalContextProvider((function(){var e;return k({session_id:null===(e=r.findTrackedSession())||void 0===e?void 0:e.id},Tt(),{view:{name:null,url:null,referrer:null}})}));var o,s=function(e,t,n){var r,i=((r={})[Le.error]=Ke(Le.error,t.eventRateLimiterThreshold,n),r[Le.warn]=Ke(Le.warn,t.eventRateLimiterThreshold,n),r[Le.info]=Ke(Le.info,t.eventRateLimiterThreshold,n),r[Le.debug]=Ke(Le.debug,t.eventRateLimiterThreshold,n),r.custom=Ke("custom",t.eventRateLimiterThreshold,n),r);return function(n,r){var o,s,u=n.date?n.date-he():void 0,a=e.findTrackedSession(u);if(a){var c=k({service:t.service,session_id:a.id},r,Tt(u),n);if(!1!==(null===(o=t.beforeSend)||void 0===o?void 0:o.call(t,c))&&!(null!==(s=i[c.status])&&void 0!==s?s:i.custom).isLimitReached())return c}}}(r,e,c);if(j()){var u=_();o=function(e){return u.send("log",e)}}else{var a=function(e){var t,n=r(e.logsEndpointBuilder);function r(t){return new P(new F(t,e.batchBytesLimit),e.maxBatchSize,e.batchBytesLimit,e.maxMessageSize,e.flushTimeout)}return void 0!==e.replica&&(t=r(e.replica.logsEndpointBuilder)),{add:function(e){n.add(e),t&&t.add(e)}}}(e);o=function(e){return a.add(e)}}function c(e){i.error(e.message,k({date:e.startClocks.timeStamp,error:{kind:e.type,origin:e.source,stack:e.stack}},e.resource?{http:{method:e.resource.method,status_code:e.resource.statusCode,url:e.resource.url}}:void 0))}return t.subscribe(c),function(e,t){var n=s(e,t);n&&o(n)}}(e,i,r,function(e){if(void 0===document.cookie||null===document.cookie)return!1;try{var t="dd_cookie_test_"+h(),r="test";ae(t,r,d,e);var i=ce(t)===r;return fe(t,e),i}catch(e){return n.error(e),!1}}(e.cookieOptions)&&!j()?Et(e):function(e){var t=kt(e)===St.TRACKED?{}:void 0;return{findTrackedSession:function(){return t}}}(e),t)}));Ot=function(){if("object"==typeof globalThis)return globalThis;Object.defineProperty(Object.prototype,"_dd_temp_",{get:function(){return this},configurable:!0});var e=_dd_temp_;return delete Object.prototype._dd_temp_,"object"!=typeof e&&(e="object"==typeof self?self:"object"==typeof window?window:{}),e}(),Rt=Mt,Lt=Ot[Ct="DD_LOGS"],Ot[Ct]=Rt,Lt&&Lt.q&&Lt.q.forEach((function(e){return ne(e,"onReady callback threw an error:")()}))}();

@@ -1,2 +0,2 @@

import { BuildEnv } from '@datadog/browser-core';
import type { BuildEnv } from '@datadog/browser-core';
export declare const buildEnv: BuildEnv;

@@ -6,4 +6,4 @@ "use strict";

buildMode: 'release',
sdkVersion: '4.1.0',
sdkVersion: '4.2.0',
};
//# sourceMappingURL=buildEnv.js.map

@@ -1,5 +0,6 @@

import { Context, InitConfiguration } from '@datadog/browser-core';
import { LogsInitConfiguration } from '../domain/configuration';
import { HandlerType, Logger, StatusType } from '../domain/logger';
import { startLogs } from './startLogs';
import type { Context, InitConfiguration } from '@datadog/browser-core';
import type { LogsInitConfiguration } from '../domain/configuration';
import type { HandlerType, StatusType } from '../domain/logger';
import { Logger } from '../domain/logger';
import type { startLogs } from './startLogs';
export interface LoggerConfiguration {

@@ -6,0 +7,0 @@ level?: StatusType;

@@ -1,7 +0,8 @@

import { Context, InternalMonitoring, Observable, RawError } from '@datadog/browser-core';
import { Logger, LogsMessage } from '../domain/logger';
import { LogsSessionManager } from '../domain/logsSessionManager';
import { LogsConfiguration } from '../domain/configuration';
import type { Context, InternalMonitoring, RawError } from '@datadog/browser-core';
import { Observable } from '@datadog/browser-core';
import type { Logger, LogsMessage } from '../domain/logger';
import type { LogsSessionManager } from '../domain/logsSessionManager';
import type { LogsConfiguration } from '../domain/configuration';
export declare function startLogs(configuration: LogsConfiguration, errorLogger: Logger): (message: LogsMessage, currentContext: Context) => void;
export declare function doStartLogs(configuration: LogsConfiguration, errorObservable: Observable<RawError>, internalMonitoring: InternalMonitoring, sessionManager: LogsSessionManager, errorLogger: Logger): (message: LogsMessage, currentContext: Context) => void;
export declare function buildAssemble(sessionManager: LogsSessionManager, configuration: LogsConfiguration, reportError: (error: RawError) => void): (message: LogsMessage, currentContext: Context) => Context | undefined;

@@ -1,3 +0,3 @@

import { Configuration, InitConfiguration } from '@datadog/browser-core';
import { LogsEvent } from '../logsEvent.types';
import type { Configuration, InitConfiguration } from '@datadog/browser-core';
import type { LogsEvent } from '../logsEvent.types';
export interface LogsInitConfiguration extends InitConfiguration {

@@ -10,3 +10,8 @@ beforeSend?: ((event: LogsEvent) => void | boolean) | undefined;

forwardErrorsToLogs: boolean;
requestErrorResponseLengthLimit: number;
}
/**
* arbitrary value, byte precision not needed
*/
export declare const DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT: number;
export declare function validateAndBuildLogsConfiguration(initConfiguration: LogsInitConfiguration): LogsConfiguration | undefined;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAndBuildLogsConfiguration = void 0;
exports.validateAndBuildLogsConfiguration = exports.DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT = void 0;
var tslib_1 = require("tslib");
var browser_core_1 = require("@datadog/browser-core");
var buildEnv_1 = require("../boot/buildEnv");
/**
* arbitrary value, byte precision not needed
*/
exports.DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT = 32 * browser_core_1.ONE_KILO_BYTE;
function validateAndBuildLogsConfiguration(initConfiguration) {

@@ -12,5 +16,5 @@ var baseConfiguration = browser_core_1.validateAndBuildConfiguration(initConfiguration, buildEnv_1.buildEnv);

}
return tslib_1.__assign(tslib_1.__assign({}, baseConfiguration), { forwardErrorsToLogs: !!initConfiguration.forwardErrorsToLogs });
return tslib_1.__assign(tslib_1.__assign({}, baseConfiguration), { forwardErrorsToLogs: !!initConfiguration.forwardErrorsToLogs, requestErrorResponseLengthLimit: exports.DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT });
}
exports.validateAndBuildLogsConfiguration = validateAndBuildLogsConfiguration;
//# sourceMappingURL=configuration.js.map

@@ -1,2 +0,2 @@

import { Context, ContextValue, TimeStamp } from '@datadog/browser-core';
import type { Context, ContextValue, TimeStamp } from '@datadog/browser-core';
export declare const StatusType: {

@@ -3,0 +3,0 @@ readonly debug: "debug";

@@ -1,3 +0,3 @@

import { RelativeTime } from '@datadog/browser-core';
import { LogsConfiguration } from './configuration';
import type { RelativeTime } from '@datadog/browser-core';
import type { LogsConfiguration } from './configuration';
export declare const LOGS_SESSION_KEY = "logs";

@@ -4,0 +4,0 @@ export interface LogsSessionManager {

@@ -1,5 +0,8 @@

import { Observable, RawError } from '@datadog/browser-core';
import { LogsConfiguration } from './configuration';
import type { Observable, RawError } from '@datadog/browser-core';
import type { LogsConfiguration } from './configuration';
export declare function trackNetworkError(configuration: LogsConfiguration, errorObservable: Observable<RawError>): {
stop: () => void;
};
export declare function computeXhrResponseData(xhr: XMLHttpRequest, configuration: LogsConfiguration, callback: (responseData: unknown) => void): void;
export declare function computeFetchErrorText(error: Error, configuration: LogsConfiguration, callback: (errorText: string) => void): void;
export declare function computeFetchResponseText(response: Response, configuration: LogsConfiguration, callback: (responseText?: string) => void): void;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.trackNetworkError = void 0;
exports.computeFetchResponseText = exports.computeFetchErrorText = exports.computeXhrResponseData = exports.trackNetworkError = void 0;
var browser_core_1 = require("@datadog/browser-core");

@@ -18,2 +18,13 @@ function trackNetworkError(configuration, errorObservable) {

if (!configuration.isIntakeUrl(request.url) && (isRejected(request) || isServerError(request))) {
if ('xhr' in request) {
computeXhrResponseData(request.xhr, configuration, onResponseDataAvailable);
}
else if (request.response) {
computeFetchResponseText(request.response, configuration, onResponseDataAvailable);
}
else if (request.error) {
computeFetchErrorText(request.error, configuration, onResponseDataAvailable);
}
}
function onResponseDataAvailable(responseData) {
errorObservable.notify({

@@ -27,3 +38,3 @@ message: format(type) + " error " + request.method + " " + request.url,

source: browser_core_1.ErrorSource.NETWORK,
stack: truncateResponseText(request.responseText, configuration) || 'Failed to load',
stack: responseData || 'Failed to load',
startClocks: request.startClocks,

@@ -41,2 +52,69 @@ });

exports.trackNetworkError = trackNetworkError;
// TODO: ideally, computeXhrResponseData should always call the callback with a string instead of
// `unknown`. But to keep backward compatibility, in the case of XHR with a `responseType` different
// than "text", the response data should be whatever `xhr.response` is. This is a bit confusing as
// Logs event 'stack' is expected to be a string. This should be changed in a future major version
// as it could be a breaking change.
function computeXhrResponseData(xhr, configuration, callback) {
if (typeof xhr.response === 'string') {
callback(truncateResponseText(xhr.response, configuration));
}
else {
callback(xhr.response);
}
}
exports.computeXhrResponseData = computeXhrResponseData;
function computeFetchErrorText(error, configuration, callback) {
callback(truncateResponseText(browser_core_1.toStackTraceString(browser_core_1.computeStackTrace(error)), configuration));
}
exports.computeFetchErrorText = computeFetchErrorText;
function computeFetchResponseText(response, configuration, callback) {
if (!window.TextDecoder) {
// If the browser doesn't support TextDecoder, let's read the whole response then truncate it.
//
// This should only be the case on early versions of Edge (before they migrated to Chromium).
// Even if it could be possible to implement a workaround for the missing TextDecoder API (using
// a Blob and FileReader), we found another issue preventing us from reading only the first
// bytes from the response: contrary to other browsers, when reading from the cloned response,
// if the original response gets canceled, the cloned response is also canceled and we can't
// know about it. In the following illustration, the promise returned by `reader.read()` may
// never be fulfilled:
//
// fetch('/').then((response) => {
// const reader = response.clone().body.getReader()
// readMore()
// function readMore() {
// reader.read().then(
// (result) => {
// if (result.done) {
// console.log('done')
// } else {
// readMore()
// }
// },
// () => console.log('error')
// )
// }
// response.body.getReader().cancel()
// })
response
.clone()
.text()
.then(browser_core_1.monitor(function (text) { return callback(truncateResponseText(text, configuration)); }), browser_core_1.monitor(function (error) { return callback("Unable to retrieve response: " + error); }));
}
else if (!response.body) {
callback();
}
else {
truncateResponseStream(response.clone().body, configuration.requestErrorResponseLengthLimit, function (error, responseText) {
if (error) {
callback("Unable to retrieve response: " + error);
}
else {
callback(responseText);
}
});
}
}
exports.computeFetchResponseText = computeFetchResponseText;
function isRejected(request) {

@@ -49,3 +127,3 @@ return request.status === 0 && request.responseType !== 'opaque';

function truncateResponseText(responseText, configuration) {
if (responseText && responseText.length > configuration.requestErrorResponseLengthLimit) {
if (responseText.length > configuration.requestErrorResponseLengthLimit) {
return responseText.substring(0, configuration.requestErrorResponseLengthLimit) + "...";

@@ -61,2 +139,65 @@ }

}
function truncateResponseStream(stream, limit, callback) {
readLimitedAmountOfBytes(stream, limit, function (error, bytes, limitExceeded) {
if (error) {
callback(error);
}
else {
var responseText = new TextDecoder().decode(bytes);
if (limitExceeded) {
responseText += '...';
}
callback(undefined, responseText);
}
});
}
/**
* Read bytes from a ReadableStream until at least `limit` bytes have been read (or until the end of
* the stream). The callback is invoked with the at most `limit` bytes, and indicates that the limit
* has been exceeded if more bytes were available.
*/
function readLimitedAmountOfBytes(stream, limit, callback) {
var reader = stream.getReader();
var chunks = [];
var readBytesCount = 0;
readMore();
function readMore() {
reader.read().then(browser_core_1.monitor(function (result) {
if (result.done) {
onDone();
return;
}
chunks.push(result.value);
readBytesCount += result.value.length;
if (readBytesCount > limit) {
onDone();
}
else {
readMore();
}
}), browser_core_1.monitor(function (error) { return callback(error); }));
}
function onDone() {
reader.cancel().catch(
// we don't care if cancel fails, but we still need to catch the error to avoid reporting it
// as an unhandled rejection
browser_core_1.noop);
var completeBuffer;
if (chunks.length === 1) {
// optim: if the response is small enough to fit in a single buffer (provided by the browser), just
// use it directly.
completeBuffer = chunks[0];
}
else {
// else, we need to copy buffers into a larger buffer to concatenate them.
completeBuffer = new Uint8Array(readBytesCount);
var offset_1 = 0;
chunks.forEach(function (chunk) {
completeBuffer.set(chunk, offset_1);
offset_1 += chunk.length;
});
}
callback(undefined, completeBuffer.slice(0, limit), completeBuffer.length > limit);
}
}
//# sourceMappingURL=trackNetworkError.js.map

@@ -1,5 +0,5 @@

import { Context } from '@datadog/browser-core';
import { LogsConfiguration } from '../domain/configuration';
import type { Context } from '@datadog/browser-core';
import type { LogsConfiguration } from '../domain/configuration';
export declare function startLoggerBatch(configuration: LogsConfiguration): {
add(message: Context): void;
};

@@ -1,2 +0,2 @@

import { BuildEnv } from '@datadog/browser-core';
import type { BuildEnv } from '@datadog/browser-core';
export declare const buildEnv: BuildEnv;
export var buildEnv = {
buildMode: 'release',
sdkVersion: '4.1.0',
sdkVersion: '4.2.0',
};
//# sourceMappingURL=buildEnv.js.map

@@ -1,5 +0,6 @@

import { Context, InitConfiguration } from '@datadog/browser-core';
import { LogsInitConfiguration } from '../domain/configuration';
import { HandlerType, Logger, StatusType } from '../domain/logger';
import { startLogs } from './startLogs';
import type { Context, InitConfiguration } from '@datadog/browser-core';
import type { LogsInitConfiguration } from '../domain/configuration';
import type { HandlerType, StatusType } from '../domain/logger';
import { Logger } from '../domain/logger';
import type { startLogs } from './startLogs';
export interface LoggerConfiguration {

@@ -6,0 +7,0 @@ level?: StatusType;

@@ -1,7 +0,8 @@

import { Context, InternalMonitoring, Observable, RawError } from '@datadog/browser-core';
import { Logger, LogsMessage } from '../domain/logger';
import { LogsSessionManager } from '../domain/logsSessionManager';
import { LogsConfiguration } from '../domain/configuration';
import type { Context, InternalMonitoring, RawError } from '@datadog/browser-core';
import { Observable } from '@datadog/browser-core';
import type { Logger, LogsMessage } from '../domain/logger';
import type { LogsSessionManager } from '../domain/logsSessionManager';
import type { LogsConfiguration } from '../domain/configuration';
export declare function startLogs(configuration: LogsConfiguration, errorLogger: Logger): (message: LogsMessage, currentContext: Context) => void;
export declare function doStartLogs(configuration: LogsConfiguration, errorObservable: Observable<RawError>, internalMonitoring: InternalMonitoring, sessionManager: LogsSessionManager, errorLogger: Logger): (message: LogsMessage, currentContext: Context) => void;
export declare function buildAssemble(sessionManager: LogsSessionManager, configuration: LogsConfiguration, reportError: (error: RawError) => void): (message: LogsMessage, currentContext: Context) => Context | undefined;

@@ -1,3 +0,3 @@

import { Configuration, InitConfiguration } from '@datadog/browser-core';
import { LogsEvent } from '../logsEvent.types';
import type { Configuration, InitConfiguration } from '@datadog/browser-core';
import type { LogsEvent } from '../logsEvent.types';
export interface LogsInitConfiguration extends InitConfiguration {

@@ -10,3 +10,8 @@ beforeSend?: ((event: LogsEvent) => void | boolean) | undefined;

forwardErrorsToLogs: boolean;
requestErrorResponseLengthLimit: number;
}
/**
* arbitrary value, byte precision not needed
*/
export declare const DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT: number;
export declare function validateAndBuildLogsConfiguration(initConfiguration: LogsInitConfiguration): LogsConfiguration | undefined;
import { __assign } from "tslib";
import { validateAndBuildConfiguration } from '@datadog/browser-core';
import { ONE_KILO_BYTE, validateAndBuildConfiguration } from '@datadog/browser-core';
import { buildEnv } from '../boot/buildEnv';
/**
* arbitrary value, byte precision not needed
*/
export var DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT = 32 * ONE_KILO_BYTE;
export function validateAndBuildLogsConfiguration(initConfiguration) {

@@ -9,4 +13,4 @@ var baseConfiguration = validateAndBuildConfiguration(initConfiguration, buildEnv);

}
return __assign(__assign({}, baseConfiguration), { forwardErrorsToLogs: !!initConfiguration.forwardErrorsToLogs });
return __assign(__assign({}, baseConfiguration), { forwardErrorsToLogs: !!initConfiguration.forwardErrorsToLogs, requestErrorResponseLengthLimit: DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT });
}
//# sourceMappingURL=configuration.js.map

@@ -1,2 +0,2 @@

import { Context, ContextValue, TimeStamp } from '@datadog/browser-core';
import type { Context, ContextValue, TimeStamp } from '@datadog/browser-core';
export declare const StatusType: {

@@ -3,0 +3,0 @@ readonly debug: "debug";

var _a;
import { __assign, __decorate } from "tslib";
import { combine, createContextManager, ErrorSource, includes, monitored, display, } from '@datadog/browser-core';
import { combine, createContextManager, ErrorSource, includes, monitored, display } from '@datadog/browser-core';
export var StatusType = {

@@ -5,0 +5,0 @@ debug: 'debug',

@@ -1,3 +0,3 @@

import { RelativeTime } from '@datadog/browser-core';
import { LogsConfiguration } from './configuration';
import type { RelativeTime } from '@datadog/browser-core';
import type { LogsConfiguration } from './configuration';
export declare const LOGS_SESSION_KEY = "logs";

@@ -4,0 +4,0 @@ export interface LogsSessionManager {

@@ -1,5 +0,8 @@

import { Observable, RawError } from '@datadog/browser-core';
import { LogsConfiguration } from './configuration';
import type { Observable, RawError } from '@datadog/browser-core';
import type { LogsConfiguration } from './configuration';
export declare function trackNetworkError(configuration: LogsConfiguration, errorObservable: Observable<RawError>): {
stop: () => void;
};
export declare function computeXhrResponseData(xhr: XMLHttpRequest, configuration: LogsConfiguration, callback: (responseData: unknown) => void): void;
export declare function computeFetchErrorText(error: Error, configuration: LogsConfiguration, callback: (errorText: string) => void): void;
export declare function computeFetchResponseText(response: Response, configuration: LogsConfiguration, callback: (responseText?: string) => void): void;

@@ -1,2 +0,2 @@

import { ErrorSource, initXhrObservable, RequestType, initFetchObservable, } from '@datadog/browser-core';
import { ErrorSource, initXhrObservable, RequestType, initFetchObservable, computeStackTrace, toStackTraceString, monitor, noop, } from '@datadog/browser-core';
export function trackNetworkError(configuration, errorObservable) {

@@ -15,2 +15,13 @@ var xhrSubscription = initXhrObservable().subscribe(function (context) {

if (!configuration.isIntakeUrl(request.url) && (isRejected(request) || isServerError(request))) {
if ('xhr' in request) {
computeXhrResponseData(request.xhr, configuration, onResponseDataAvailable);
}
else if (request.response) {
computeFetchResponseText(request.response, configuration, onResponseDataAvailable);
}
else if (request.error) {
computeFetchErrorText(request.error, configuration, onResponseDataAvailable);
}
}
function onResponseDataAvailable(responseData) {
errorObservable.notify({

@@ -24,3 +35,3 @@ message: format(type) + " error " + request.method + " " + request.url,

source: ErrorSource.NETWORK,
stack: truncateResponseText(request.responseText, configuration) || 'Failed to load',
stack: responseData || 'Failed to load',
startClocks: request.startClocks,

@@ -37,2 +48,66 @@ });

}
// TODO: ideally, computeXhrResponseData should always call the callback with a string instead of
// `unknown`. But to keep backward compatibility, in the case of XHR with a `responseType` different
// than "text", the response data should be whatever `xhr.response` is. This is a bit confusing as
// Logs event 'stack' is expected to be a string. This should be changed in a future major version
// as it could be a breaking change.
export function computeXhrResponseData(xhr, configuration, callback) {
if (typeof xhr.response === 'string') {
callback(truncateResponseText(xhr.response, configuration));
}
else {
callback(xhr.response);
}
}
export function computeFetchErrorText(error, configuration, callback) {
callback(truncateResponseText(toStackTraceString(computeStackTrace(error)), configuration));
}
export function computeFetchResponseText(response, configuration, callback) {
if (!window.TextDecoder) {
// If the browser doesn't support TextDecoder, let's read the whole response then truncate it.
//
// This should only be the case on early versions of Edge (before they migrated to Chromium).
// Even if it could be possible to implement a workaround for the missing TextDecoder API (using
// a Blob and FileReader), we found another issue preventing us from reading only the first
// bytes from the response: contrary to other browsers, when reading from the cloned response,
// if the original response gets canceled, the cloned response is also canceled and we can't
// know about it. In the following illustration, the promise returned by `reader.read()` may
// never be fulfilled:
//
// fetch('/').then((response) => {
// const reader = response.clone().body.getReader()
// readMore()
// function readMore() {
// reader.read().then(
// (result) => {
// if (result.done) {
// console.log('done')
// } else {
// readMore()
// }
// },
// () => console.log('error')
// )
// }
// response.body.getReader().cancel()
// })
response
.clone()
.text()
.then(monitor(function (text) { return callback(truncateResponseText(text, configuration)); }), monitor(function (error) { return callback("Unable to retrieve response: " + error); }));
}
else if (!response.body) {
callback();
}
else {
truncateResponseStream(response.clone().body, configuration.requestErrorResponseLengthLimit, function (error, responseText) {
if (error) {
callback("Unable to retrieve response: " + error);
}
else {
callback(responseText);
}
});
}
}
function isRejected(request) {

@@ -45,3 +120,3 @@ return request.status === 0 && request.responseType !== 'opaque';

function truncateResponseText(responseText, configuration) {
if (responseText && responseText.length > configuration.requestErrorResponseLengthLimit) {
if (responseText.length > configuration.requestErrorResponseLengthLimit) {
return responseText.substring(0, configuration.requestErrorResponseLengthLimit) + "...";

@@ -57,2 +132,65 @@ }

}
function truncateResponseStream(stream, limit, callback) {
readLimitedAmountOfBytes(stream, limit, function (error, bytes, limitExceeded) {
if (error) {
callback(error);
}
else {
var responseText = new TextDecoder().decode(bytes);
if (limitExceeded) {
responseText += '...';
}
callback(undefined, responseText);
}
});
}
/**
* Read bytes from a ReadableStream until at least `limit` bytes have been read (or until the end of
* the stream). The callback is invoked with the at most `limit` bytes, and indicates that the limit
* has been exceeded if more bytes were available.
*/
function readLimitedAmountOfBytes(stream, limit, callback) {
var reader = stream.getReader();
var chunks = [];
var readBytesCount = 0;
readMore();
function readMore() {
reader.read().then(monitor(function (result) {
if (result.done) {
onDone();
return;
}
chunks.push(result.value);
readBytesCount += result.value.length;
if (readBytesCount > limit) {
onDone();
}
else {
readMore();
}
}), monitor(function (error) { return callback(error); }));
}
function onDone() {
reader.cancel().catch(
// we don't care if cancel fails, but we still need to catch the error to avoid reporting it
// as an unhandled rejection
noop);
var completeBuffer;
if (chunks.length === 1) {
// optim: if the response is small enough to fit in a single buffer (provided by the browser), just
// use it directly.
completeBuffer = chunks[0];
}
else {
// else, we need to copy buffers into a larger buffer to concatenate them.
completeBuffer = new Uint8Array(readBytesCount);
var offset_1 = 0;
chunks.forEach(function (chunk) {
completeBuffer.set(chunk, offset_1);
offset_1 += chunk.length;
});
}
callback(undefined, completeBuffer.slice(0, limit), completeBuffer.length > limit);
}
}
//# sourceMappingURL=trackNetworkError.js.map

@@ -1,5 +0,5 @@

import { Context } from '@datadog/browser-core';
import { LogsConfiguration } from '../domain/configuration';
import type { Context } from '@datadog/browser-core';
import type { LogsConfiguration } from '../domain/configuration';
export declare function startLoggerBatch(configuration: LogsConfiguration): {
add(message: Context): void;
};
{
"name": "@datadog/browser-logs",
"version": "4.1.0",
"version": "4.2.0",
"license": "Apache-2.0",

@@ -16,3 +16,3 @@ "main": "cjs/entries/main.js",

"dependencies": {
"@datadog/browser-core": "4.1.0",
"@datadog/browser-core": "4.2.0",
"tslib": "^1.10.0"

@@ -29,3 +29,3 @@ },

},
"gitHead": "27c7b4c01354dd77116f5bfb6eef370d4e2585bd"
"gitHead": "caceec86d8039d63ae5c176ba82e35e466e6cec7"
}

@@ -1,2 +0,2 @@

import { BuildEnv, BuildMode } from '@datadog/browser-core'
import type { BuildEnv, BuildMode } from '@datadog/browser-core'

@@ -3,0 +3,0 @@ export const buildEnv: BuildEnv = {

@@ -0,3 +1,3 @@

import type { Context } from '@datadog/browser-core'
import {
Context,
monitor,

@@ -9,7 +9,10 @@ ONE_SECOND,

} from '@datadog/browser-core'
import { Clock, deleteEventBridgeStub, initEventBridgeStub, mockClock } from '../../../core/test/specHelper'
import { HybridInitConfiguration, LogsInitConfiguration } from '../domain/configuration'
import type { Clock } from '../../../core/test/specHelper'
import { deleteEventBridgeStub, initEventBridgeStub, mockClock } from '../../../core/test/specHelper'
import type { HybridInitConfiguration, LogsInitConfiguration } from '../domain/configuration'
import { HandlerType, LogsMessage, StatusType } from '../domain/logger'
import { LogsPublicApi, makeLogsPublicApi, StartLogs } from './logsPublicApi'
import type { LogsMessage } from '../domain/logger'
import { HandlerType, StatusType } from '../domain/logger'
import type { LogsPublicApi, StartLogs } from './logsPublicApi'
import { makeLogsPublicApi } from './logsPublicApi'

@@ -16,0 +19,0 @@ const DEFAULT_INIT_CONFIGURATION = { clientToken: 'xxx' }

@@ -0,5 +1,5 @@

import type { Context, InitConfiguration } from '@datadog/browser-core'
import {
BoundedBuffer,
combine,
Context,
createContextManager,

@@ -10,8 +10,9 @@ makePublicApi,

deepClone,
InitConfiguration,
canUseEventBridge,
} from '@datadog/browser-core'
import { LogsInitConfiguration, validateAndBuildLogsConfiguration } from '../domain/configuration'
import { HandlerType, Logger, LogsMessage, StatusType } from '../domain/logger'
import { startLogs } from './startLogs'
import type { LogsInitConfiguration } from '../domain/configuration'
import { validateAndBuildLogsConfiguration } from '../domain/configuration'
import type { HandlerType, LogsMessage, StatusType } from '../domain/logger'
import { Logger } from '../domain/logger'
import type { startLogs } from './startLogs'

@@ -18,0 +19,0 @@ export interface LoggerConfiguration {

@@ -0,3 +1,3 @@

import type { Context, RawError, RelativeTime, TimeStamp } from '@datadog/browser-core'
import {
Context,
ErrorSource,

@@ -7,6 +7,3 @@ noop,

ONE_MINUTE,
RawError,
RelativeTime,
resetExperimentalFeatures,
TimeStamp,
updateExperimentalFeatures,

@@ -16,4 +13,4 @@ getTimeStamp,

import sinon from 'sinon'
import type { Clock } from '../../../core/test/specHelper'
import {
Clock,
deleteEventBridgeStub,

@@ -24,7 +21,9 @@ initEventBridgeStub,

} from '../../../core/test/specHelper'
import { LogsConfiguration, validateAndBuildLogsConfiguration } from '../domain/configuration'
import type { LogsConfiguration } from '../domain/configuration'
import { validateAndBuildLogsConfiguration } from '../domain/configuration'
import { Logger, LogsMessage, StatusType } from '../domain/logger'
import { LogsSessionManager } from '../domain/logsSessionManager'
import { LogsEvent } from '../logsEvent.types'
import type { LogsMessage } from '../domain/logger'
import { Logger, StatusType } from '../domain/logger'
import type { LogsSessionManager } from '../domain/logsSessionManager'
import type { LogsEvent } from '../logsEvent.types'
import { buildAssemble, doStartLogs, startLogs as originalStartLogs } from './startLogs'

@@ -31,0 +30,0 @@

@@ -0,10 +1,7 @@

import type { Context, InternalMonitoring, RawError, RelativeTime } from '@datadog/browser-core'
import {
areCookiesAuthorized,
combine,
Context,
createEventRateLimiter,
InternalMonitoring,
Observable,
RawError,
RelativeTime,
trackRuntimeError,

@@ -18,6 +15,8 @@ trackConsoleError,

import { trackNetworkError } from '../domain/trackNetworkError'
import { Logger, LogsMessage, StatusType } from '../domain/logger'
import { LogsSessionManager, startLogsSessionManager, startLogsSessionManagerStub } from '../domain/logsSessionManager'
import type { Logger, LogsMessage } from '../domain/logger'
import { StatusType } from '../domain/logger'
import type { LogsSessionManager } from '../domain/logsSessionManager'
import { startLogsSessionManager, startLogsSessionManagerStub } from '../domain/logsSessionManager'
import { startLoggerBatch } from '../transport/startLoggerBatch'
import { LogsConfiguration } from '../domain/configuration'
import type { LogsConfiguration } from '../domain/configuration'

@@ -24,0 +23,0 @@ export function startLogs(configuration: LogsConfiguration, errorLogger: Logger) {

@@ -1,4 +0,5 @@

import { Configuration, InitConfiguration, validateAndBuildConfiguration } from '@datadog/browser-core'
import type { Configuration, InitConfiguration } from '@datadog/browser-core'
import { ONE_KILO_BYTE, validateAndBuildConfiguration } from '@datadog/browser-core'
import { buildEnv } from '../boot/buildEnv'
import { LogsEvent } from '../logsEvent.types'
import type { LogsEvent } from '../logsEvent.types'

@@ -14,4 +15,10 @@ export interface LogsInitConfiguration extends InitConfiguration {

forwardErrorsToLogs: boolean
requestErrorResponseLengthLimit: number
}
/**
* arbitrary value, byte precision not needed
*/
export const DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT = 32 * ONE_KILO_BYTE
export function validateAndBuildLogsConfiguration(

@@ -29,3 +36,5 @@ initConfiguration: LogsInitConfiguration

forwardErrorsToLogs: !!initConfiguration.forwardErrorsToLogs,
requestErrorResponseLengthLimit: DEFAULT_REQUEST_ERROR_RESPONSE_LENGTH_LIMIT,
}
}
import { display } from '@datadog/browser-core'
import { HandlerType, Logger, LogsMessage, STATUSES, StatusType } from './logger'
import type { LogsMessage } from './logger'
import { HandlerType, Logger, STATUSES, StatusType } from './logger'

@@ -4,0 +5,0 @@ describe('Logger', () => {

@@ -1,12 +0,3 @@

import {
combine,
Context,
ContextValue,
createContextManager,
ErrorSource,
includes,
monitored,
display,
TimeStamp,
} from '@datadog/browser-core'
import type { Context, ContextValue, TimeStamp } from '@datadog/browser-core'
import { combine, createContextManager, ErrorSource, includes, monitored, display } from '@datadog/browser-core'

@@ -13,0 +4,0 @@ export const StatusType = {

@@ -0,1 +1,2 @@

import type { RelativeTime } from '@datadog/browser-core'
import {

@@ -8,7 +9,7 @@ COOKIE_ACCESS_DELAY,

ONE_SECOND,
RelativeTime,
} from '@datadog/browser-core'
import { Clock, mockClock } from '../../../core/test/specHelper'
import type { Clock } from '../../../core/test/specHelper'
import { mockClock } from '../../../core/test/specHelper'
import { LogsConfiguration } from './configuration'
import type { LogsConfiguration } from './configuration'
import {

@@ -15,0 +16,0 @@ LOGS_SESSION_KEY,

@@ -1,3 +0,4 @@

import { performDraw, startSessionManager, RelativeTime } from '@datadog/browser-core'
import { LogsConfiguration } from './configuration'
import type { RelativeTime } from '@datadog/browser-core'
import { performDraw, startSessionManager } from '@datadog/browser-core'
import type { LogsConfiguration } from './configuration'

@@ -4,0 +5,0 @@ export const LOGS_SESSION_KEY = 'logs'

@@ -1,7 +0,19 @@

import { isIE, Observable, RawError } from '@datadog/browser-core'
import { FetchStub, FetchStubManager, SPEC_ENDPOINTS, stubFetch } from '../../../core/test/specHelper'
import { LogsConfiguration } from './configuration'
import type { RawError } from '@datadog/browser-core'
import { isIE, Observable } from '@datadog/browser-core'
import type { FetchStub, FetchStubManager } from '../../../core/test/specHelper'
import { SPEC_ENDPOINTS, ResponseStub, stubFetch } from '../../../core/test/specHelper'
import type { LogsConfiguration } from './configuration'
import { trackNetworkError } from './trackNetworkError'
import {
computeFetchErrorText,
computeFetchResponseText,
computeXhrResponseData,
trackNetworkError,
} from './trackNetworkError'
const CONFIGURATION = {
requestErrorResponseLengthLimit: 64,
...SPEC_ENDPOINTS,
} as LogsConfiguration
describe('network error tracker', () => {

@@ -12,3 +24,2 @@ let errorObservableSpy: jasmine.Spy

let stopNetworkErrorTracking: () => void
let configuration: LogsConfiguration
let errorObservable: Observable<RawError>

@@ -31,9 +42,5 @@ const FAKE_URL = 'http://fake.com/'

errorObservableSpy = spyOn(errorObservable, 'notify')
configuration = {
requestErrorResponseLengthLimit: 32,
...SPEC_ENDPOINTS,
} as LogsConfiguration
fetchStubManager = stubFetch()
;({ stop: stopNetworkErrorTracking } = trackNetworkError(configuration, errorObservable))
;({ stop: stopNetworkErrorTracking } = trackNetworkError(CONFIGURATION, errorObservable))
fetchStub = window.fetch as FetchStub

@@ -111,4 +118,4 @@ })

it('should add a default error response text', (done) => {
fetchStub(FAKE_URL).resolveWith({ ...DEFAULT_REQUEST, responseText: undefined })
it('uses a fallback when the response text is empty', (done) => {
fetchStub(FAKE_URL).resolveWith({ ...DEFAULT_REQUEST, responseText: '' })

@@ -122,15 +129,145 @@ fetchStubManager.whenAllComplete(() => {

})
})
it('should truncate error response text', (done) => {
fetchStub(FAKE_URL).resolveWith({
...DEFAULT_REQUEST,
responseText: 'Lorem ipsum dolor sit amet orci aliquam.',
describe('computeXhrResponseData', () => {
it('computes response text from XHR', (done) => {
const xhr = { response: 'foo' } as XMLHttpRequest
computeXhrResponseData(xhr, CONFIGURATION, (responseData) => {
expect(responseData).toBe('foo')
done()
})
})
fetchStubManager.whenAllComplete(() => {
const stack = (errorObservableSpy.calls.mostRecent().args[0] as RawError).stack
expect(stack).toEqual('Lorem ipsum dolor sit amet orci ...')
it('return the response value directly if it is not a string', (done) => {
const xhr = { response: { foo: 'bar' } } as XMLHttpRequest
computeXhrResponseData(xhr, CONFIGURATION, (responseData) => {
expect(responseData).toEqual({ foo: 'bar' })
done()
})
})
it('truncates xhr response text', (done) => {
const xhr = { response: 'Lorem ipsum dolor sit amet orci aliquam.' } as XMLHttpRequest
computeXhrResponseData(xhr, { ...CONFIGURATION, requestErrorResponseLengthLimit: 32 }, (responseData) => {
expect(responseData).toBe('Lorem ipsum dolor sit amet orci ...')
done()
})
})
})
describe('computeFetchResponseText', () => {
let onunhandledrejectionSpy: jasmine.Spy
beforeEach(() => {
if (isIE()) {
pending('IE does not support the fetch API')
}
onunhandledrejectionSpy = jasmine.createSpy()
window.onunhandledrejection = onunhandledrejectionSpy
})
afterEach(() => {
window.onunhandledrejection = null
})
it('computes response text from Response objects', (done) => {
computeFetchResponseText(new ResponseStub({ responseText: 'foo' }), CONFIGURATION, (responseText) => {
expect(responseText).toBe('foo')
done()
})
})
// https://fetch.spec.whatwg.org/#concept-body-consume-body
it('computes response text from Response objects failing to retrieve text', (done) => {
computeFetchResponseText(
new ResponseStub({ responseTextError: new Error('locked') }),
CONFIGURATION,
(responseText) => {
expect(responseText).toBe('Unable to retrieve response: Error: locked')
done()
}
)
})
it('does not consume the response body', (done) => {
const response = new ResponseStub({ responseText: 'foo' })
computeFetchResponseText(response, CONFIGURATION, () => {
expect(response.bodyUsed).toBe(false)
done()
})
})
it('reads a limited amount of bytes from the response', (done) => {
// Creates a response that stream "f" indefinitely, one byte at a time
const cancelSpy = jasmine.createSpy()
const pullSpy = jasmine.createSpy().and.callFake((controller: ReadableStreamDefaultController<Uint8Array>) => {
controller.enqueue(new TextEncoder().encode('f'))
})
const response = new ResponseStub({
body: new ReadableStream({
pull: pullSpy,
cancel: cancelSpy,
}),
})
computeFetchResponseText(response, CONFIGURATION, () => {
expect(pullSpy).toHaveBeenCalledTimes(
// readLimitedAmountOfBytes may read one more byte than necessary to make sure it exceeds the limit
CONFIGURATION.requestErrorResponseLengthLimit + 1
)
expect(cancelSpy).toHaveBeenCalledTimes(1)
done()
})
})
it('truncates the response if its size is greater than the limit', (done) => {
const text = 'foobar'
computeFetchResponseText(
new ResponseStub({ responseText: text }),
{ ...CONFIGURATION, requestErrorResponseLengthLimit: text.length - 1 },
(responseData) => {
expect(responseData).toBe('fooba...')
done()
}
)
})
it('does not truncate the response if its size is equal to the limit', (done) => {
const text = 'foo'
computeFetchResponseText(
new ResponseStub({ responseText: text }),
{ ...CONFIGURATION, requestErrorResponseLengthLimit: text.length },
(responseData) => {
expect(responseData).toBe(text)
done()
}
)
})
it('does not yield an unhandled rejection error if the cancel promise is rejected', (done) => {
// Creates a response that stream "f" indefinitely and fails to be canceled
const response = new ResponseStub({
body: new ReadableStream({
pull: (controller) => controller.enqueue(new TextEncoder().encode('f')),
cancel: () => Promise.reject(new Error('foo')),
}),
})
computeFetchResponseText(response, CONFIGURATION, () => {
setTimeout(() => {
expect(onunhandledrejectionSpy).not.toHaveBeenCalled()
done()
})
})
})
})
describe('computeFetchErrorText', () => {
it('computes response text from requests ending as an error', (done) => {
computeFetchErrorText(new Error('fetch error'), CONFIGURATION, (errorText) => {
expect(errorText).toContain('Error: fetch error')
done()
})
})
})

@@ -0,12 +1,13 @@

import type { FetchCompleteContext, Observable, RawError, XhrCompleteContext } from '@datadog/browser-core'
import {
ErrorSource,
FetchCompleteContext,
initXhrObservable,
Observable,
RawError,
RequestType,
initFetchObservable,
XhrCompleteContext,
computeStackTrace,
toStackTraceString,
monitor,
noop,
} from '@datadog/browser-core'
import { LogsConfiguration } from './configuration'
import type { LogsConfiguration } from './configuration'

@@ -27,2 +28,12 @@ export function trackNetworkError(configuration: LogsConfiguration, errorObservable: Observable<RawError>) {

if (!configuration.isIntakeUrl(request.url) && (isRejected(request) || isServerError(request))) {
if ('xhr' in request) {
computeXhrResponseData(request.xhr, configuration, onResponseDataAvailable)
} else if (request.response) {
computeFetchResponseText(request.response, configuration, onResponseDataAvailable)
} else if (request.error) {
computeFetchErrorText(request.error, configuration, onResponseDataAvailable)
}
}
function onResponseDataAvailable(responseData: unknown) {
errorObservable.notify({

@@ -36,3 +47,3 @@ message: `${format(type)} error ${request.method} ${request.url}`,

source: ErrorSource.NETWORK,
stack: truncateResponseText(request.responseText, configuration) || 'Failed to load',
stack: (responseData as string) || 'Failed to load',
startClocks: request.startClocks,

@@ -51,2 +62,84 @@ })

// TODO: ideally, computeXhrResponseData should always call the callback with a string instead of
// `unknown`. But to keep backward compatibility, in the case of XHR with a `responseType` different
// than "text", the response data should be whatever `xhr.response` is. This is a bit confusing as
// Logs event 'stack' is expected to be a string. This should be changed in a future major version
// as it could be a breaking change.
export function computeXhrResponseData(
xhr: XMLHttpRequest,
configuration: LogsConfiguration,
callback: (responseData: unknown) => void
) {
if (typeof xhr.response === 'string') {
callback(truncateResponseText(xhr.response, configuration))
} else {
callback(xhr.response)
}
}
export function computeFetchErrorText(
error: Error,
configuration: LogsConfiguration,
callback: (errorText: string) => void
) {
callback(truncateResponseText(toStackTraceString(computeStackTrace(error)), configuration))
}
export function computeFetchResponseText(
response: Response,
configuration: LogsConfiguration,
callback: (responseText?: string) => void
) {
if (!window.TextDecoder) {
// If the browser doesn't support TextDecoder, let's read the whole response then truncate it.
//
// This should only be the case on early versions of Edge (before they migrated to Chromium).
// Even if it could be possible to implement a workaround for the missing TextDecoder API (using
// a Blob and FileReader), we found another issue preventing us from reading only the first
// bytes from the response: contrary to other browsers, when reading from the cloned response,
// if the original response gets canceled, the cloned response is also canceled and we can't
// know about it. In the following illustration, the promise returned by `reader.read()` may
// never be fulfilled:
//
// fetch('/').then((response) => {
// const reader = response.clone().body.getReader()
// readMore()
// function readMore() {
// reader.read().then(
// (result) => {
// if (result.done) {
// console.log('done')
// } else {
// readMore()
// }
// },
// () => console.log('error')
// )
// }
// response.body.getReader().cancel()
// })
response
.clone()
.text()
.then(
monitor((text) => callback(truncateResponseText(text, configuration))),
monitor((error) => callback(`Unable to retrieve response: ${error as string}`))
)
} else if (!response.body) {
callback()
} else {
truncateResponseStream(
response.clone().body!,
configuration.requestErrorResponseLengthLimit,
(error, responseText) => {
if (error) {
callback(`Unable to retrieve response: ${(error as unknown) as string}`)
} else {
callback(responseText)
}
}
)
}
}
function isRejected(request: { status: number; responseType?: string }) {

@@ -60,4 +153,4 @@ return request.status === 0 && request.responseType !== 'opaque'

function truncateResponseText(responseText: string | undefined, configuration: LogsConfiguration) {
if (responseText && responseText.length > configuration.requestErrorResponseLengthLimit) {
function truncateResponseText(responseText: string, configuration: LogsConfiguration) {
if (responseText.length > configuration.requestErrorResponseLengthLimit) {
return `${responseText.substring(0, configuration.requestErrorResponseLengthLimit)}...`

@@ -74,1 +167,82 @@ }

}
function truncateResponseStream(
stream: ReadableStream<Uint8Array>,
limit: number,
callback: (error?: Error, responseText?: string) => void
) {
readLimitedAmountOfBytes(stream, limit, (error, bytes, limitExceeded) => {
if (error) {
callback(error)
} else {
let responseText = new TextDecoder().decode(bytes)
if (limitExceeded) {
responseText += '...'
}
callback(undefined, responseText)
}
})
}
/**
* Read bytes from a ReadableStream until at least `limit` bytes have been read (or until the end of
* the stream). The callback is invoked with the at most `limit` bytes, and indicates that the limit
* has been exceeded if more bytes were available.
*/
function readLimitedAmountOfBytes(
stream: ReadableStream<Uint8Array>,
limit: number,
callback: (error?: Error, bytes?: Uint8Array, limitExceeded?: boolean) => void
) {
const reader = stream.getReader()
const chunks: Uint8Array[] = []
let readBytesCount = 0
readMore()
function readMore() {
reader.read().then(
monitor((result: ReadableStreamReadResult<Uint8Array>) => {
if (result.done) {
onDone()
return
}
chunks.push(result.value)
readBytesCount += result.value.length
if (readBytesCount > limit) {
onDone()
} else {
readMore()
}
}),
monitor((error) => callback(error))
)
}
function onDone() {
reader.cancel().catch(
// we don't care if cancel fails, but we still need to catch the error to avoid reporting it
// as an unhandled rejection
noop
)
let completeBuffer: Uint8Array
if (chunks.length === 1) {
// optim: if the response is small enough to fit in a single buffer (provided by the browser), just
// use it directly.
completeBuffer = chunks[0]
} else {
// else, we need to copy buffers into a larger buffer to concatenate them.
completeBuffer = new Uint8Array(readBytesCount)
let offset = 0
chunks.forEach((chunk) => {
completeBuffer.set(chunk, offset)
offset += chunk.length
})
}
callback(undefined, completeBuffer.slice(0, limit), completeBuffer.length > limit)
}
}
import { defineGlobal, getGlobalObject } from '@datadog/browser-core'
import { LogsPublicApi, makeLogsPublicApi } from '../boot/logsPublicApi'
import type { LogsPublicApi } from '../boot/logsPublicApi'
import { makeLogsPublicApi } from '../boot/logsPublicApi'
import { startLogs } from '../boot/startLogs'

@@ -4,0 +5,0 @@

@@ -1,3 +0,4 @@

import { Batch, Context, HttpRequest, EndpointBuilder } from '@datadog/browser-core'
import { LogsConfiguration } from '../domain/configuration'
import type { Context, EndpointBuilder } from '@datadog/browser-core'
import { Batch, HttpRequest } from '@datadog/browser-core'
import type { LogsConfiguration } from '../domain/configuration'

@@ -4,0 +5,0 @@ export function startLoggerBatch(configuration: LogsConfiguration) {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc