!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).YouzanRontgen={})}(this,(function(t){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n={},r={__esModule:!0,LEGACY_HTTP_TRACE_HEADER:"x-cat-trace",X_YZ_TEACE_HEADER:"x-yz-trace",X_SERVICE_CHIAN_HEADER:"x-service-chain",X_YZ_ACTION_ID_HEADER:"x-yz-action-id",LEGACY_DUBBO_TRACE_ATTACHMENT:"CAT_TRACE",LEGACY_NAQ_TRACE_EXTENSION_KEY:"_catContext",DUBBO_TRACE_ATTACHMENT:"rontgen",NAQ_TRACE__EXTENSION_KEY:"_rontgen",HTTP_TRACE_HEADER:"x-rontgen",SAMPLE_MARK:"sample=true",DUBBO_PROTOCOL_NAME:"dubbo"},o={__esModule:!0},i=function(){function t(t){var e=t.traceId,n=t.parentId,r=t.spanId,o=t.appName;this.durationNano=0,this.finished=!1,this.spanId=r,this.traceId=e||"null",this.parentId=n,this.appName=o,this.logs=[]}return t.prototype.isFinished=function(){return this.finished},t.prototype.markError=function(t){try{this.finish(),this.tags[0][1]="true",t&&"object"==typeof t?(void 0!==t.code&&this.addTag("error.code",String(t.code)),this.addLog("error.message",String(t.message||t.msg||JSON.stringify(t))),t.stack&&this.addLog("error.stack",t.stack)):this.addLog("error.message",JSON.stringify(t))}catch(t){console.warn("[rontgen] markError fail",t)}},t.prototype.hasError=function(){return"true"===this.tags[0][1]},t.prototype.addTag=function(t,e){this.tags.push([t,e])},t.prototype.getTag=function(t){var e;return(null===(e=this.tags.find((function(e){return e[0]===t})))||void 0===e?void 0:e[1])||null},t.prototype.setTagVal=function(t,e){var n=this.tags.find((function(e){return e[0]===t}));n?n[1]=e:this.addTag(t,e)},t.prototype.addLog=function(t,e){var n;this.logs.push(((n={})[t]=e,n))},t.prototype.setOperation=function(t,e){this.operationType=t,this.operationName=e},t.prototype.toString=function(){return'{"app":"'+this.appName+'","traceId":"'+this.traceId+'","parentId":'+(null===this.parentId?"null":'"'+this.parentId+'"')+',"spanId":"'+this.spanId+'","opType":"'+this.operationType+'","opName":"'+this.operationName+'","time":'+this.startTimeNano+',"duration":'+this.durationNano+',"tags":'+JSON.stringify(this.tags)+',"logs":'+JSON.stringify(this.logs)+"}"},t}();o.Span=i;var a={__esModule:!0},s=function(){function t(){}return t.encode=function(t){var e=t.getTag("segment_id");return'{"_catRootMessageId": "'+t.traceId+'","_catParentMessageId": "'+e+'","_catChildMessageId":"'+t.spanId+'"}'},t.decode=function(t){return t?JSON.parse(t):null},t}();a.LegacyHeaderCodec=s;var u={__esModule:!0},c="traceId=",l="sample=",p=function(){function t(){}return t.decode=function(t){if(!t)return null;var e,n=t.split(";"),r=!1;try{for(var o=0;o0&&(this.logger.info(this.queue),this.queue.length=0)},t.prototype.intervalFlush=function(){var t=this;this.timer=setTimeout((function(){t.flush(),t.intervalFlush()}),this.interval)},t.prototype.clearInterval=function(){clearTimeout(this.timer)},t}();g.ReportQueue=m;var y={__esModule:!0},v=function(t){this.span=t};y.AbstractTagCollector=v;var I={__esModule:!0},S=function(t){this.appName=t};I.TraceIdGenerator=S;var R={__esModule:!0},C=function(t){this.sampleConfig=t};R.AbstractSampler=C;var N=e&&e.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e};n.__esModule=!0;var O=N(r),A=n.constants=O,b=o,x=n.Span=b.Span,w=a,M=n.LegacyHeaderCodec=w.LegacyHeaderCodec,L=u,H=n.CookieHeaderCodec=L.CookieHeaderCodec,D=d,P=n.TagEnum=D.TagEnum,B=n.LogEnum=D.LogEnum,Q=n.OperationTypeEnum=D.OperationTypeEnum,q=h,U=n.BaseTraceContext=q.BaseTraceContext,k=n.isTraceContext=q.isTraceContext,z=g,F=n.ReportQueue=z.ReportQueue,j=y,V=n.AbstractTagCollector=j.AbstractTagCollector,Y=I,G=n.TraceIdGenerator=Y.TraceIdGenerator,X=R,W=n.AbstractSampler=X.AbstractSampler,Z=T,J=n.getRandomInt=Z.getRandomInt,K=n.calSamplingValue=Z.calSamplingValue,$=n.generateHexIp=Z.generateHexIp,tt=n.randomString=Z.randomString,et=n.parseUrl=Z.parseUrl,nt=function(t,e){return nt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},nt(t,e)};function rt(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}nt(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var ot=function(){return ot=Object.assign||function(t){for(var e,n=1,r=arguments.length;n0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]>=0,n=String(void 0!==n?n:""),t.length>e)return String(t);if((e-=t.length)>n.length)for(var r=n,o=e/n.length,i=0;ithis.maxQueueSize&&this.queue.flush()},e.prototype.forceFlush=function(){var t=this.getFinishSpan().filter((function(t){return"null"!==t.traceId}));this.queue.add(t),this.queue.flush()},e.prototype.shouldSample=function(){return!1},e.prototype.removeSpan=function(t){this.spanQueue=this.spanQueue.filter((function(e){return!e.equal(t)}))},e}(U),It=function(){function t(t,e){void 0===t&&(t={}),this.containerElm=null,this.pageWidth=0,this.dpr=window.devicePixelRatio,this.traceQueue=[],this.actionId="";var n=t.style,r=void 0===n?{mobile:{},pc:{}}:n;this.request=e,this.options=ot(ot({maxLength:10,containerElmId:"yzTraceWaterMarkContainer",autoRemove:0},t),{style:ot(ot({opacity:.01,letterSpacing:4,colors:["rgb(142,142,142)","rgb(255,255,0)","rgb(255,0,255,.7)","rgb(0,255,255)"]},r),{mobile:ot({marginBottom:10,marginRight:10,fontSize:20},r.mobile),pc:ot({marginBottom:10,marginRight:10,fontSize:30},r.pc)})})}return t.prototype.clear=function(){this.containerElm&&document.body.removeChild(this.containerElm),this.containerElm=null,this.context=null,this.traceQueue=[]},t.prototype.add=function(t){return it(this,void 0,void 0,(function(){var e,n;return at(this,(function(r){switch(r.label){case 0:return t.traceId?this.actionId?[3,2]:(e=this,[4,this.toShortTraceId(Tt())]):[2];case 1:e.actionId=r.sent(),r.label=2;case 2:return[4,this.toShortTraceId(t.traceId)];case 3:return(n=r.sent())&&(this.traceQueue.push({traceId:n}),this.traceQueue.splice(0,this.traceQueue.length-this.options.maxLength)),this.draw(),[2]}}))}))},t.prototype.toShortTraceId=function(t){return it(this,void 0,void 0,(function(){return at(this,(function(e){return t?[2,this.request({url:"/api/rontgen/shortTraceId?traceId="+t,method:"GET"})]:[2]}))}))},t.prototype.format=function(t,e){return"#"+(e+1)+"_"+t.traceId},t.prototype.makeContainer=function(){if(window&&document&&!document.getElementById(this.options.containerElmId)){var t=this.options.style,e=document.createElement("canvas");e.id=this.options.containerElmId,e.style.cssText="\n position: fixed;\n width: 100%;\n height: 100%;\n left: 0;\n right: 0;\n top: 0;\n bottom: 0;\n pointer-events: none;\n z-index: 99999;\n opacity: "+t.opacity+";\n letter-spacing: "+t.letterSpacing+"px;\n ",this.context=e.getContext("2d"),document.body.appendChild(e);var n=e.offsetHeight,r=e.offsetWidth;this.pageWidth=r,e.width=this.calc(r),e.height=this.calc(n),this.containerElm=e}},t.prototype.getStyle=function(){var t=this.options.style;return this.pageWidth>1e3?t.pc:t.mobile},t.prototype.calc=function(t){return t*this.dpr},t.prototype.draw=function(){var t=this;if(this.traceQueue.length){this.context||this.makeContainer();var e=this,n=e.context,r=e.options,o=r.style,i=r.autoRemove,a=e.traceQueue,s=void 0===a?[]:a;if(n){var u=n.canvas.getBoundingClientRect(),c=u.width,l=u.height;n.clearRect(0,0,this.calc(c),this.calc(l)),n.font="bold "+this.calc(this.getStyle().fontSize)+"px monospace";for(var p=0,d=this.calc(this.getStyle().fontSize),h=!1,f=function(){for(var t=0,e=0,n=arguments.length;ethis.calc(c)&&(p=0,d+=this.calc(this.getStyle().fontSize+this.getStyle().marginBottom)),d>this.calc(l)){h=!0;break}n.fillStyle=v,n.fillText(E,p,d),p+=Math.ceil(_)+this.calc(this.getStyle().marginRight)}i&&(clearTimeout(this.timer),this.timer=window.setTimeout((function(){return t.clear()}),i))}}},t}(),St=A.HTTP_TRACE_HEADER,Rt=A.SAMPLE_MARK,Ct=A.X_YZ_ACTION_ID_HEADER;function Nt(){}var Ot=function(){function t(t){var e,n=(e=t.loggerUrl||st,function(t){var n=t.url,r=t.method,o=t.data,i=t.headers;return new Promise((function(t){var a=new XMLHttpRequest;a.open(r,e+n,!0),a.timeout=1e4,a.setRequestHeader("Content-Type","application/json; charset=utf-8"),i&&Object.keys(i).forEach((function(t){a.setRequestHeader(t,i[t])})),a.ontimeout=function(e){console.warn("Timeout of 10000 ms exceeded",e),t()},a.onerror=function(e){console.warn("Network Error",e),t()},a.onreadystatechange=function(){4===a.readyState&&t(200===a.status?a.response:void 0)},a.send(o)}))});this.options={appName:t.appName||"unkown-app",request:n,collector:t.collector||Nt,strategy:t.strategy||"delay",reportInterval:t.reportInterval||1e3,maxQueueSize:t.maxQueueSize||10,successCodes:t.successCodes||[0,200],successTextCodes:t.successCodes?t.successCodes.map((function(t){return'"code":'+t+","})):['"code":0,','"code":200,']},t.isResponseFailed&&(this.options.isResponseFailed=t.isResponseFailed),this.waterMark=new It(t.watermark,n)}return t.init=function(e){return this.instance||(this.instance=new t(e),this.instance.interceptXhr(),this.instance.updateSpanBeforeUnload(e.loggerUrl||st)),this.instance},t.setOptions=function(t){if(!this.instance)throw new Error("should call RontgenBrowser#init() first.");t.collector&&(this.instance.options.collector=t.collector),t.isResponseFailed&&(this.instance.options.isResponseFailed=t.isResponseFailed),t.successCodes&&(this.instance.options.successCodes=t.successCodes,this.instance.options.successTextCodes=t.successCodes.map((function(t){return'"code":'+t+","})))},t.prototype.interceptXhr=function(){if("XMLHttpRequest"in window){var t=this.options,e=t.appName,n=t.request,r=t.reportInterval,o=t.strategy,i=t.maxQueueSize,a=new vt({parentId:"null",traceId:"null",appName:e,request:n,strategy:o,reportInterval:r,maxQueueSize:i});this.traceContext=a;var s=this;dt(window.XMLHttpRequest.prototype,"open",(function(t){return function(){for(var e=[],n=0;n=400&&("json"===i.responseType?(r.markError(i.response),s.waterMark.add({traceId:e})):""!==i.responseType&&"text"!==i.responseType||(r.markError(i.responseText),s.waterMark.add({traceId:e})));var h=i.getResponseHeader(St);t||(null==h?void 0:h.includes(Rt))?a.flush():a.removeSpan(r)}catch(t){console.error("[Rontgen] collect tags failed after request finish",t)}}"onreadystatechange"in i&&"function"==typeof i.onreadystatechange?dt(i,"onreadystatechange",(function(t){return function(){for(var e=[],n=0;n0){var r="["+n.map((function(t){return t.toString()})).join(",")+"]";navigator.sendBeacon&&navigator.sendBeacon(t+"/api/rontgen/spans",r)}}))},t}();t.AbstractSampler=W,t.AbstractTagCollector=V,t.BaseTraceContext=U,t.CookieHeaderCodec=H,t.LegacyHeaderCodec=M,t.LogEnum=B,t.OperationTypeEnum=Q,t.ReportQueue=F,t.RontgenBrowser=Ot,t.Span=x,t.TagEnum=P,t.TraceIdGenerator=G,t.__moduleExports=n,t.calSamplingValue=K,t.constants=A,t.generateHexIp=$,t.getActId=Tt,t.getActionId=Tt,t.getRandomInt=J,t.isTraceContext=k,t.parseUrl=et,t.randomString=tt,Object.defineProperty(t,"__esModule",{value:!0})}));