@zuplo/otel 6.51.30 → 6.51.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,25 @@
1
+
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Zuplo, Inc. All rights reserved.
4
+ *
5
+ * This software and associated documentation files (the "Software") is intended to be used
6
+ * only by Zuplo customers solely to develop and test applications that will be deployed
7
+ * to Zuplo hosted services. You and others in your organization may use these files on your
8
+ * Development Devices solely for the above stated purpose.
9
+ *
10
+ * Outside of uses stated above, no license is granted for any other purpose including
11
+ * without limitation the rights to use, copy, modify, merge, publish, distribute,
12
+ * sublicense, host, and/or sell copies of the Software.
13
+ *
14
+ * The software may include third party components with separate legal notices or governed by
15
+ * other agreements, as described in licenses either embedded in or accompanying the Software.
16
+ *
17
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
+ * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
20
+ * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21
+ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
+ * DEALINGS IN THE SOFTWARE.
23
+ *--------------------------------------------------------------------------------------------*/
24
+
25
+ var he=Object.defineProperty;var a=(r,e)=>he(r,"name",{value:e,configurable:!0});import{Buffer as xe}from"node:buffer";globalThis.Buffer=xe;import{TelemetryPlugin as wt,trackFeature as It}from"@zuplo/runtime";import{SpanKind as ze,SpanStatusCode as Ue,context as z,propagation as We,trace as je}from"@opentelemetry/api";import{context as G}from"@opentelemetry/api";var B=Symbol("Otel Tracing Configuration");function K(r,e=G.active()){return e.setValue(B,r)}a(K,"setConfig");function m(){return G.active().getValue(B)}a(m,"getActiveConfig");var k=Symbol("unwrap");function Z(r){return r&&!!r[k]}a(Z,"isWrapped");function Te(r){return typeof r=="object"||typeof r=="function"}a(Te,"isProxyable");function S(r,e,t=!0){if(Z(r)||!Te(r))return r;let n=Object.assign({},e);return n.get=(o,s,i)=>{if(s===k)return r;if(e.get)return e.get(o,s,i);if(s==="bind")return()=>i;if(t)return L(o,s)},n.apply=(o,s,i)=>{if(e.apply)return e.apply(g(o),g(s),i)},new Proxy(r,n)}a(S,"wrap");function g(r){return r&&Z(r)?r[k]:r}a(g,"unwrap");function L(r,e,t){let n=Reflect.get(g(r),e);return typeof n=="function"?(t=t||g(r),n.bind(t)):n}a(L,"passthroughGet");import{trace as ke}from"@opentelemetry/api";import{SpanKind as Ae,TraceFlags as Q,context as M,trace as b}from"@opentelemetry/api";import{sanitizeAttributes as we}from"@opentelemetry/core";import{RandomIdGenerator as Ie,SamplingDecision as Fe}from"@opentelemetry/sdk-trace-base";import{SpanKind as Ce,SpanStatusCode as Re}from"@opentelemetry/api";import{hrTimeDuration as ye,isAttributeValue as be,isTimeInput as Pe,sanitizeAttributes as X}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as Y,ATTR_EXCEPTION_STACKTRACE as Ee,ATTR_EXCEPTION_TYPE as J}from"@opentelemetry/semantic-conventions";function ve(r){let e={};return typeof r=="string"?e[Y]=r:(r.code?e[J]=r.code.toString():r.name&&(e[J]=r.name),r.message&&(e[Y]=r.message),r.stack&&(e[Ee]=r.stack)),e}a(ve,"transformExceptionAttributes");function O(r){return[Math.trunc(r/1e3),r%1e3*1e6]}a(O,"millisToHr");function H(r){let e=Date.now();if(r){if(r instanceof Date)return O(r.getTime());if(typeof r=="number")return O(r);if(Array.isArray(r))return r}else return O(e);let t=r;throw new Error(`unreachable value: ${JSON.stringify(t)}`)}a(H,"getHrTime");function _e(r){return typeof r=="string"&&r.length>0}a(_e,"isAttributeKey");var y=class{static{a(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;parentSpanContext;kind;attributes;status={code:Re.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationScope={name:"@zuplo/otel"};_ended=!1;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.parentSpanContext=e.parentSpanContext,this.kind=e.spanKind||Ce.INTERNAL,this.attributes=X(e.attributes),this.startTime=H(e.startTime),this.links=e.links||[],this.resource=e.resource,this.onEnd=e.onEnd}addLink(e){return this.links.push(e),this}addLinks(e){return this.links.push(...e),this}spanContext(){return this._spanContext}setAttribute(e,t){return _e(e)&&be(t)&&(this.attributes[e]=t),this}setAttributes(e){for(let[t,n]of Object.entries(e))this.setAttribute(t,n);return this}addEvent(e,t,n){Pe(t)&&(n=t,t=void 0);let o=X(t),s=H(n);return this.events.push({name:e,attributes:o,time:s}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=H(e),this._duration=ye(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,t){let n=ve(e);this.addEvent("exception",n,t)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}};var h=class{static{a(this,"WorkerTracer")}_spanProcessors;resource;idGenerator=new Ie;constructor(e,t){this._spanProcessors=e,this.resource=t}get spanProcessors(){return this._spanProcessors}addToResource(e){this.resource.merge(e)}startSpan(e,t={},n=M.active()){t.root&&(n=b.deleteSpan(n));let s=b.getSpan(n)?.spanContext(),i=s&&b.isSpanContextValid(s),p=i?s.traceId:this.idGenerator.generateTraceId(),l=t.kind||Ae.INTERNAL,c=we(t.attributes),u=m().sampling.headSampler.shouldSample(n,p,e,l,c,[]),{decision:x,traceState:w,attributes:I}=u,V=Object.assign({},c,I),T=this.idGenerator.generateSpanId(),$=i?s.spanId:void 0,C=x===Fe.RECORD_AND_SAMPLED?Q.SAMPLED:Q.NONE,F={traceId:p,spanId:T,traceFlags:C,traceState:w},R=new y({attributes:V,name:e,onEnd:a(f=>{this.spanProcessors.forEach(Se=>{Se.onEnd(f)})},"onEnd"),resource:this.resource,spanContext:F,parentSpanId:$,spanKind:l,startTime:t.startTime});return this.spanProcessors.forEach(f=>{f.onStart(R,n)}),R}startActiveSpan(e,...t){let n=t.length>1?t[0]:void 0,o=t.length>2?t[1]:M.active(),s=t[t.length-1],i=this.startSpan(e,n,o),p=b.setSpan(o,i);return M.with(p,s,void 0,i)}};var N=class{static{a(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await Oe(this._outstandingPromises)}};function Le(r,e,t){return S(r,{apply(o,s,i){return t.track(i[0]),Reflect.apply(o,e,i)}})}a(Le,"createWaitUntil");function ee(r){let e=new N;return{event:new Proxy(r,{get(n,o){if(o==="waitUntil"){let s=Reflect.get(n,o);return Le(s,r,e)}else return L(n,o)}}),tracker:e}}a(ee,"proxyExecutionContext");async function te(r){let e=ke.getTracer("export");if(e instanceof h){typeof scheduler<"u"?await scheduler.wait(1):await new Promise(n=>{setTimeout(n,1)}),r&&await r.wait();let t=e.spanProcessors.map(async n=>{await n.forceFlush()});await Promise.allSettled(t)}else console.error("The global tracer is not of type WorkerTracer and can not export spans")}a(te,"exportSpans");async function Oe(r){let e;do e=await Promise.allSettled(r);while(e.length!==r.length);return e}a(Oe,"allSettledMutable");import{SpanKind as He,context as Me,propagation as Ne,trace as qe}from"@opentelemetry/api";function q(r){let e={},t=r.headers,n=r.cf;e["http.request.method"]=r.method.toUpperCase(),e["network.protocol.name"]="http",e["network.protocol.version"]=n?.httpProtocol;let o=t.get("content-length");o&&(e["http.request.body.size"]=o);let s=t.get("user-agent");s&&(e["user_agent.original"]=s);let i=t.get("content-type");i&&(e["http.mime_type"]=i),e["http.accepts"]=n?.clientAcceptEncoding;let p=new URL(r.url);return e["url.full"]=`${p.protocol}//${p.host}${p.pathname}${p.search}`,e["server.address"]=p.host,e["url.scheme"]=p.protocol,e["url.path"]=p.pathname,e["url.query"]=p.search,e}a(q,"gatherRequestAttributes");function D(r){let e={};e["http.response.status_code"]=r.status;let t=r.headers.get("content-length");t&&(e["http.response.body.size"]=t);let n=r.headers.get("content-type");return n&&(e["http.mime_type"]=n),e}a(D,"gatherResponseAttributes");function re(r){let e={},t=r.cf;return e["net.colo"]=t?.colo,e["net.country"]=t?.country,e["net.request_priority"]=t?.requestPriority,e["net.tls_cipher"]=t?.tlsCipher,e["net.tls_version"]=t?.tlsVersion,e["net.asn"]=t?.asn,e["net.tcp_rtt"]=t?.clientTcpRtt,e}a(re,"gatherIncomingCfAttributes");function De(r,e,t){return S(r,{apply:a((o,s,i)=>{let p=new Request(i[0],i[1]);if(!p.url.startsWith("http"))return Reflect.apply(o,s,i);let l=m(),c=e(l),d=qe.getTracer("fetcher"),u={kind:He.CLIENT,attributes:t},x=new URL(p.url).host,w=p.method.toUpperCase(),I=typeof t?.name=="string"?t?.name:`${w}: ${x}`;return d.startActiveSpan(I,u,async T=>{((typeof c.includeTraceContext=="function"?c.includeTraceContext(p):c.includeTraceContext)??!0)&&Ne.inject(Me.active(),p.headers,{set:a((F,R,f)=>F.set(R,typeof f=="string"?f:String(f)),"set")}),T.setAttributes(q(p));let C=await Reflect.apply(o,s,[p]);return T.setAttributes(D(C)),T.end(),C})},"apply")},!0)}a(De,"instrumentClientFetch");function ne(){globalThis.fetch=De(globalThis.fetch,r=>r.fetch)}a(ne,"instrumentGlobalFetch");function Ve(r){return We.extract(z.active(),r,{get(e,t){return e.get(t)||void 0},keys(e){return[...e.keys()]}})}a(Ve,"getParentContextFromHeaders");function $e(r){let e=m();return(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(r):e.handlers.fetch.acceptTraceContext??!0)?Ve(r.headers):z.active()}a($e,"getParentContextFromRequest");var oe=!0;function Ge(r,[e,t]){let n=$e(e),o=je.getTracer("pipeline"),s={"faas.trigger":"http","faas.coldstart":oe,"faas.invocation_id":e.headers.get("zp-rid")??void 0,"cf.ray_id":e.headers.get("cf-ray")??void 0};oe=!1,Object.assign(s,q(e)),Object.assign(s,re(e));let i={attributes:s,kind:ze.SERVER},p=e.method.toUpperCase();return o.startActiveSpan(p,i,n,async c=>{let d=c;try{let u=await r(e,t);return c.setAttributes(D(u)),d.attributes["http.route"]&&c.updateName(`${p} ${d.attributes["http.route"]}`),u}catch(u){throw d.attributes["http.route"]&&c.updateName(`${p} ${d.attributes["http.route"]}`),c.recordException(u),c.setStatus({code:Ue.ERROR}),u}finally{c.end()}})}a(Ge,"executeRequestHandler");function ae(r,e){return S(r,{apply:a(async(n,o,s)=>{let[i,p]=s,l=e(i),{event:c,tracker:d}=ee(p),u=K(l);try{let x=[i,c];return await z.with(u,Ge,void 0,n,x)}finally{p.waitUntil(te(d))}},"apply")})}a(ae,"createHandlerProxy");import{propagation as mt}from"@opentelemetry/api";import{W3CTraceContextPropagator as ft}from"@opentelemetry/core";import{resourceFromAttributes as ue}from"@opentelemetry/resources";import{AlwaysOnSampler as gt,ParentBasedSampler as de,TraceIdRatioBasedSampler as St}from"@opentelemetry/sdk-trace-base";import{ATTR_SERVICE_NAME as ht,ATTR_SERVICE_VERSION as xt,ATTR_TELEMETRY_SDK_NAME as Tt}from"@opentelemetry/semantic-conventions";import{SemanticAttributes as A}from"@zuplo/runtime";import{ExportResultCode as Be}from"@opentelemetry/core";import{JsonTraceSerializer as Ke}from"@opentelemetry/otlp-transformer";import{BackgroundDispatcher as Ze}from"@zuplo/runtime";var Xe={accept:"application/json","content-type":"application/json"},P=class{static{a(this,"OTLPExporter")}headers;url;constructor(e){this.url=e.url,this.headers=Object.assign({},Xe,e.headers)}export(e,t){e.forEach(n=>{this.batcher.enqueue(n)}),t({code:Be.SUCCESS})}shutdown(){throw new Error("Method not implemented.")}forceFlush(){throw new Error("Method not implemented.")}dispatchFunction=a(async e=>{if(e.length===0)return;let t=new TextDecoder,n=Ke.serializeRequest(e),o=t.decode(n),s=await g(fetch)(this.url,{method:"POST",body:o,headers:this.headers});if(!s.ok)try{let i=await s.text();console.error("Error exporting traces",i)}catch{console.error("Error exporting traces")}},"dispatchFunction");batcher=new Ze(this.dispatchFunction,{msDelay:10})};import{context as tt,trace as rt}from"@opentelemetry/api";import{AsyncLocalStorage as Ye}from"node:async_hooks";import{EventEmitter as Je}from"node:events";import{ROOT_CONTEXT as Qe}from"@opentelemetry/api";var et=["addListener","on","once","prependListener","prependOnceListener"],U=class{static{a(this,"AbstractAsyncHooksContextManager")}bind(e,t){return t instanceof Je?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}_bindFunction(e,t){let n=this,o=a(function(...s){return n.with(e,()=>t.apply(this,s))},"contextWrapper");return Object.defineProperty(o,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),o}_bindEventEmitter(e,t){return this._getPatchMap(t)!==void 0||(this._createPatchMap(t),et.forEach(o=>{t[o]!==void 0&&(t[o]=this._patchAddListener(t,t[o],e))}),typeof t.removeListener=="function"&&(t.removeListener=this._patchRemoveListener(t,t.removeListener)),typeof t.off=="function"&&(t.off=this._patchRemoveListener(t,t.off)),typeof t.removeAllListeners=="function"&&(t.removeAllListeners=this._patchRemoveAllListeners(t,t.removeAllListeners))),t}_patchRemoveListener(e,t){let n=this;return function(o,s){let i=n._getPatchMap(e)?.[o];if(i===void 0)return t.call(this,o,s);let p=i.get(s);return t.call(this,o,p||s)}}_patchRemoveAllListeners(e,t){let n=this;return function(o){let s=n._getPatchMap(e);return s!==void 0&&(arguments.length===0?n._createPatchMap(e):s[o]!==void 0&&delete s[o]),t.apply(this,arguments)}}_patchAddListener(e,t,n){let o=this;return function(s,i){if(o._wrapped)return t.call(this,s,i);let p=o._getPatchMap(e);p===void 0&&(p=o._createPatchMap(e));let l=p[s];l===void 0&&(l=new WeakMap,p[s]=l);let c=o.bind(n,i);l.set(i,c),o._wrapped=!0;try{return t.call(this,s,c)}finally{o._wrapped=!1}}}_createPatchMap(e){let t=Object.create(null);return e[this._kOtListeners]=t,t}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},E=class extends U{static{a(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Ye}active(){return this._asyncLocalStorage.getStore()??Qe}with(e,t,n,...o){let s=n==null?t:t.bind(n);return this._asyncLocalStorage.run(e,s,...o)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};var v=class{static{a(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,t){this.spanProcessors=e,this.resource=t}getTracer(e,t,n){let o=`${e}@${t||""}:${n?.schemaUrl||""}`;return this.tracers[o]||(this.tracers[o]=new h(this.spanProcessors,this.resource)),this.tracers[o]}register(){rt.setGlobalTracerProvider(this),tt.setGlobalContextManager(new E)}};import{SpanStatusCode as nt,TraceFlags as ot}from"@opentelemetry/api";import{SemanticAttributes as W}from"@zuplo/runtime";function se(r){return e=>{let t=e.localRootSpan;return t.attributes[W.SystemTrace]??t.attributes[W.RouteSystem]??t.attributes[W.RouteTrace]===!1?!1:r(e)}}a(se,"internalTailSampler");function ie(r){return e=>r.reduce((t,n)=>t||n(e),!1)}a(ie,"multiTailSampler");var pe=a(r=>r.localRootSpan.spanContext().traceFlags===ot.SAMPLED,"isHeadSampled"),ce=a(r=>r.localRootSpan.status.code===nt.ERROR,"isRootErrorSpan");import{trace as at}from"@opentelemetry/api";import{ExportResultCode as st}from"@opentelemetry/core";import{stateMachine as it}from"ts-checked-fsm";function pt(r,{span:e}){let t=e.spanContext().spanId;return{...r,stateName:"in_progress",traceId:e.spanContext().traceId,localRootSpan:e,completedSpans:[],inProgressSpanIds:new Set([t])}}a(pt,"newTrace");function ct(r,{span:e}){let t=e.spanContext().spanId;return r.inProgressSpanIds.add(t),{...r}}a(ct,"newSpan");function lt(r,{span:e}){return r.completedSpans.push(e),r.inProgressSpanIds.delete(e.spanContext().spanId),r.inProgressSpanIds.size===0?{stateName:"trace_complete",traceId:r.traceId,localRootSpan:r.localRootSpan,completedSpans:r.completedSpans}:{...r}}a(lt,"endSpan");function ut(r,{args:e}){let{exporter:t,tailSampler:n,postProcessor:o}=e,{traceId:s,localRootSpan:i,completedSpans:p}=r;if(n({traceId:s,localRootSpan:i,spans:p})){let c=o(p);return{stateName:"exporting",promise:new Promise(u=>{t.export(c,u)})}}else return{stateName:"done"}}a(ut,"startExport");var{nextState:dt}=it().state("not_started").state("in_progress").state("trace_complete").state("exporting").state("done").transition("not_started","in_progress").transition("in_progress","in_progress").transition("in_progress","trace_complete").transition("trace_complete","exporting").transition("trace_complete","done").transition("exporting","done").action("startSpan").action("endSpan").action("startExport").action("exportDone").actionHandler("not_started","startSpan",pt).actionHandler("in_progress","startSpan",ct).actionHandler("in_progress","endSpan",lt).actionHandler("trace_complete","startExport",ut).actionHandler("exporting","exportDone",(r,e)=>({stateName:"done"})).done(),_=class{constructor(e){this.exporter=e}static{a(this,"BatchTraceSpanProcessor")}traceLookup=new Map;localRootSpanLookup=new Map;inprogressExports=new Map;action(e,t){let n=this.traceLookup.get(e)||{stateName:"not_started"},o=dt(n,t);return o.stateName==="done"?this.traceLookup.delete(e):this.traceLookup.set(e,o),o}export(e){let{sampling:t,postProcessor:n}=m(),o={exporter:this.exporter,tailSampler:t.tailSampler,postProcessor:n},s=this.action(e,{actionName:"startExport",args:o});if(s.stateName==="exporting"){let i=s.promise;this.inprogressExports.set(e,i),i.then(p=>{p.code===st.FAILED&&console.log("Error sending spans to exporter:",p.error),this.action(e,{actionName:"exportDone"}),this.inprogressExports.delete(e)})}}onStart(e,t){let n=e.spanContext().spanId,o=at.getSpan(t)?.spanContext()?.spanId,i=(o?this.localRootSpanLookup.get(o):void 0)||n;this.localRootSpanLookup.set(n,i),this.action(i,{actionName:"startSpan",span:e})}onEnd(e){let t=e.spanContext().spanId,n=this.localRootSpanLookup.get(t);if(n){let o=this.action(n,{actionName:"endSpan",span:e});o.stateName==="trace_complete"&&(o.completedSpans.forEach(s=>{this.localRootSpanLookup.delete(s.spanContext().spanId)}),this.export(n))}}async forceFlush(){await Promise.allSettled(this.inprogressExports.values())}async shutdown(){}};function le(r){return!!r.spanProcessors}a(le,"isSpanProcessorConfig");import{ATTR_CLOUD_ACCOUNT_ID as Ct,ATTR_CLOUD_PLATFORM as Rt,ATTR_CLOUD_PROVIDER as yt,ATTR_SERVICE_NAMESPACE as bt}from"@opentelemetry/semantic-conventions/incubating";var Pt=a((r,e)=>{let t={[yt]:"zuplo",[Rt]:"zuplo-api",[Ct]:r.accountName,"cloud.project.id":r.projectName,"cloud.resource_id":r.deploymentName,"cloud.instance_id":r.instanceId,"deployment.environment.name":r.environmentStage,[Tt]:"@zuplo/otel",[A.ZuploBuildId]:r.buildId,[A.ZuploBuildVersion]:r.zuploVersion,[A.ZuploBuildCompatibilityDate]:r.compatibilityDate,[A.ZuploEnvironmentType]:r.environmentType},n=ue({[ht]:e.service.name,[bt]:e.service.namespace,[xt]:e.service.version});return ue(t).merge(n)},"createResource");function Et(r){return!!r.export}a(Et,"isSpanExporter");function vt(r){return!!r.shouldSample}a(vt,"isSampler");function _t(r){let e=new St(r.ratio);return typeof r.acceptRemote=="boolean"&&!r.acceptRemote?new de({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new de({root:e})}a(_t,"createSampler");var me=!1;function At(r,e){if(!me){ne(),mt.setGlobalPropagator(e.propagator);let t=Pt(r,e);new v(e.spanProcessors,t).register(),me=!0}}a(At,"init");function fe(r,e){if(le(e)){let t=e.sampling?.headSampler,n=t?vt(t)?t:_t(t):new gt,o=Array.isArray(e.spanProcessors)?e.spanProcessors:[e.spanProcessors];return o.length===0&&console.log("Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration."),{fetch:{includeTraceContext:e.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:e.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:e.postProcessor??(s=>s),sampling:{headSampler:n,tailSampler:se(e.sampling?.tailSampler??ie([pe,ce]))},service:{name:e.service?.name??r.deploymentName,version:e.service?.version,namespace:e.service?.namespace},spanProcessors:o,propagator:e.propagator??new ft}}else{let t=Et(e.exporter)?e.exporter:new P(e.exporter),n=[new _(t)],o=Object.assign(e,{exporter:void 0,spanProcessors:n});return fe(r,o)}}a(fe,"parseConfig");function ge(r,e){return()=>{let t=fe(r,e);return At(r,t),t}}a(ge,"createInitializer");var j=class extends wt{constructor(t){super();this.config=t;It("opentelemetry")}static{a(this,"OpenTelemetryPlugin")}instrument(t){let n=ge(t,this.config);return{requestHandlerProxy:a(s=>ae(s,n),"requestHandlerProxy")}}};export{j as a};
package/out/esm/index.js CHANGED
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a}from"./chunk-OPHLYIRC.js";export{a as OpenTelemetryPlugin};
25
+ import{a}from"./chunk-RKVZF2YJ.js";export{a as OpenTelemetryPlugin};
@@ -1,4 +1,3 @@
1
- import { OtlpEncodingOptions } from '@opentelemetry/otlp-transformer';
2
1
  import { ReadableSpan } from '@opentelemetry/sdk-trace-base';
3
2
  import { RequestHandlerProxy } from '@zuplo/runtime';
4
3
  import { Sampler } from '@opentelemetry/sdk-trace-base';
@@ -42,7 +41,7 @@ export declare class OpenTelemetryPlugin extends TelemetryPlugin {
42
41
  };
43
42
  }
44
43
 
45
- declare interface OTLPExporterConfig extends OtlpEncodingOptions {
44
+ declare interface OTLPExporterConfig {
46
45
  url: string;
47
46
  headers?: Record<string, string>;
48
47
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/otel",
3
3
  "type": "module",
4
- "version": "6.51.30",
4
+ "version": "6.51.32",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {
@@ -28,17 +28,17 @@
28
28
  "typescript": "^5.6.2"
29
29
  },
30
30
  "dependencies": {
31
- "@opentelemetry/api": "1.8.0",
32
- "@opentelemetry/core": "1.22.0",
33
- "@opentelemetry/exporter-trace-otlp-http": "0.49.1",
34
- "@opentelemetry/otlp-exporter-base": "0.49.1",
35
- "@opentelemetry/otlp-transformer": "0.49.1",
36
- "@opentelemetry/resources": "1.22.0",
37
- "@opentelemetry/sdk-trace-base": "1.22.0",
38
- "@opentelemetry/semantic-conventions": "1.22.0",
31
+ "@opentelemetry/api": "1.9.0",
32
+ "@opentelemetry/core": "2.0.1",
33
+ "@opentelemetry/exporter-trace-otlp-http": "0.201.1",
34
+ "@opentelemetry/otlp-exporter-base": "0.201.1",
35
+ "@opentelemetry/otlp-transformer": "0.201.1",
36
+ "@opentelemetry/resources": "2.0.1",
37
+ "@opentelemetry/sdk-trace-base": "2.0.1",
38
+ "@opentelemetry/semantic-conventions": "1.34.0",
39
39
  "ts-checked-fsm": "^1.1.0"
40
40
  },
41
41
  "peerDependencies": {
42
- "@zuplo/runtime": "6.51.30"
42
+ "@zuplo/runtime": "6.51.32"
43
43
  }
44
44
  }
@@ -1,25 +0,0 @@
1
-
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Zuplo, Inc. All rights reserved.
4
- *
5
- * This software and associated documentation files (the "Software") is intended to be used
6
- * only by Zuplo customers solely to develop and test applications that will be deployed
7
- * to Zuplo hosted services. You and others in your organization may use these files on your
8
- * Development Devices solely for the above stated purpose.
9
- *
10
- * Outside of uses stated above, no license is granted for any other purpose including
11
- * without limitation the rights to use, copy, modify, merge, publish, distribute,
12
- * sublicense, host, and/or sell copies of the Software.
13
- *
14
- * The software may include third party components with separate legal notices or governed by
15
- * other agreements, as described in licenses either embedded in or accompanying the Software.
16
- *
17
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
18
- * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
19
- * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
20
- * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
21
- * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22
- * DEALINGS IN THE SOFTWARE.
23
- *--------------------------------------------------------------------------------------------*/
24
-
25
- var he=Object.defineProperty;var a=(r,e)=>he(r,"name",{value:e,configurable:!0});import{Buffer as xe}from"node:buffer";globalThis.Buffer=xe;import{TelemetryPlugin as It,trackFeature as Ft}from"@zuplo/runtime";import{SpanKind as ze,SpanStatusCode as Ue,context as z,propagation as Be,trace as We}from"@opentelemetry/api";import{context as $}from"@opentelemetry/api";var G=Symbol("Otel Tracing Configuration");function K(r,e=$.active()){return e.setValue(G,r)}a(K,"setConfig");function m(){return $.active().getValue(G)}a(m,"getActiveConfig");var L=Symbol("unwrap");function Z(r){return r&&!!r[L]}a(Z,"isWrapped");function Te(r){return typeof r=="object"||typeof r=="function"}a(Te,"isProxyable");function g(r,e,t=!0){if(Z(r)||!Te(r))return r;let n=Object.assign({},e);return n.get=(o,s,p)=>{if(s===L)return r;if(e.get)return e.get(o,s,p);if(s==="bind")return()=>p;if(t)return k(o,s)},n.apply=(o,s,p)=>{if(e.apply)return e.apply(S(o),S(s),p)},new Proxy(r,n)}a(g,"wrap");function S(r){return r&&Z(r)?r[L]:r}a(S,"unwrap");function k(r,e,t){let n=Reflect.get(S(r),e);return typeof n=="function"?(t=t||S(r),n.bind(t)):n}a(k,"passthroughGet");import{trace as Le}from"@opentelemetry/api";import{SpanKind as Ae,TraceFlags as Q,context as M,trace as E}from"@opentelemetry/api";import{sanitizeAttributes as we}from"@opentelemetry/core";import{RandomIdGenerator as Ie,SamplingDecision as Fe}from"@opentelemetry/sdk-trace-base";import{SpanKind as Re,SpanStatusCode as Ce}from"@opentelemetry/api";import{hrTimeDuration as ye,isAttributeKey as Ee,isAttributeValue as be,isTimeInput as Pe,sanitizeAttributes as X}from"@opentelemetry/core";import{SEMATTRS_EXCEPTION_MESSAGE as Y,SEMATTRS_EXCEPTION_STACKTRACE as ve,SEMATTRS_EXCEPTION_TYPE as J}from"@opentelemetry/semantic-conventions";function _e(r){let e={};return typeof r=="string"?e[Y]=r:(r.code?e[J]=r.code.toString():r.name&&(e[J]=r.name),r.message&&(e[Y]=r.message),r.stack&&(e[ve]=r.stack)),e}a(_e,"transformExceptionAttributes");function O(r){return[Math.trunc(r/1e3),r%1e3*1e6]}a(O,"millisToHr");function H(r){let e=Date.now();if(r){if(r instanceof Date)return O(r.getTime());if(typeof r=="number")return O(r);if(Array.isArray(r))return r}else return O(e);let t=r;throw new Error(`unreachable value: ${JSON.stringify(t)}`)}a(H,"getHrTime");var y=class{static{a(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;kind;attributes;status={code:Ce.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationLibrary={name:"@zuplo/otel"};_ended=!1;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;constructor(e){this.name=e.name,this._spanContext=e.spanContext,this.parentSpanId=e.parentSpanId,this.kind=e.spanKind||Re.INTERNAL,this.attributes=X(e.attributes),this.startTime=H(e.startTime),this.links=e.links||[],this.resource=e.resource,this.onEnd=e.onEnd}spanContext(){return this._spanContext}setAttribute(e,t){return Ee(e)&&be(t)&&(this.attributes[e]=t),this}setAttributes(e){for(let[t,n]of Object.entries(e))this.setAttribute(t,n);return this}addEvent(e,t,n){Pe(t)&&(n=t,t=void 0);let o=X(t),s=H(n);return this.events.push({name:e,attributes:o,time:s}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=H(e),this._duration=ye(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,t){let n=_e(e);this.addEvent("exception",n,t)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}};var h=class{static{a(this,"WorkerTracer")}_spanProcessors;resource;idGenerator=new Ie;constructor(e,t){this._spanProcessors=e,this.resource=t}get spanProcessors(){return this._spanProcessors}addToResource(e){this.resource.merge(e)}startSpan(e,t={},n=M.active()){t.root&&(n=E.deleteSpan(n));let s=E.getSpan(n)?.spanContext(),p=s&&E.isSpanContextValid(s),i=p?s.traceId:this.idGenerator.generateTraceId(),l=t.kind||Ae.INTERNAL,c=we(t.attributes),u=m().sampling.headSampler.shouldSample(n,i,e,l,c,[]),{decision:x,traceState:w,attributes:I}=u,j=Object.assign({},c,I),T=this.idGenerator.generateSpanId(),V=p?s.spanId:void 0,R=x===Fe.RECORD_AND_SAMPLED?Q.SAMPLED:Q.NONE,F={traceId:i,spanId:T,traceFlags:R,traceState:w},C=new y({attributes:j,name:e,onEnd:a(f=>{this.spanProcessors.forEach(ge=>{ge.onEnd(f)})},"onEnd"),resource:this.resource,spanContext:F,parentSpanId:V,spanKind:l,startTime:t.startTime});return this.spanProcessors.forEach(f=>{f.onStart(C,n)}),C}startActiveSpan(e,...t){let n=t.length>1?t[0]:void 0,o=t.length>2?t[1]:M.active(),s=t[t.length-1],p=this.startSpan(e,n,o),i=E.setSpan(o,p);return M.with(i,s,void 0,p)}};var N=class{static{a(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await Oe(this._outstandingPromises)}};function ke(r,e,t){return g(r,{apply(o,s,p){return t.track(p[0]),Reflect.apply(o,e,p)}})}a(ke,"createWaitUntil");function ee(r){let e=new N;return{event:new Proxy(r,{get(n,o){if(o==="waitUntil"){let s=Reflect.get(n,o);return ke(s,r,e)}else return k(n,o)}}),tracker:e}}a(ee,"proxyExecutionContext");async function te(r){let e=Le.getTracer("export");if(e instanceof h){typeof scheduler<"u"?await scheduler.wait(1):await new Promise(n=>{setTimeout(n,1)}),r&&await r.wait();let t=e.spanProcessors.map(async n=>{await n.forceFlush()});await Promise.allSettled(t)}else console.error("The global tracer is not of type WorkerTracer and can not export spans")}a(te,"exportSpans");async function Oe(r){let e;do e=await Promise.allSettled(r);while(e.length!==r.length);return e}a(Oe,"allSettledMutable");import{SpanKind as He,context as Me,propagation as Ne,trace as qe}from"@opentelemetry/api";function q(r){let e={},t=r.headers,n=r.cf;e["http.request.method"]=r.method.toUpperCase(),e["network.protocol.name"]="http",e["network.protocol.version"]=n?.httpProtocol;let o=t.get("content-length");o&&(e["http.request.body.size"]=o);let s=t.get("user-agent");s&&(e["user_agent.original"]=s);let p=t.get("content-type");p&&(e["http.mime_type"]=p),e["http.accepts"]=n?.clientAcceptEncoding;let i=new URL(r.url);return e["url.full"]=`${i.protocol}//${i.host}${i.pathname}${i.search}`,e["server.address"]=i.host,e["url.scheme"]=i.protocol,e["url.path"]=i.pathname,e["url.query"]=i.search,e}a(q,"gatherRequestAttributes");function D(r){let e={};e["http.response.status_code"]=r.status;let t=r.headers.get("content-length");t&&(e["http.response.body.size"]=t);let n=r.headers.get("content-type");return n&&(e["http.mime_type"]=n),e}a(D,"gatherResponseAttributes");function re(r){let e={},t=r.cf;return e["net.colo"]=t?.colo,e["net.country"]=t?.country,e["net.request_priority"]=t?.requestPriority,e["net.tls_cipher"]=t?.tlsCipher,e["net.tls_version"]=t?.tlsVersion,e["net.asn"]=t?.asn,e["net.tcp_rtt"]=t?.clientTcpRtt,e}a(re,"gatherIncomingCfAttributes");function De(r,e,t){return g(r,{apply:a((o,s,p)=>{let i=new Request(p[0],p[1]);if(!i.url.startsWith("http"))return Reflect.apply(o,s,p);let l=m(),c=e(l),d=qe.getTracer("fetcher"),u={kind:He.CLIENT,attributes:t},x=new URL(i.url).host,w=i.method.toUpperCase(),I=typeof t?.name=="string"?t?.name:`${w}: ${x}`;return d.startActiveSpan(I,u,async T=>{((typeof c.includeTraceContext=="function"?c.includeTraceContext(i):c.includeTraceContext)??!0)&&Ne.inject(Me.active(),i.headers,{set:a((F,C,f)=>F.set(C,typeof f=="string"?f:String(f)),"set")}),T.setAttributes(q(i));let R=await Reflect.apply(o,s,[i]);return T.setAttributes(D(R)),T.end(),R})},"apply")},!0)}a(De,"instrumentClientFetch");function ne(){globalThis.fetch=De(globalThis.fetch,r=>r.fetch)}a(ne,"instrumentGlobalFetch");function je(r){return Be.extract(z.active(),r,{get(e,t){return e.get(t)||void 0},keys(e){return[...e.keys()]}})}a(je,"getParentContextFromHeaders");function Ve(r){let e=m();return(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(r):e.handlers.fetch.acceptTraceContext??!0)?je(r.headers):z.active()}a(Ve,"getParentContextFromRequest");var oe=!0;function $e(r,[e,t]){let n=Ve(e),o=We.getTracer("pipeline"),s={"faas.trigger":"http","faas.coldstart":oe,"faas.invocation_id":e.headers.get("zp-rid")??void 0,"cf.ray_id":e.headers.get("cf-ray")??void 0};oe=!1,Object.assign(s,q(e)),Object.assign(s,re(e));let p={attributes:s,kind:ze.SERVER},i=e.method.toUpperCase();return o.startActiveSpan(i,p,n,async c=>{let d=c;try{let u=await r(e,t);return c.setAttributes(D(u)),d.attributes["http.route"]&&c.updateName(`${i} ${d.attributes["http.route"]}`),u}catch(u){throw d.attributes["http.route"]&&c.updateName(`${i} ${d.attributes["http.route"]}`),c.recordException(u),c.setStatus({code:Ue.ERROR}),u}finally{c.end()}})}a($e,"executeRequestHandler");function ae(r,e){return g(r,{apply:a(async(n,o,s)=>{let[p,i]=s,l=e(p),{event:c,tracker:d}=ee(i),u=K(l);try{let x=[p,c];return await z.with(u,$e,void 0,n,x)}finally{i.waitUntil(te(d))}},"apply")})}a(ae,"createHandlerProxy");import{propagation as mt}from"@opentelemetry/api";import{W3CTraceContextPropagator as ft}from"@opentelemetry/core";import{Resource as ue}from"@opentelemetry/resources";import{AlwaysOnSampler as St,ParentBasedSampler as de,TraceIdRatioBasedSampler as gt}from"@opentelemetry/sdk-trace-base";import{SEMRESATTRS_CLOUD_ACCOUNT_ID as ht,SEMRESATTRS_CLOUD_PLATFORM as xt,SEMRESATTRS_CLOUD_PROVIDER as Tt,SEMRESATTRS_DEPLOYMENT_ENVIRONMENT as Rt,SEMRESATTRS_SERVICE_NAME as Ct,SEMRESATTRS_SERVICE_NAMESPACE as yt,SEMRESATTRS_SERVICE_VERSION as Et,SEMRESATTRS_TELEMETRY_SDK_NAME as bt}from"@opentelemetry/semantic-conventions";import{SemanticAttributes as A}from"@zuplo/runtime";import{ExportResultCode as Ge}from"@opentelemetry/core";import{createExportTraceServiceRequest as Ke}from"@opentelemetry/otlp-transformer";import{BackgroundDispatcher as Ze}from"@zuplo/runtime";var Xe={accept:"application/json","content-type":"application/json"},b=class{static{a(this,"OTLPExporter")}headers;url;useHex;useLongBits;constructor(e){this.url=e.url,this.headers=Object.assign({},Xe,e.headers),this.useHex=e.useHex,this.useLongBits=e.useLongBits}export(e,t){e.forEach(n=>{this.batcher.enqueue(n)}),t({code:Ge.SUCCESS})}shutdown(){throw new Error("Method not implemented.")}forceFlush(){throw new Error("Method not implemented.")}dispatchFunction=a(async e=>{if(e.length===0)return;let t=Ke(e,{useLongBits:this.useLongBits,useHex:this.useHex}),n=await S(fetch)(this.url,{method:"POST",body:JSON.stringify(t),headers:this.headers});if(!n.ok)try{let o=await n.text();console.error("Error exporting traces",o)}catch{console.error("Error exporting traces")}},"dispatchFunction");batcher=new Ze(this.dispatchFunction,{msDelay:10})};import{context as tt,trace as rt}from"@opentelemetry/api";import{AsyncLocalStorage as Ye}from"node:async_hooks";import{EventEmitter as Je}from"node:events";import{ROOT_CONTEXT as Qe}from"@opentelemetry/api";var et=["addListener","on","once","prependListener","prependOnceListener"],U=class{static{a(this,"AbstractAsyncHooksContextManager")}bind(e,t){return t instanceof Je?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}_bindFunction(e,t){let n=this,o=a(function(...s){return n.with(e,()=>t.apply(this,s))},"contextWrapper");return Object.defineProperty(o,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),o}_bindEventEmitter(e,t){return this._getPatchMap(t)!==void 0||(this._createPatchMap(t),et.forEach(o=>{t[o]!==void 0&&(t[o]=this._patchAddListener(t,t[o],e))}),typeof t.removeListener=="function"&&(t.removeListener=this._patchRemoveListener(t,t.removeListener)),typeof t.off=="function"&&(t.off=this._patchRemoveListener(t,t.off)),typeof t.removeAllListeners=="function"&&(t.removeAllListeners=this._patchRemoveAllListeners(t,t.removeAllListeners))),t}_patchRemoveListener(e,t){let n=this;return function(o,s){let p=n._getPatchMap(e)?.[o];if(p===void 0)return t.call(this,o,s);let i=p.get(s);return t.call(this,o,i||s)}}_patchRemoveAllListeners(e,t){let n=this;return function(o){let s=n._getPatchMap(e);return s!==void 0&&(arguments.length===0?n._createPatchMap(e):s[o]!==void 0&&delete s[o]),t.apply(this,arguments)}}_patchAddListener(e,t,n){let o=this;return function(s,p){if(o._wrapped)return t.call(this,s,p);let i=o._getPatchMap(e);i===void 0&&(i=o._createPatchMap(e));let l=i[s];l===void 0&&(l=new WeakMap,i[s]=l);let c=o.bind(n,p);l.set(p,c),o._wrapped=!0;try{return t.call(this,s,c)}finally{o._wrapped=!1}}}_createPatchMap(e){let t=Object.create(null);return e[this._kOtListeners]=t,t}_getPatchMap(e){return e[this._kOtListeners]}_kOtListeners=Symbol("OtListeners");_wrapped=!1},P=class extends U{static{a(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Ye}active(){return this._asyncLocalStorage.getStore()??Qe}with(e,t,n,...o){let s=n==null?t:t.bind(n);return this._asyncLocalStorage.run(e,s,...o)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};var v=class{static{a(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,t){this.spanProcessors=e,this.resource=t}getTracer(e,t,n){let o=`${e}@${t||""}:${n?.schemaUrl||""}`;return this.tracers[o]||(this.tracers[o]=new h(this.spanProcessors,this.resource)),this.tracers[o]}register(){rt.setGlobalTracerProvider(this),tt.setGlobalContextManager(new P)}};import{SpanStatusCode as nt,TraceFlags as ot}from"@opentelemetry/api";import{SemanticAttributes as B}from"@zuplo/runtime";function se(r){return e=>{let t=e.localRootSpan;return t.attributes[B.SystemTrace]??t.attributes[B.RouteSystem]??t.attributes[B.RouteTrace]===!1?!1:r(e)}}a(se,"internalTailSampler");function ie(r){return e=>r.reduce((t,n)=>t||n(e),!1)}a(ie,"multiTailSampler");var pe=a(r=>r.localRootSpan.spanContext().traceFlags===ot.SAMPLED,"isHeadSampled"),ce=a(r=>r.localRootSpan.status.code===nt.ERROR,"isRootErrorSpan");import{trace as at}from"@opentelemetry/api";import{ExportResultCode as st}from"@opentelemetry/core";import{stateMachine as it}from"ts-checked-fsm";function pt(r,{span:e}){let t=e.spanContext().spanId;return{...r,stateName:"in_progress",traceId:e.spanContext().traceId,localRootSpan:e,completedSpans:[],inProgressSpanIds:new Set([t])}}a(pt,"newTrace");function ct(r,{span:e}){let t=e.spanContext().spanId;return r.inProgressSpanIds.add(t),{...r}}a(ct,"newSpan");function lt(r,{span:e}){return r.completedSpans.push(e),r.inProgressSpanIds.delete(e.spanContext().spanId),r.inProgressSpanIds.size===0?{stateName:"trace_complete",traceId:r.traceId,localRootSpan:r.localRootSpan,completedSpans:r.completedSpans}:{...r}}a(lt,"endSpan");function ut(r,{args:e}){let{exporter:t,tailSampler:n,postProcessor:o}=e,{traceId:s,localRootSpan:p,completedSpans:i}=r;if(n({traceId:s,localRootSpan:p,spans:i})){let c=o(i);return{stateName:"exporting",promise:new Promise(u=>{t.export(c,u)})}}else return{stateName:"done"}}a(ut,"startExport");var{nextState:dt}=it().state("not_started").state("in_progress").state("trace_complete").state("exporting").state("done").transition("not_started","in_progress").transition("in_progress","in_progress").transition("in_progress","trace_complete").transition("trace_complete","exporting").transition("trace_complete","done").transition("exporting","done").action("startSpan").action("endSpan").action("startExport").action("exportDone").actionHandler("not_started","startSpan",pt).actionHandler("in_progress","startSpan",ct).actionHandler("in_progress","endSpan",lt).actionHandler("trace_complete","startExport",ut).actionHandler("exporting","exportDone",(r,e)=>({stateName:"done"})).done(),_=class{constructor(e){this.exporter=e}static{a(this,"BatchTraceSpanProcessor")}traceLookup=new Map;localRootSpanLookup=new Map;inprogressExports=new Map;action(e,t){let n=this.traceLookup.get(e)||{stateName:"not_started"},o=dt(n,t);return o.stateName==="done"?this.traceLookup.delete(e):this.traceLookup.set(e,o),o}export(e){let{sampling:t,postProcessor:n}=m(),o={exporter:this.exporter,tailSampler:t.tailSampler,postProcessor:n},s=this.action(e,{actionName:"startExport",args:o});if(s.stateName==="exporting"){let p=s.promise;this.inprogressExports.set(e,p),p.then(i=>{i.code===st.FAILED&&console.log("Error sending spans to exporter:",i.error),this.action(e,{actionName:"exportDone"}),this.inprogressExports.delete(e)})}}onStart(e,t){let n=e.spanContext().spanId,o=at.getSpan(t)?.spanContext()?.spanId,p=(o?this.localRootSpanLookup.get(o):void 0)||n;this.localRootSpanLookup.set(n,p),this.action(p,{actionName:"startSpan",span:e})}onEnd(e){let t=e.spanContext().spanId,n=this.localRootSpanLookup.get(t);if(n){let o=this.action(n,{actionName:"endSpan",span:e});o.stateName==="trace_complete"&&(o.completedSpans.forEach(s=>{this.localRootSpanLookup.delete(s.spanContext().spanId)}),this.export(n))}}async forceFlush(){await Promise.allSettled(this.inprogressExports.values())}async shutdown(){}};function le(r){return!!r.spanProcessors}a(le,"isSpanProcessorConfig");var Pt=a((r,e)=>{let t={[Tt]:"zuplo",[xt]:"zuplo-api",[ht]:r.accountName,"cloud.project.id":r.projectName,"cloud.resource_id":r.deploymentName,"cloud.instance_id":r.instanceId,[Rt]:r.environmentStage,[bt]:"@zuplo/otel",[A.ZuploBuildId]:r.buildId,[A.ZuploBuildVersion]:r.zuploVersion,[A.ZuploBuildCompatibilityDate]:r.compatibilityDate,[A.ZuploEnvironmentType]:r.environmentType},n=new ue({[Ct]:e.service.name,[yt]:e.service.namespace,[Et]:e.service.version});return new ue(t).merge(n)},"createResource");function vt(r){return!!r.export}a(vt,"isSpanExporter");function _t(r){return!!r.shouldSample}a(_t,"isSampler");function At(r){let e=new gt(r.ratio);return typeof r.acceptRemote=="boolean"&&!r.acceptRemote?new de({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new de({root:e})}a(At,"createSampler");var me=!1;function wt(r,e){if(!me){ne(),mt.setGlobalPropagator(e.propagator);let t=Pt(r,e);new v(e.spanProcessors,t).register(),me=!0}}a(wt,"init");function fe(r,e){if(le(e)){let t=e.sampling?.headSampler,n=t?_t(t)?t:At(t):new St,o=Array.isArray(e.spanProcessors)?e.spanProcessors:[e.spanProcessors];return o.length===0&&console.log("Warning! You must either specify an exporter or your own SpanProcessor(s)/Exporter combination in the open-telemetry configuration."),{fetch:{includeTraceContext:e.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:e.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:e.postProcessor??(s=>s),sampling:{headSampler:n,tailSampler:se(e.sampling?.tailSampler??ie([pe,ce]))},service:{name:e.service?.name??r.deploymentName,version:e.service?.version,namespace:e.service?.namespace},spanProcessors:o,propagator:e.propagator??new ft}}else{let t=vt(e.exporter)?e.exporter:new b({useHex:!0,useLongBits:!1,...e.exporter}),n=[new _(t)],o=Object.assign(e,{exporter:void 0,spanProcessors:n});return fe(r,o)}}a(fe,"parseConfig");function Se(r,e){return()=>{let t=fe(r,e);return wt(r,t),t}}a(Se,"createInitializer");var W=class extends It{constructor(t){super();this.config=t;Ft("opentelemetry")}static{a(this,"OpenTelemetryPlugin")}instrument(t){let n=Se(t,this.config);return{requestHandlerProxy:a(s=>ae(s,n),"requestHandlerProxy")}}};export{W as a};