
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Zuplo, Inc. All rights reserved.
 *
 *  This software and associated documentation files (the "Software") is intended to be used
 *  only by Zuplo customers solely to develop and test applications that will be deployed
 *  to Zuplo hosted services. You and others in your organization may use these files on your
 *  Development Devices solely for the above stated purpose.
 *
 *  Outside of uses stated above, no license is granted for any other purpose including
 *  without limitation the rights to use, copy, modify, merge, publish, distribute,
 *  sublicense, host, and/or sell copies of the Software.
 *
 *  The software may include third party components with separate legal notices or governed by
 *  other agreements, as described in licenses either embedded in or accompanying the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 *  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
 *  PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
 *  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
 *  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 *--------------------------------------------------------------------------------------------*/
    
var Ct=Object.defineProperty;var n=(r,e)=>Ct(r,"name",{value:e,configurable:!0});import{Buffer as yt}from"node:buffer";globalThis.Buffer=yt;import{ExportResultCode as Ae}from"@opentelemetry/core";import{JsonLogsSerializer as Et,JsonTraceSerializer as wt}from"@opentelemetry/otlp-transformer";import{BackgroundDispatcher as Ie}from"@zuplo/runtime";function Lt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}n(Lt,"isPlainObject");function we(r){if(r==null)return"";if(Array.isArray(r)){for(let e=0;e<r.length;e+=1)r[e]=we(r[e]);return r}return Lt(r)&&H(r),r}n(we,"sanitizeValue");function H(r){Object.keys(r).forEach(e=>{r[e]=we(r[e])})}n(H,"sanitizeEmptyAttributes");var ue=Symbol("unwrap");function Oe(r){return r&&!!r[ue]}n(Oe,"isWrapped");function vt(r){return r!==null&&typeof r=="object"||typeof r=="function"}n(vt,"isProxyable");function U(r,e,t=!0){if(Oe(r)||!vt(r))return r;let o=Object.assign({},e);return o.get=(s,i,a)=>{if(i===ue)return r;if(e.get)return e.get(s,i,a);if(i==="bind")return()=>a;if(t)return de(s,i)},o.apply=(s,i,a)=>{if(e.apply)return e.apply(S(s),S(i),a)},new Proxy(r,o)}n(U,"wrap");function S(r){return r&&Oe(r)?r[ue]:r}n(S,"unwrap");function de(r,e,t){let o=S(r);t=S(t)||o;let s=Reflect.get(o,e);return typeof s=="function"?s.constructor.name==="RpcProperty"?(...i)=>o[e](...i):s.bind(t):s}n(de,"passthroughGet");var Fe={accept:"application/json","content-type":"application/json"},b=class{static{n(this,"OTLPSpanExporter")}headers;url;constructor(e){this.url=e.url,this.headers=Object.assign({},Fe,e.headers)}export(e,t){e.forEach(o=>{this.batcher.enqueue(o)}),t({code:Ae.SUCCESS})}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}dispatchFunction=n(async e=>{if(e.length===0)return;e.forEach(a=>{H(a.attributes)});let t=new TextDecoder,o=wt.serializeRequest(e),s=t.decode(o),i=await S(fetch)(this.url,{method:"POST",body:s,headers:this.headers});if(!i.ok)try{let a=await i.text();throw new Error(`Error exporting traces: ${i.status}:${a}`)}catch(a){throw new Error(`Error exporting traces ${a.message}`)}},"dispatchFunction");batcher=new Ie(this.dispatchFunction,{msDelay:10})},B=class{static{n(this,"OTLPLogExporter")}headers;url;batcher;constructor(e,t){this.url=e.url,this.headers=Object.assign({},Fe,e.headers),this.batcher=new Ie(this.dispatchFunction,{msDelay:t?.scheduledDelayMillis??10})}export(e,t){e.forEach(o=>{this.batcher.enqueue(o)}),t({code:Ae.SUCCESS})}shutdown(){return Promise.resolve()}dispatchFunction=n(async e=>{if(e.length===0)return;e.forEach(a=>{H(a.attributes)});let t=new TextDecoder,o=Et.serializeRequest(e),s=t.decode(o),i=await S(fetch)(this.url,{method:"POST",body:s,headers:this.headers});if(!i.ok)try{let a=await i.text();throw new Error(`Error exporting OTel logs: ${i.status}:${a}`)}catch(a){throw new Error(`Error exporting OTel logs: ${a.message}`)}},"dispatchFunction")};import{TelemetryPlugin as wr,trackFeature as Or}from"@zuplo/runtime";import{context as V,propagation as qe,SpanKind as Ke,SpanStatusCode as Mt,trace as Ht}from"@opentelemetry/api";import{context as Ve}from"@opentelemetry/api";import{W3CTraceContextPropagator as kt}from"@opentelemetry/core";var j=class{static{n(this,"DefaultLogProcessor")}exporter;constructor(e){this.exporter=e}forceFlush(){return Promise.resolve()}shutdown(){return Promise.resolve()}onEmit(e){this.exporter.export([e],t=>{})}};import{SpanStatusCode as Ot,TraceFlags as ke}from"@opentelemetry/api";import{ParentBasedSampler as Ne,TraceIdRatioBasedSampler as At}from"@opentelemetry/sdk-trace-base";import{SemanticAttributes as ge}from"@zuplo/runtime";function De(r){return e=>{let t=e.localRootSpan;return t.attributes[ge.SystemTrace]??t.attributes[ge.RouteSystem]??t.attributes[ge.RouteTrace]===!1?!1:r(e)}}n(De,"internalTailSampler");function Ge(r){return e=>r.reduce((t,o)=>t||o(e),!1)}n(Ge,"multiTailSampler");var Me=n(r=>(r.localRootSpan.spanContext().traceFlags&ke.SAMPLED)===ke.SAMPLED,"isHeadSampled"),He=n(r=>r.localRootSpan.status.code===Ot.ERROR,"isRootErrorSpan");function Ue(r){let e=new At(r.ratio);return typeof r.acceptRemote=="boolean"&&!r.acceptRemote?new Ne({root:e,remoteParentSampled:e,remoteParentNotSampled:e}):new Ne({root:e})}n(Ue,"createSampler");import{ExportResultCode as It}from"@opentelemetry/core";function Ft(){let r=T();return r||console.log("Could not find config for sampling, sending everything by default"),r?r.sampling.tailSampler:()=>!0}n(Ft,"getSampler");var me=class{static{n(this,"TraceState")}unexportedSpans=[];inprogressSpans=new Set;exporter;exportPromises=[];localRootSpan;traceDecision;isFlushed=!1;constructor(e){this.exporter=e}addSpan(e){let t=e;this.localRootSpan=this.localRootSpan||t,this.unexportedSpans.push(t),this.inprogressSpans.add(e.spanContext().spanId)}hasFinished(){return this.inprogressSpans.size===0&&this.isFlushed}async endSpan(e){this.inprogressSpans.delete(e.spanContext().spanId),this.inprogressSpans.size===0&&await this.flush()}sample(){if(this.traceDecision===void 0&&this.unexportedSpans.length>0){let e=Ft();this.traceDecision=e({traceId:this.localRootSpan.spanContext().traceId,localRootSpan:this.localRootSpan,spans:this.unexportedSpans})}this.unexportedSpans=this.traceDecision?this.unexportedSpans:[]}async flush(){if(this.unexportedSpans.length>0){let e=this.unexportedSpans.filter(t=>this.isSpanInProgress(t));for(let t of e)console.log(`Span ${t.spanContext().spanId} was not ended properly`),t.end();this.sample(),this.exportPromises.push(this.exportSpans([...this.unexportedSpans])),this.unexportedSpans=[]}this.exportPromises.length>0&&(await Promise.allSettled(this.exportPromises),this.exportPromises=[],this.isFlushed=!0)}isSpanInProgress(e){return this.inprogressSpans.has(e.spanContext().spanId)}async exportSpans(e){let t=T();if(!t){console.log("No config found for exporting spans, skipping export");return}let o=t.postProcessor(e);await scheduler.wait(1),await new Promise((i,a)=>{this.exporter.export(o,c=>{c.code===It.SUCCESS?i():(console.log(`exporting spans failed! ${c.error}`),a(c.error))})})}},_=class{constructor(e){this.exporter=e}exporter;static{n(this,"BatchTraceSpanProcessor")}traces={};getTraceState(e){let t=this.traces[e]||new me(this.exporter);return this.traces[e]=t,t}onStart(e,t){let o=e.spanContext().traceId;this.getTraceState(o).addSpan(e)}onEnd(e){let t=e.spanContext().traceId,o=this.getTraceState(t);o.endSpan(e).catch(s=>{console.log(s,"Failed to end span")}).finally(()=>{o.hasFinished()&&delete this.traces[t]})}async forceFlush(e){if(e)await this.getTraceState(e).flush(),delete this.traces[e];else{let t=Object.values(this.traces).map(o=>o.flush);await Promise.allSettled(t),this.traces={}}}async shutdown(){await this.forceFlush()}};function Be(r){return!!r.spanProcessors}n(Be,"isSpanProcessorConfig");function je(r){let e=!!r.spanProcessors,t=!!r.logProcessors;return e&&t}n(je,"isProcessorConfig");var ze=Symbol("Otel Tracing Configuration");function $e(r,e=Ve.active()){return e.setValue(ze,r)}n($e,"setConfig");function T(){return Ve.active().getValue(ze)||void 0}n(T,"getActiveConfig");function Nt(r){return!!r.shouldSample}n(Nt,"isSampler");function Dt(r){return!!r.exporter}n(Dt,"isTraceConfigExporter");function Gt(r){return!!r.logUrl&&!!r.traceUrl&&!!r.headers}n(Gt,"isTraceAndLogConfigExporter");function fe(r){let e=[],t=[];Dt(r)?e=[new _(new b(r.exporter))]:Gt(r)?(e=[new _(new b({url:r.traceUrl,headers:r.headers}))],t=[new j(new B({url:r.logUrl,headers:r.headers}))]):je(r)?(e=Array.isArray(r.spanProcessors)?r.spanProcessors:[r.spanProcessors],t=Array.isArray(r.logProcessors)?r.logProcessors:[r.logProcessors]):Be(r)&&(e=Array.isArray(r.spanProcessors)?r.spanProcessors:[r.spanProcessors]);let o=r.sampling?.headSampler||{ratio:1},s=Nt(o)?o:Ue(o);return{fetch:{includeTraceContext:r.fetch?.includeTraceContext??!0},handlers:{fetch:{acceptTraceContext:r.handlers?.fetch?.acceptTraceContext??!0}},postProcessor:r.postProcessor||(i=>i),sampling:{headSampler:s,tailSampler:De(r.sampling?.tailSampler??Ge([Me,He]))},service:r.service,resourceAttributes:r.resourceAttributes,spanProcessors:e,propagator:r.propagator||new kt,instrumentation:{instrumentGlobalFetch:r.instrumentation?.instrumentGlobalFetch??!0},logProcessors:t}}n(fe,"parseConfig");function Ze(r){let e={},t=r.headers;e["http.request.method"]=r.method.toUpperCase(),e["http.request.body.size"]=t.get("content-length"),e["user_agent.original"]=t.get("user-agent"),e["http.mime_type"]=t.get("content-type"),e["http.accepts"]=t.get("accept");let o=new URL(r.url);return e["url.full"]=`${o.protocol}//${o.host}${o.pathname}${o.search}`,e["server.address"]=o.host,e["url.scheme"]=o.protocol,e["url.path"]=o.pathname,e["url.query"]=o.search,e}n(Ze,"gatherRequestAttributes");function Ye(r){let e={};return e["http.response.status_code"]=r.status,r.headers.get("content-length")==null&&(e["http.response.body.size"]=r.headers.get("content-length")),e["http.mime_type"]=r.headers.get("content-type"),e}n(Ye,"gatherResponseAttributes");function Ut(r){return qe.extract(V.active(),r,{get(e,t){return e.get(t)||void 0},keys(e){return[...e.keys()]}})}n(Ut,"getParentContextFromHeaders");function Bt(r){let e=T();return e===void 0?V.active():(typeof e.handlers.fetch.acceptTraceContext=="function"?e.handlers.fetch.acceptTraceContext(r):e.handlers.fetch.acceptTraceContext??!0)?Ut(r.headers):V.active()}n(Bt,"getParentContextFromRequest");function We(r,e){let t=r;if(t.attributes["http.route"]){let o=e.method.toUpperCase();r.updateName(`${o} ${t.attributes["http.route"]}`)}}n(We,"updateSpanNameOnRoute");var Xe={getInitialSpanInfo:n(r=>{let e=Bt(r),t={"faas.trigger":"http","faas.invocation_id":r.headers.get("zp-rid")??void 0,"cf.ray_id":r.headers.get("cf-ray")??void 0};return Object.assign(t,Ze(r)),{name:`fetchHandler ${r.method.toUpperCase()}`,options:{attributes:t,kind:Ke.SERVER},context:e}},"getInitialSpanInfo"),getAttributesFromResult:n(r=>Ye(r),"getAttributesFromResult"),executionSuccess:We,executionFailed:We};function jt(r,e,t){return U(r,{apply:n((s,i,a)=>{let c=new Request(a[0],a[1]);if(!c.url.startsWith("http"))return Reflect.apply(s,i,a);let l=T();if(!l)return Reflect.apply(s,i,[c]);let u=e(l),m=Ht.getTracer("fetcher"),h={kind:Ke.CLIENT,attributes:t},d=new URL(c.url).host,w=c.method.toUpperCase(),M=typeof t?.name=="string"?t?.name:`${w}: ${d}`;return m.startActiveSpan(M,h,async p=>{try{((typeof u.includeTraceContext=="function"?u.includeTraceContext(c):u.includeTraceContext)??!0)&&qe.inject(V.active(),c.headers,{set:n((ce,pe,P)=>ce.set(pe,typeof P=="string"?P:String(P)),"set")}),p.setAttributes(Ze(c));let ae=await Reflect.apply(s,i,[c]);return p.setAttributes(Ye(ae)),ae}catch(x){throw p.recordException(x),p.setStatus({code:Mt.ERROR}),x}finally{p.end()}})},"apply")},!0)}n(jt,"instrumentClientFetch");function Je(){globalThis.fetch=jt(globalThis.fetch,r=>r.fetch)}n(Je,"instrumentGlobalFetch");import{context as St,context as hr,propagation as Tr,SpanStatusCode as xr,trace as Rt}from"@opentelemetry/api";import{resourceFromAttributes as ve}from"@opentelemetry/resources";import{ATTR_CLOUD_ACCOUNT_ID as Sr,ATTR_CLOUD_PLATFORM as Rr,ATTR_CLOUD_PROVIDER as Pr,ATTR_SERVICE_NAME as br,ATTR_SERVICE_NAMESPACE as _r,ATTR_SERVICE_VERSION as Cr,ATTR_TELEMETRY_SDK_NAME as yr}from"@opentelemetry/semantic-conventions/incubating";import{SemanticAttributes as ie}from"@zuplo/runtime";import{AsyncLocalStorage as Vt}from"node:async_hooks";import{EventEmitter as zt}from"node:events";import{ROOT_CONTEXT as $t}from"@opentelemetry/api";var Wt=["addListener","on","once","prependListener","prependOnceListener"],he=class{static{n(this,"AbstractAsyncHooksContextManager")}bind(e,t){return t instanceof zt?this._bindEventEmitter(e,t):typeof t=="function"?this._bindFunction(e,t):t}_bindFunction(e,t){let o=this,s=n(function(...i){return o.with(e,()=>t.apply(this,i))},"contextWrapper");return Object.defineProperty(s,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),s}_bindEventEmitter(e,t){return this._getPatchMap(t)!==void 0||(this._createPatchMap(t),Wt.forEach(s=>{t[s]!==void 0&&(t[s]=this._patchAddListener(t,t[s],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 o=this;return function(s,i){let a=o._getPatchMap(e)?.[s];if(a===void 0)return t.call(this,s,i);let c=a.get(i);return t.call(this,s,c||i)}}_patchRemoveAllListeners(e,t){let o=this;return function(s){let i=o._getPatchMap(e);return i!==void 0&&(arguments.length===0?o._createPatchMap(e):i[s]!==void 0&&delete i[s]),t.apply(this,arguments)}}_patchAddListener(e,t,o){let s=this;return function(i,a){if(s._wrapped)return t.call(this,i,a);let c=s._getPatchMap(e);c===void 0&&(c=s._createPatchMap(e));let l=c[i];l===void 0&&(l=new WeakMap,c[i]=l);let u=s.bind(o,a);l.set(a,u),s._wrapped=!0;try{return t.call(this,i,u)}finally{s._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},z=class extends he{static{n(this,"AsyncLocalStorageContextManager")}_asyncLocalStorage;constructor(){super(),this._asyncLocalStorage=new Vt}active(){return this._asyncLocalStorage.getStore()??$t}with(e,t,o,...s){let i=o==null?t:t.bind(o);return this._asyncLocalStorage.run(e,i,...s)}enable(){return this}disable(){return this._asyncLocalStorage.disable(),this}};import{trace as Sn}from"@opentelemetry/api";import{context as Se,SpanKind as tr,TraceFlags as ot,trace as W}from"@opentelemetry/api";import{sanitizeAttributes as nt}from"@opentelemetry/core";import{RandomIdGenerator as rr,SamplingDecision as or}from"@opentelemetry/sdk-trace-base";import{SpanKind as qt,SpanStatusCode as Kt}from"@opentelemetry/api";import{hrTimeDuration as Zt,isAttributeValue as Yt,isTimeInput as Xt,sanitizeAttributes as Qe}from"@opentelemetry/core";import{ATTR_EXCEPTION_MESSAGE as et,ATTR_EXCEPTION_STACKTRACE as Jt,ATTR_EXCEPTION_TYPE as tt}from"@opentelemetry/semantic-conventions";function Qt(r){let e={};return typeof r=="string"?e[et]=r:(r.code?e[tt]=r.code.toString():r.name&&(e[tt]=r.name),r.message&&(e[et]=r.message),r.stack&&(e[Jt]=r.stack)),e}n(Qt,"transformExceptionAttributes");function Te(r){return[Math.trunc(r/1e3),r%1e3*1e6]}n(Te,"millisToHr");function xe(r){let e=Date.now();if(r){if(r instanceof Date)return Te(r.getTime());if(typeof r=="number")return Te(r);if(Array.isArray(r))return r}else return Te(e);let t=r;throw new Error(`unreachable value: ${JSON.stringify(t)}`)}n(xe,"getHrTime");function er(r){return typeof r=="string"&&r.length>0}n(er,"isAttributeKey");var $=class{static{n(this,"SpanImpl")}name;_spanContext;onEnd;parentSpanId;parentSpanContext;kind;attributes;status={code:Kt.UNSET};endTime=[0,0];_duration=[0,0];startTime;events=[];links;resource;instrumentationScope=rt;_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||qt.INTERNAL,this.attributes=Qe(e.attributes),this.startTime=xe(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 er(e)&&Yt(t)&&(this.attributes[e]=t),this}setAttributes(e){for(let[t,o]of Object.entries(e))this.setAttribute(t,o);return this}addEvent(e,t,o){Xt(t)&&(o=t,t=void 0);let s=Qe(t),i=xe(o);return this.events.push({name:e,attributes:s,time:i}),this}setStatus(e){return this.status=e,this}updateName(e){return this.name=e,this}end(e){this._ended||(this._ended=!0,this.endTime=xe(e),this._duration=Zt(this.startTime,this.endTime),this.onEnd(this))}isRecording(){return!this._ended}recordException(e,t){let o=Qt(e);this.addEvent("exception",o,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 it=new rr,st;function nr(r,e){return(r>>e-1&1)*e}n(nr,"getFlagAt");var R=class{static{n(this,"WorkerTracer")}spanProcessors;resource;constructor(e,t){this.spanProcessors=e,this.resource=t}async forceFlush(e){let t=this.spanProcessors.map(async o=>{await o.forceFlush(e)});await Promise.allSettled(t)}addToResource(e){this.resource.merge(e)}startSpan(e,t={},o=Se.active()){t.root&&(o=W.deleteSpan(o));let s=T();if(!s)throw new Error("Config is undefined. This is a bug in the instrumentation logic");let i=W.getSpan(o)?.spanContext(),{traceId:a,randomTraceFlag:c}=sr(i),l=t.kind||tr.INTERNAL,u=nt(t.attributes),h=s.sampling.headSampler.shouldSample(o,a,e,l,u,[]),{decision:d,traceState:w,attributes:M}=h,g=Object.assign({},t.attributes,M,st);st={};let p=it.generateSpanId(),x=i?.spanId,ce=(d===or.RECORD_AND_SAMPLED?ot.SAMPLED:ot.NONE)+c,pe={traceId:a,spanId:p,traceFlags:ce,traceState:w},P=new $({attributes:nt(g),name:e,onEnd:n(le=>{this.spanProcessors.forEach(_t=>{_t.onEnd(le)})},"onEnd"),resource:this.resource,spanContext:pe,parentSpanContext:i,parentSpanId:x,spanKind:l,startTime:t.startTime});return this.spanProcessors.forEach(le=>{le.onStart(P,o)}),P}startActiveSpan(e,...t){let o=t.length>1?t[0]:void 0,s=t.length>2?t[1]:Se.active(),i=t[t.length-1],a=this.startSpan(e,o,s),c=W.setSpan(s,a);return Se.with(c,i,void 0,a)}};function sr(r){if(r&&W.isSpanContextValid(r)){let{traceId:e,traceFlags:t}=r;return{traceId:e,randomTraceFlag:nr(t,2)}}else return{traceId:it.generateTraceId(),randomTraceFlag:2}}n(sr,"getTraceInfo");var Re=class{static{n(this,"PromiseTracker")}_outstandingPromises=[];get outstandingPromiseCount(){return this._outstandingPromises.length}track(e){this._outstandingPromises.push(e)}async wait(){await ar(this._outstandingPromises)}};function ir(r,e,t){return U(r,{apply(s,i,a){return t.track(a[0]),Reflect.apply(s,e,a)}})}n(ir,"createWaitUntil");function at(r){let e=new Re;return{event:new Proxy(r,{get(o,s){if(s==="waitUntil"){let i=Reflect.get(o,s);return ir(i,r,e)}else return de(o,s)}}),tracker:e}}n(at,"proxyExecutionContext");async function ar(r){let e;do e=await Promise.allSettled(r);while(e.length!==r.length);return e}n(ar,"allSettledMutable");var O=class{static{n(this,"NoopLogger")}emit(e){}},ct=new O;var Pe=class{static{n(this,"NoopLoggerProvider")}getLogger(e,t,o){return new O}},q=new Pe;var K=class{static{n(this,"ProxyLogger")}constructor(e,t,o,s){this._provider=e,this.name=t,this.version=o,this.options=s}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):ct}};var A=class{static{n(this,"ProxyLoggerProvider")}getLogger(e,t,o){var s;return(s=this.getDelegateLogger(e,t,o))!==null&&s!==void 0?s:new K(this,e,t,o)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:q}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,o){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getLogger(e,t,o)}};var be=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};var I=Symbol.for("io.opentelemetry.js.api.logs"),C=be;function pt(r,e,t){return o=>o===r?e:t}n(pt,"makeGetter");var _e=1;var Z=class r{static{n(this,"LogsAPI")}constructor(){this._proxyLoggerProvider=new A}static getInstance(){return this._instance||(this._instance=new r),this._instance}setGlobalLoggerProvider(e){return C[I]?this.getLoggerProvider():(C[I]=pt(_e,e,q),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return(t=(e=C[I])===null||e===void 0?void 0:e.call(C,_e))!==null&&t!==void 0?t:this._proxyLoggerProvider}getLogger(e,t,o){return this.getLoggerProvider().getLogger(e,t,o)}disable(){delete C[I],this._proxyLoggerProvider=new A}};var lt=Z.getInstance();import{diag as D}from"@opentelemetry/api";var y=class{static{n(this,"NoopLogger")}emit(e){}},F=new y;var Ce=class{static{n(this,"NoopLoggerProvider")}getLogger(e,t,o){return new y}},Y=new Ce;var X=class{static{n(this,"ProxyLogger")}constructor(e,t,o,s){this._provider=e,this.name=t,this.version=o,this.options=s}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):F}};var k=class{static{n(this,"ProxyLoggerProvider")}getLogger(e,t,o){var s;return(s=this.getDelegateLogger(e,t,o))!==null&&s!==void 0?s:new X(this,e,t,o)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Y}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,o){var s;return(s=this._delegate)===null||s===void 0?void 0:s.getLogger(e,t,o)}};var ye=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{};var N=Symbol.for("io.opentelemetry.js.api.logs"),L=ye;function ut(r,e,t){return o=>o===r?e:t}n(ut,"makeGetter");var Le=1;var J=class r{static{n(this,"LogsAPI")}constructor(){this._proxyLoggerProvider=new k}static getInstance(){return this._instance||(this._instance=new r),this._instance}setGlobalLoggerProvider(e){return L[N]?this.getLoggerProvider():(L[N]=ut(Le,e,Y),this._proxyLoggerProvider.setDelegate(e),e)}getLoggerProvider(){var e,t;return(t=(e=L[N])===null||e===void 0?void 0:e.call(L,Le))!==null&&t!==void 0?t:this._proxyLoggerProvider}getLogger(e,t,o){return this.getLoggerProvider().getLogger(e,t,o)}disable(){delete L[N],this._proxyLoggerProvider=new k}};var Ss=J.getInstance();import{defaultResource as ur}from"@opentelemetry/resources";import{BindOnceFuture as dr,merge as gr}from"@opentelemetry/core";import{context as pr}from"@opentelemetry/api";import{diag as cr}from"@opentelemetry/api";import*as f from"@opentelemetry/api";import{timeInputToHrTime as dt,isAttributeValue as gt}from"@opentelemetry/core";var Q=class{static{n(this,"LogRecord")}hrTime;hrTimeObserved;spanContext;resource;instrumentationScope;attributes={};_severityText;_severityNumber;_body;totalAttributesCount=0;_isReadonly=!1;_logRecordLimits;set severityText(e){this._isLogRecordReadonly()||(this._severityText=e)}get severityText(){return this._severityText}set severityNumber(e){this._isLogRecordReadonly()||(this._severityNumber=e)}get severityNumber(){return this._severityNumber}set body(e){this._isLogRecordReadonly()||(this._body=e)}get body(){return this._body}get droppedAttributesCount(){return this.totalAttributesCount-Object.keys(this.attributes).length}constructor(e,t,o){let{timestamp:s,observedTimestamp:i,severityNumber:a,severityText:c,body:l,attributes:u={},context:m}=o,h=Date.now();if(this.hrTime=dt(s??h),this.hrTimeObserved=dt(i??h),m){let d=f.trace.getSpanContext(m);d&&f.isSpanContextValid(d)&&(this.spanContext=d)}this.severityNumber=a,this.severityText=c,this.body=l,this.resource=e.resource,this.instrumentationScope=t,this._logRecordLimits=e.logRecordLimits,this.setAttributes(u)}setAttribute(e,t){return this._isLogRecordReadonly()?this:t===null?this:e.length===0?(f.diag.warn(`Invalid attribute key: ${e}`),this):!gt(t)&&!(typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length>0)?(f.diag.warn(`Invalid attribute value set for key: ${e}`),this):(this.totalAttributesCount+=1,Object.keys(this.attributes).length>=this._logRecordLimits.attributeCountLimit&&!Object.prototype.hasOwnProperty.call(this.attributes,e)?(this.droppedAttributesCount===1&&f.diag.warn("Dropping extra attributes."),this):(gt(t)?this.attributes[e]=this._truncateToSize(t):this.attributes[e]=t,this))}setAttributes(e){for(let[t,o]of Object.entries(e))this.setAttribute(t,o);return this}setBody(e){return this.body=e,this}setSeverityNumber(e){return this.severityNumber=e,this}setSeverityText(e){return this.severityText=e,this}_makeReadonly(){this._isReadonly=!0}_truncateToSize(e){let t=this._logRecordLimits.attributeValueLengthLimit;return t<=0?(f.diag.warn(`Attribute value limit must be positive, got ${t}`),e):typeof e=="string"?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(o=>typeof o=="string"?this._truncateToLimitUtil(o,t):o):e}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_isLogRecordReadonly(){return this._isReadonly&&cr.warn("Can not execute the operation on emitted log record"),this._isReadonly}};var ee=class{static{n(this,"Logger")}instrumentationScope;_sharedState;constructor(e,t){this.instrumentationScope=e,this._sharedState=t}emit(e){let t=e.context||pr.active(),o=new Q(this._sharedState,this.instrumentationScope,{context:t,...e});this._sharedState.activeProcessor.onEmit(o,t),o._makeReadonly()}};import{getNumberFromEnv as v}from"@opentelemetry/core";function mt(){return{forceFlushTimeoutMillis:3e4,logRecordLimits:{attributeValueLengthLimit:v("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0,attributeCountLimit:v("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??128},includeTraceContext:!0}}n(mt,"loadDefaultConfig");function ft(r){return{attributeCountLimit:r.attributeCountLimit??v("OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT")??v("OTEL_ATTRIBUTE_COUNT_LIMIT")??128,attributeValueLengthLimit:r.attributeValueLengthLimit??v("OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT")??v("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT")??1/0}}n(ft,"reconfigureLimits");var te=class{static{n(this,"NoopLogRecordProcessor")}forceFlush(){return Promise.resolve()}onEmit(e,t){}shutdown(){return Promise.resolve()}};import{callWithTimeout as lr}from"@opentelemetry/core";var E=class{static{n(this,"MultiLogRecordProcessor")}processors;forceFlushTimeoutMillis;constructor(e,t){this.processors=e,this.forceFlushTimeoutMillis=t}async forceFlush(){let e=this.forceFlushTimeoutMillis;await Promise.all(this.processors.map(t=>lr(t.forceFlush(),e)))}onEmit(e,t){this.processors.forEach(o=>o.onEmit(e,t))}async shutdown(){await Promise.all(this.processors.map(e=>e.shutdown()))}};var re=class{static{n(this,"LoggerProviderSharedState")}resource;forceFlushTimeoutMillis;logRecordLimits;processors;loggers=new Map;activeProcessor;registeredLogRecordProcessors=[];constructor(e,t,o,s){this.resource=e,this.forceFlushTimeoutMillis=t,this.logRecordLimits=o,this.processors=s,s.length>0?(this.registeredLogRecordProcessors=s,this.activeProcessor=new E(this.registeredLogRecordProcessors,this.forceFlushTimeoutMillis)):this.activeProcessor=new te}};var mr="unknown",G=class{static{n(this,"LoggerProvider")}_shutdownOnce;_sharedState;constructor(e={}){let t=gr({},mt(),e),o=e.resource??ur();this._sharedState=new re(o,t.forceFlushTimeoutMillis,ft(t.logRecordLimits),e?.processors??[]),this._shutdownOnce=new dr(this._shutdown,this)}getLogger(e,t,o){if(this._shutdownOnce.isCalled)return D.warn("A shutdown LoggerProvider cannot provide a Logger"),F;e||D.warn("Logger requested without instrumentation scope name.");let s=e||mr,i=`${s}@${t||""}:${o?.schemaUrl||""}`;return this._sharedState.loggers.has(i)||this._sharedState.loggers.set(i,new ee({name:s,version:t,schemaUrl:o?.schemaUrl},this._sharedState)),this._sharedState.loggers.get(i)}addLogRecordProcessor(e){this._sharedState.registeredLogRecordProcessors.length===0&&this._sharedState.activeProcessor.shutdown().catch(t=>D.error("Error while trying to shutdown current log record processor",t)),this._sharedState.registeredLogRecordProcessors.push(e),this._sharedState.activeProcessor=new E(this._sharedState.registeredLogRecordProcessors,this._sharedState.forceFlushTimeoutMillis)}forceFlush(){return this._shutdownOnce.isCalled?(D.warn("invalid attempt to force flush after LoggerProvider shutdown"),this._shutdownOnce.promise):this._sharedState.activeProcessor.forceFlush()}shutdown(){return this._shutdownOnce.isCalled?(D.warn("shutdown may only be called once per LoggerProvider"),this._shutdownOnce.promise):this._shutdownOnce.call()}_shutdown(){return this._sharedState.activeProcessor.shutdown()}};var oe=class{static{n(this,"ZuploOtelLogger")}baseLogger;constructor(e){this.baseLogger=e}emit(e){this.baseLogger.emit(e)}};var ne=class extends G{static{n(this,"ZuploLoggerProvider")}getLogger(e,t,o){let s=super.getLogger(e,t,o);return new oe(s)}register(){lt.setGlobalLoggerProvider(this)}};import{trace as fr}from"@opentelemetry/api";var se=class{static{n(this,"ZuploTracerProvider")}spanProcessors;resource;tracers={};constructor(e,t){this.spanProcessors=e,this.resource=t}getTracer(e,t,o){let s=`${e}@${t||""}:${o?.schemaUrl||""}`;return this.tracers[s]||(this.tracers[s]=new R(this.spanProcessors,this.resource)),this.tracers[s]}register(){fr.setGlobalTracerProvider(this)}};var Lr=n((r,e)=>{let t={[Pr]:"zuplo",[Rr]:"zuplo-api",[Sr]:r.accountName,"cloud.project.id":r.projectName,"cloud.resource_id":r.deploymentName,"cloud.instance_id":r.instanceId,"deployment.environment.name":r.environmentStage,[yr]:"@zuplo/otel",[ie.ZuploBuildId]:r.buildId,[ie.ZuploBuildVersion]:r.zuploVersion,[ie.ZuploBuildCompatibilityDate]:r.compatibilityDate,[ie.ZuploEnvironmentType]:r.environmentType},o=ve({[br]:e.service.name,[_r]:e.service.namespace,[Cr]:e.service.version}),s=ve(t).merge(o);return e.resourceAttributes?s.merge(ve(e.resourceAttributes)):s},"createResource"),ht=!1;function Tt(r,e){if(!ht){e.instrumentation.instrumentGlobalFetch&&Je(),Tr.setGlobalPropagator(e.propagator);let t=Lr(r,e);new se(e.spanProcessors,t).register(),e.logProcessors.length>0&&new ne({resource:t,processors:e.logProcessors}).register(),hr.setGlobalContextManager(new z),ht=!0}}n(Tt,"init");function Pt(r,e){return typeof e=="function"?t=>{let o=fe(e(t));return Tt(r,o),o}:()=>{let t=fe(e);return Tt(r,t),t}}n(Pt,"createInitializer");async function vr(r,e){let t=Rt.getTracer("export");t instanceof R?(await scheduler.wait(1),await e?.wait(),await t.forceFlush(r)):console.error("The global tracer is not of type WorkerTracer and can not export spans")}n(vr,"exportSpans");var xt=!0;function Er(r){return(e,t)=>{let[o,s]=t,{event:i,tracker:a}=at(s),c=r.instrumentTrigger?r.instrumentTrigger(o):o,l=Rt.getTracer("handler"),{name:u,options:m,context:h}=r.getInitialSpanInfo(o),d=m.attributes||{};d["faas.coldstart"]=xt,m.attributes=d,xt=!1;let w=h||St.active();return l.startActiveSpan(u,m,w,async g=>{try{let p=await e(c,i);if(r.getAttributesFromResult){let x=r.getAttributesFromResult(p);g.setAttributes(x)}return r.executionSuccess&&r.executionSuccess(g,o,p),p}catch(p){throw g.recordException(p),g.setStatus({code:xr.ERROR}),r.executionFailed&&r.executionFailed(g,o,p),p}finally{g.end(),s.waitUntil(vr(g.spanContext().traceId,a))}})}}n(Er,"createHandlerFlowFn");function bt(r,e,t){return(o,s)=>{let i=e(o),a=$e(i),c=Er(t);return St.with(a,c,o,r,[o,s])}}n(bt,"createHandlerProxy");var rt={name:"@zuplo/otel"};var Ee=class extends wr{static{n(this,"OpenTelemetryPlugin")}config;constructor(e){super(),Or("opentelemetry"),this.config=e}instrument(e){let t=Pt(e,this.config);return{requestHandlerProxy:n(s=>bt(s,t,Xe),"requestHandlerProxy")}}};export{b as a,_ as b,Ee as c};
//# sourceMappingURL=chunk-U3KEMFL3.js.map
