@vercel/otel 2.0.0-2cf7cf1c-20250926110730 → 2.0.1
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.
- package/dist/edge/index.js +1 -1
- package/dist/edge/index.js.map +2 -2
- package/dist/node/index.js +1 -1
- package/dist/node/index.js.map +2 -2
- package/package.json +1 -1
package/dist/edge/index.js
CHANGED
|
@@ -13,5 +13,5 @@ var Zl=Object.create;var ke=Object.defineProperty;var tA=Object.getOwnPropertyDe
|
|
|
13
13
|
To resolve the conflict:`,Io(s,t))),n=o):c.diag.warn("A view or instrument with the name ",t.name,` has already been registered and is incompatible with another registered view.
|
|
14
14
|
`,`Details:
|
|
15
15
|
`,Lo(s,t),`To resolve the conflict:
|
|
16
|
-
`,Io(s,t))}return n}};var en=class{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,n,o){this._backingStorages.forEach(s=>{s.record(t,e,n,o)})}};d();d();var rn=class{_instrumentName;_valueType;_buffer=new H;constructor(t,e){this._instrumentName=t,this._valueType=e}observe(t,e={}){if(typeof t!="number"){c.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}this._valueType===c.ValueType.INT&&!Number.isInteger(t)&&(c.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),t=Math.trunc(t),!Number.isInteger(t))||this._buffer.set(e,t)}},nn=class{_buffer=new Map;observe(t,e,n={}){if(!be(t))return;let o=this._buffer.get(t);if(o==null&&(o=new H,this._buffer.set(t,o)),typeof e!="number"){c.diag.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}t._descriptor.valueType===c.ValueType.INT&&!Number.isInteger(e)&&(c.diag.warn(`INT value type cannot accept a floating-point value for ${t._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||o.set(n,e)}};var on=class{_callbacks=[];_batchCallbacks=[];addCallback(t,e){this._findCallback(t,e)>=0||this._callbacks.push({callback:t,instrument:e})}removeCallback(t,e){let n=this._findCallback(t,e);n<0||this._callbacks.splice(n,1)}addBatchCallback(t,e){let n=new Set(e.filter(be));if(n.size===0){c.diag.error("BatchObservableCallback is not associated with valid instruments",e);return}this._findBatchCallback(t,n)>=0||this._batchCallbacks.push({callback:t,instruments:n})}removeBatchCallback(t,e){let n=new Set(e.filter(be)),o=this._findBatchCallback(t,n);o<0||this._batchCallbacks.splice(o,1)}async observe(t,e){let n=this._observeCallbacks(t,e),o=this._observeBatchCallbacks(t,e);return(await zS([...n,...o])).filter(QS).map(a=>a.reason)}_observeCallbacks(t,e){return this._callbacks.map(async({callback:n,instrument:o})=>{let s=new rn(o._descriptor.name,o._descriptor.valueType),i=Promise.resolve(n(s));e!=null&&(i=uo(i,e)),await i,o._metricStorages.forEach(a=>{a.record(s._buffer,t)})})}_observeBatchCallbacks(t,e){return this._batchCallbacks.map(async({callback:n,instruments:o})=>{let s=new nn,i=Promise.resolve(n(s));e!=null&&(i=uo(i,e)),await i,o.forEach(a=>{let _=s._buffer.get(a);_!=null&&a._metricStorages.forEach(E=>{E.record(_,t)})})})}_findCallback(t,e){return this._callbacks.findIndex(n=>n.callback===t&&n.instrument===e)}_findBatchCallback(t,e){return this._batchCallbacks.findIndex(n=>n.callback===t&&JS(n.instruments,e))}};var sn=class extends te{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,n,o,s){super(t),this._attributesProcessor=n,this._aggregationCardinalityLimit=s,this._deltaMetricStorage=new ee(e,this._aggregationCardinalityLimit),this._temporalMetricStorage=new re(e,o)}record(t,e,n,o){e=this._attributesProcessor.process(e,n),this._deltaMetricStorage.record(t,e,n,o)}collect(t,e){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,n,e)}};var xo=class{process(t,e){return t}},Do=class{_processors;constructor(t){this._processors=t}process(t,e){let n=t;for(let o of this._processors)n=o.process(n,e);return n}};function an(){return oI}function Ep(r){return new Do(r)}var oI=new xo;var cn=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new tn;observableRegistry=new on;meter;constructor(t,e){this._meterProviderSharedState=t,this._instrumentationScope=e,this.meter=new Jr(this)}registerMetricStorage(t){let e=this._registerMetricStorage(t,sn);return e.length===1?e[0]:new en(e)}registerAsyncMetricStorage(t){return this._registerMetricStorage(t,Zr)}async collect(t,e,n){let o=await this.observableRegistry.observe(e,n?.timeoutMillis),s=this.metricStorageRegistry.getStorages(t);if(s.length===0)return null;let i=s.map(a=>a.collect(t,e)).filter($S);return i.length===0?{errors:o}:{scopeMetrics:{scope:this._instrumentationScope,metrics:i},errors:o}}_registerMetricStorage(t,e){let o=this._meterProviderSharedState.viewRegistry.findViews(t,this._instrumentationScope).map(s=>{let i=ap(s,t),a=this.metricStorageRegistry.findOrUpdateCompatibleStorage(i);if(a!=null)return a;let _=s.aggregation.createAggregator(i),E=new e(i,_,s.attributesProcessor,this._meterProviderSharedState.metricCollectors,s.aggregationCardinalityLimit);return this.metricStorageRegistry.register(E),E});if(o.length===0){let i=this._meterProviderSharedState.selectAggregations(t.type).map(([a,_])=>{let E=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(a,t);if(E!=null)return E;let T=_.createAggregator(t),l=a.selectCardinalityLimit(t.type),A=new e(t,T,an(),[a],l);return this.metricStorageRegistry.registerForCollector(a,A),A});o=o.concat(i)}return o}};var _n=class{resource;viewRegistry=new Kr;metricCollectors=[];meterSharedStates=new Map;constructor(t){this.resource=t}getMeterSharedState(t){let e=XS(t),n=this.meterSharedStates.get(e);return n==null&&(n=new cn(this,t),this.meterSharedStates.set(e,n)),n}selectAggregations(t){let e=[];for(let n of this.metricCollectors)e.push([n,kr(n.selectAggregation(t))]);return e}};var up=O(P()),En=class{_sharedState;_metricReader;constructor(t,e){this._sharedState=t,this._metricReader=e}async collect(t){let e=(0,up.millisToHrTime)(Date.now()),n=[],o=[],s=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,e,t);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&o.push(...a.errors)});return await Promise.all(s),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}}async forceFlush(t){await this._metricReader.forceFlush(t)}async shutdown(t){await this._metricReader.shutdown(t)}selectAggregationTemporality(t){return this._metricReader.selectAggregationTemporality(t)}selectAggregation(t){return this._metricReader.selectAggregation(t)}selectCardinalityLimit(t){return this._metricReader.selectCardinalityLimit?.(t)??2e3}};var sI=/[\^$\\.+?()[\]{}|]/g,ne=class r{_matchAll;_regexp;constructor(t){t==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(t)))}match(t){return this._matchAll?!0:this._regexp.test(t)}static escapePattern(t){return`^${t.replace(sI,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}},gt=class{_matchAll;_pattern;constructor(t){this._matchAll=t===void 0,this._pattern=t}match(t){return!!(this._matchAll||t===this._pattern)}};var un=class{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new ne(t?.name??"*"),this._type=t?.type,this._unitFilter=new gt(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}};var Tn=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new gt(t?.name),this._versionFilter=new gt(t?.version),this._schemaUrlFilter=new gt(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}};function iI(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}function aI(r){if(iI(r))throw new Error("Cannot create view with no selector arguments supplied");if(r.name!=null&&(r?.instrumentName==null||ne.hasWildcard(r.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}var Sn=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){aI(t),t.attributesProcessors!=null?this.attributesProcessor=Ep(t.attributesProcessors):this.attributesProcessor=an(),this.name=t.name,this.description=t.description,this.aggregation=kr(t.aggregation??{type:_t.DEFAULT}),this.instrumentSelector=new un({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit}),this.meterSelector=new Tn({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl}),this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}};var ye=class{_sharedState;_shutdown=!1;constructor(t){if(this._sharedState=new _n(t?.resource??Ut()),t?.views!=null&&t.views.length>0)for(let e of t.views)this._sharedState.viewRegistry.addView(new Sn(e));if(t?.readers!=null&&t.readers.length>0)for(let e of t.readers){let n=new En(this._sharedState,e);e.setMetricProducer(n),this._sharedState.metricCollectors.push(n)}}getMeter(t,e="",n={}){return this._shutdown?(c.diag.warn("A shutdown MeterProvider cannot provide a Meter"),(0,c.createNoopMeter)()):this._sharedState.getMeterSharedState({name:t,version:e,schemaUrl:n.schemaUrl}).meter}async shutdown(t){if(this._shutdown){c.diag.warn("shutdown may only be called once per MeterProvider");return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(e=>e.shutdown(t)))}async forceFlush(t){if(this._shutdown){c.diag.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map(e=>e.forceFlush(t)))}};var zl=O(lp(),1),Ct=O(P(),1);var Ap="http.method",dp="http.url",dn="http.host",mp="http.scheme",Bo="http.status_code",fp="http.user_agent",wo="http.response_content_length_uncompressed",hp="net.peer.port",Rp="net.peer.name";var Op="service.name",gp="service.version";d();var mI=Symbol.for("@vercel/request-context");function ut(){return globalThis[mI]?.get()}function mn(r){return Object.fromEntries(Object.entries(r).filter(([t,e])=>e!==void 0))}function Np(r){return r?r.split("::").at(-1):void 0}function Mp(r=ut(),t){if(!r)return;let e=t?hI(t,r.headers):void 0;return mn({[dn]:r.headers.host,[fp]:r.headers["user-agent"],"http.referer":r.headers.referer,"vercel.request_id":Np(r.headers["x-vercel-id"]),"vercel.matched_path":r.headers["x-matched-path"],"vercel.edge_region":process.env.VERCEL_REGION,...e})}var fI={keys(r){return[]},get(r,t){return r[t.toLocaleLowerCase()]}};function hI(r,t){if(typeof r=="function")return r(t,fI);let e={};for(let[n,o]of Object.entries(r)){let s=t[o.toLocaleLowerCase()];s!==void 0&&(e[n]=s)}return e}d();function ie(r){return(r&c.TraceFlags.SAMPLED)!==0}var fn=class{constructor(t,e){this.processors=t;this.attributesFromHeaders=e;this.rootSpanIds=new Map;this.waitSpanEnd=new Map}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush().catch(e=>{c.diag.error("@vercel/otel: forceFlush failed:",e)}))).then(()=>{})}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown().catch(()=>{}))).then(()=>{})}onStart(t,e){let{traceId:n,spanId:o,traceFlags:s}=t.spanContext(),i=!t.parentSpanContext?.spanId||!this.rootSpanIds.has(n);if(i?this.rootSpanIds.set(n,{rootSpanId:o,open:[]}):this.rootSpanIds.get(n)?.open.push(t),i&&ie(s)){let a=ut(),_=Mp(a,this.attributesFromHeaders);_&&t.setAttributes(_),a&&a.waitUntil(async()=>{if(this.rootSpanIds.has(n)){let E=new Promise(l=>{this.waitSpanEnd.set(n,l)}),T;await Promise.race([E,new Promise(l=>{T=setTimeout(()=>{this.waitSpanEnd.delete(n),l(void 0)},50)})]),T&&clearTimeout(T)}return this.forceFlush()})}for(let a of this.processors)a.onStart(t,e)}onEnd(t){let{traceId:e,spanId:n,traceFlags:o}=t.spanContext(),s=ie(o),i=this.rootSpanIds.get(e),a=i?.rootSpanId===n;if(s){let _=OI(t);_&&Object.assign(t.attributes,_)}if(a){if(this.rootSpanIds.delete(e),i.open.length>0){for(let _ of i.open)if(!_.ended&&_.spanContext().spanId!==n)try{_.end()}catch(E){c.diag.error("@vercel/otel: onEnd failed:",E)}}}else if(i)for(let _=0;_<i.open.length;_++)i.open[_]?.spanContext().spanId===n&&i.open.splice(_,1);for(let _ of this.processors)_.onEnd(t);if(a){let _=this.waitSpanEnd.get(e);_&&(this.waitSpanEnd.delete(e),_())}}},RI={[c.SpanKind.INTERNAL]:"internal",[c.SpanKind.SERVER]:"server",[c.SpanKind.CLIENT]:"client",[c.SpanKind.PRODUCER]:"producer",[c.SpanKind.CONSUMER]:"consumer"};function OI(r){let{kind:t,attributes:e}=r,{"operation.name":n,"resource.name":o,"span.type":s,"next.span_type":i,"http.method":a,"http.route":_}=e;if(n)return;let E=o??(a&&typeof a=="string"&&_&&typeof _=="string"?`${a} ${_}`:_);if(r.kind===c.SpanKind.SERVER&&a&&_&&typeof a=="string"&&typeof _=="string")return{"operation.name":"web.request","resource.name":E};let T=r.instrumentationScope.name,l=i??s;if(l&&typeof l=="string"){let A=Pp(T,l);return _?{"operation.name":A,"resource.name":E}:{"operation.name":A}}return{"operation.name":Pp(T,t===c.SpanKind.INTERNAL?"":RI[t])}}function Pp(r,t){if(!r)return t;let e=r.replace(/[ @./]/g,"_");return e.startsWith("_")&&(e=e.slice(1)),t?`${e}.${t}`:e}var Gp=O(Wo(),1);d();var ae=class{constructor(t={}){this._shutdownOnce={isCalled:!1};this._sendingPromises=[];this.url=t.url||this.getDefaultUrl(t),t.headers&&(this._headers=t.headers),this.onInit()}onShutdown(){c.diag.debug("@vercel/otel/otlp: onShutdown")}onInit(){c.diag.debug("@vercel/otel/otlp: onInit")}export(t,e){if(this._shutdownOnce.isCalled){c.diag.debug("@vercel/otel/otlp: Shutdown already started. Cannot send objects");return}this.send(t,()=>e({code:0}),n=>e({code:1,error:n}))}async forceFlush(){await Promise.all(this._sendingPromises)}async shutdown(){this._shutdownOnce.isCalled=!0,this.onShutdown(),await this.forceFlush()}send(t,e,n){if(this._shutdownOnce.isCalled){c.diag.debug("@vercel/otel/otlp: Shutdown already started. Cannot send objects");return}let o=this.convert(t),s,i,a;try{({body:s,contentType:i,headers:a}=this.toMessage(o))}catch(E){c.diag.warn("@vercel/otel/otlp: no proto",E);return}let _=fetch(this.url,{method:"POST",body:s,headers:{...this._headers,...a,"Content-Type":i,"User-Agent":"OTel-OTLP-Exporter-JavaScript/0.46.0"},next:{internal:!0}}).then(E=>{c.diag.debug("@vercel/otel/otlp: onSuccess",E.status,E.statusText),e(),E.arrayBuffer().catch(()=>{})}).catch(E=>{c.diag.error("@vercel/otel/otlp: onError",E),n(E)}).finally(()=>{let E=this._sendingPromises.indexOf(_);this._sendingPromises.splice(E,1)});this._sendingPromises.push(_)}};var VI="v1/traces",vI=`http://localhost:4318/${VI}`;function On(r){return typeof r.url=="string"?r.url:vI}var ce=class{constructor(t={}){this.impl=new qo(t)}export(t,e){this.impl.export(t,e)}shutdown(){return this.impl.shutdown()}forceFlush(){return this.impl.forceFlush()}},qo=class extends ae{convert(t){return t}toMessage(t){let e=Gp.JsonTraceSerializer.serializeRequest(t);return{body:new TextDecoder().decode(e),contentType:"application/json"}}getDefaultUrl(t){return On(t)}};var Fl=O(jo(),1);var wl=O(Bl(),1);function Gl(r){let t=new wl.Writer;return qI(r,t),t.finish()}function qI(r,t){if(r.resourceSpans!=null&&r.resourceSpans.length)for(let e=0;e<r.resourceSpans.length;++e)$I(r.resourceSpans[e],t.uint32(10).fork()).ldelim();return t}function $I(r,t){if(r.resource!=null&&XI(r.resource,t.uint32(10).fork()).ldelim(),r.scopeSpans!=null&&r.scopeSpans.length)for(let e=0;e<r.scopeSpans.length;++e)zI(r.scopeSpans[e],t.uint32(18).fork()).ldelim();return r.schemaUrl!=null&&t.uint32(26).string(r.schemaUrl),t}function XI(r,t){if(r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(10).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(16).uint32(r.droppedAttributesCount),t}function zI(r,t){if(r.scope!=null&&ZI(r.scope,t.uint32(10).fork()).ldelim(),r.spans!=null&&r.spans.length)for(let e=0;e<r.spans.length;++e)tx(r.spans[e],t.uint32(18).fork()).ldelim();return r.schemaUrl!=null&&t.uint32(26).string(r.schemaUrl),t}function Ee(r,t){return r.key!=null&&t.uint32(10).string(r.key),r.value!=null&&Hl(r.value,t.uint32(18).fork()).ldelim(),t}function Hl(r,t){return r.stringValue!=null&&t.uint32(10).string(r.stringValue),r.boolValue!=null&&t.uint32(16).bool(r.boolValue),r.intValue!=null&&t.uint32(24).int64(r.intValue),r.doubleValue!=null&&t.uint32(33).double(r.doubleValue),r.arrayValue!=null&&QI(r.arrayValue,t.uint32(42).fork()).ldelim(),r.kvlistValue!=null&&JI(r.kvlistValue,t.uint32(50).fork()).ldelim(),r.bytesValue!=null&&t.uint32(58).bytes(r.bytesValue),t}function QI(r,t){if(r.values!=null&&r.values.length)for(let e=0;e<r.values.length;++e)Hl(r.values[e],t.uint32(10).fork()).ldelim();return t}function JI(r,t){if(r.values!=null&&r.values.length)for(let e=0;e<r.values.length;++e)Ee(r.values[e],t.uint32(10).fork()).ldelim();return t}function ZI(r,t){if(r.name!=null&&t.uint32(10).string(r.name),r.version!=null&&t.uint32(18).string(r.version),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(26).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(32).uint32(r.droppedAttributesCount),t}function tx(r,t){if(r.traceId!=null&&t.uint32(10).bytes(r.traceId),r.spanId!=null&&t.uint32(18).bytes(r.spanId),r.traceState!=null&&t.uint32(26).string(r.traceState),r.parentSpanId!=null&&t.uint32(34).bytes(r.parentSpanId),r.name!=null&&t.uint32(42).string(r.name),r.kind!=null&&t.uint32(48).int32(r.kind),r.startTimeUnixNano!=null&&t.uint32(57).fixed64(r.startTimeUnixNano),r.endTimeUnixNano!=null&&t.uint32(65).fixed64(r.endTimeUnixNano),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(74).fork()).ldelim();if(r.droppedAttributesCount!=null&&t.uint32(80).uint32(r.droppedAttributesCount),r.events!=null&&r.events.length)for(let e=0;e<r.events.length;++e)rx(r.events[e],t.uint32(90).fork()).ldelim();if(r.droppedEventsCount!=null&&t.uint32(96).uint32(r.droppedEventsCount),r.links!=null&&r.links.length)for(let e=0;e<r.links.length;++e)nx(r.links[e],t.uint32(106).fork()).ldelim();return r.droppedLinksCount!=null&&t.uint32(112).uint32(r.droppedLinksCount),r.status!=null&&ex(r.status,t.uint32(122).fork()).ldelim(),t}function ex(r,t){return r.message!=null&&t.uint32(18).string(r.message),r.code!=null&&t.uint32(24).int32(r.code),t}function rx(r,t){if(r.timeUnixNano!=null&&t.uint32(9).fixed64(r.timeUnixNano),r.name!=null&&t.uint32(18).string(r.name),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(26).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(32).uint32(r.droppedAttributesCount),t}function nx(r,t){if(r.traceId!=null&&t.uint32(10).bytes(r.traceId),r.spanId!=null&&t.uint32(18).bytes(r.spanId),r.traceState!=null&&t.uint32(26).string(r.traceState),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(34).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(40).uint32(r.droppedAttributesCount),t}var wt=class{constructor(t={}){this.impl=new as(t)}export(t,e){this.impl.export(t,e)}shutdown(){return this.impl.shutdown()}forceFlush(){return this.impl.forceFlush()}},as=class extends ae{convert(t){return(0,Fl.createExportTraceServiceRequest)(t)}toMessage(t){return{body:Gl(t),contentType:"application/x-protobuf",headers:{accept:"application/x-protobuf"}}}getDefaultUrl(t){return On(t)}};d();function Yl(r,t){return r.replace(/\{(?<temp1>[^{}]+)\}/g,(e,n)=>{let o=t[n];return o!==void 0?String(o):e})}var ue=class{constructor(t={}){this.instrumentationName="@vercel/otel/fetch";this.instrumentationVersion="1.0.0";this.config=t}getConfig(){return this.config}setConfig(){}setTracerProvider(t){this.tracerProvider=t}setMeterProvider(){}shouldIgnore(t,e){let n=this.config.ignoreUrls??[];if(e?.opentelemetry?.ignore!==void 0)return e.opentelemetry.ignore;if(n.length===0)return!1;let o=t.toString();return n.some(s=>typeof s=="string"?s==="*"?!0:o.startsWith(s):s.test(o))}shouldPropagate(t,e){let n=process.env.VERCEL_URL||process.env.NEXT_PUBLIC_VERCEL_URL||null,o=process.env.VERCEL_BRANCH_URL||process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL||null,s=this.config.propagateContextUrls??[],i=this.config.dontPropagateContextUrls??[];if(e?.opentelemetry?.propagateContext)return e.opentelemetry.propagateContext;let a=t.toString();return i.length>0&&i.some(_=>typeof _=="string"?_==="*"?!0:a.startsWith(_):_.test(a))?!1:n&&t.protocol==="https:"&&(t.host===n||t.host===o||t.host===ut()?.headers.host)||!n&&t.protocol==="http:"&&t.hostname==="localhost"?!0:s.some(_=>typeof _=="string"?_==="*"?!0:a.startsWith(_):_.test(a))}startSpan({tracer:t,url:e,fetchType:n,method:o="GET",name:s,attributes:i={}}){let a=this.config.resourceNameTemplate,_={[Ap]:o,[dp]:e.toString(),[dn]:e.host,[mp]:e.protocol.replace(":",""),[Rp]:e.hostname,[hp]:e.port},E=a?Yl(a,_):ix(e.toString()),T=s??`${n} ${o} ${e.toString()}`,l=c.context.active();return t.startSpan(T,{kind:c.SpanKind.CLIENT,attributes:{..._,"operation.name":`${n}.${o}`,"http.client.name":n,"resource.name":E,...i}},l)}instrumentHttp(t,e){let{tracerProvider:n}=this;if(!n)return;let o=n.getTracer(this.instrumentationName,this.instrumentationVersion),{attributesFromRequestHeaders:s,attributesFromResponseHeaders:i}=this.config,a=t.request,_=t.get,E=T=>(l,A,h)=>{let R,I={},x;if(typeof l=="string"||l instanceof URL?(R=new URL(l.toString()),typeof A=="function"?x=A:A&&typeof h=="function"?(I=A,x=h):A&&(I=A)):(I=l,typeof A=="function"&&(x=A),R=cx(I,e)),this.shouldIgnore(R))return T.apply(this,[R,I,x]);let M=this.startSpan({tracer:o,url:R,fetchType:"http",method:I.method||"GET"});if(!M.isRecording()||!ie(M.spanContext().traceFlags))return M.end(),T.apply(this,[R,I,x]);if(this.shouldPropagate(R)){let J=c.context.active(),Lt=c.trace.setSpan(J,M);c.propagation.inject(Lt,I.headers||{},sx)}s&&Cn(M,s,I.headers||{},Kl);try{let J=Date.now(),Lt=T.apply(this,[R,I,x]);return Lt.prependListener("response",w=>{let Jl=Date.now()-J;M.setAttribute("http.response_time",Jl),w.statusCode!==void 0?(M.setAttribute(Bo,w.statusCode),w.statusCode>=500&&Gt(M,`Status: ${w.statusCode}`)):Gt(M,"Response status code is undefined"),i&&Cn(M,i,w.headers,Kl),Lt.listenerCount("response")<=1&&w.resume(),w.on("end",()=>{let Fe,Un=w.statusCode;w.aborted&&!w.complete?Fe={code:c.SpanStatusCode.ERROR}:Un&&Un>=100&&Un<500?Fe={code:c.SpanStatusCode.UNSET}:Fe={code:c.SpanStatusCode.ERROR},M.setStatus(Fe),M.isRecording()&&(w.headers["content-length"]&&M.setAttribute(wo,w.headers["content-length"]),M.end())})}),Lt.on("error",w=>{M.isRecording()&&(Gt(M,w),M.end())}),Lt.on("close",()=>{M.isRecording()&&M.end()}),Lt}catch(J){throw Gt(M,J),M.end(),J}};t.request=E(a),t.get=E(_)}instrumentFetch(){let{tracerProvider:t}=this;if(!t)return;let e=t.getTracer(this.instrumentationName,this.instrumentationVersion),{attributesFromRequestHeaders:n,attributesFromResponseHeaders:o}=this.config;process.env.NEXT_OTEL_FETCH_DISABLED="1";let s=globalThis.fetch;this.originalFetch=s;let i=async(a,_)=>{let E=_;if(E?.next?.internal)return s(a,E);let T=new Request(a instanceof Request?a.clone():a,E),l=new URL(T.url);if(this.shouldIgnore(l,E))return s(a,E);let A=this.startSpan({tracer:e,url:l,fetchType:"fetch",method:T.method,name:E?.opentelemetry?.spanName,attributes:E?.opentelemetry?.attributes});if(!A.isRecording()||!ie(A.spanContext().traceFlags))return A.end(),s(a,E);if(this.shouldPropagate(l,E)){let h=c.context.active(),R=c.trace.setSpan(h,A);c.propagation.inject(R,T.headers,ox)}n&&Cn(A,n,T.headers,kl);try{let h=Date.now();E?.body&&E.body instanceof FormData&&T.headers.delete("content-type");let R=await s(a,{...E,headers:T.headers}),I=Date.now()-h;return A.setAttribute(Bo,R.status),A.setAttribute("http.response_time",I),o&&Cn(A,o,R.headers,kl),R.status>=500&&Gt(A,`Status: ${R.status} (${R.statusText})`),R.body?ax(R).then(x=>{A.isRecording()&&(A.setAttribute(wo,x),A.end())},x=>{A.isRecording()&&(Gt(A,x),A.end())}):A.end(),R}catch(h){throw Gt(A,h),A.end(),h}};globalThis.fetch=i}enable(){this.disable(),this.instrumentFetch();try{let t=Es("node:http"),e=Es("node:https");this.instrumentHttp(t,"http:"),this.instrumentHttp(e,"https:")}catch{}}disable(){this.originalFetch&&(globalThis.fetch=this.originalFetch)}},ox={set(r,t,e){r.set(t,e)}},kl={get(r,t){let e=r.get(t);if(e!==null)return e.includes(",")?e.split(",").map(n=>n.trimStart()):e},keys(r){let t=[];return r.forEach((e,n)=>{t.push(n)}),t}},sx={set(r,t,e){r[t.toLowerCase()]=e}},Kl={get(r,t){return r[t.toLowerCase()]},keys(r){return Object.keys(r)}};function ix(r){let t=r.indexOf("?");return t===-1?r:r.substring(0,t)}function ax(r){let t=0,n=r.clone().body?.getReader();if(!n)return Promise.resolve(0);let o=()=>n.read().then(({done:s,value:i})=>{if(!s)return t+=i.byteLength,o()});return o().then(()=>t)}function Gt(r,t){if(t instanceof Error)r.recordException(t),r.setStatus({code:c.SpanStatusCode.ERROR,message:t.message});else{let e=String(t);r.setStatus({code:c.SpanStatusCode.ERROR,message:e})}}function Cn(r,t,e,n){for(let[o,s]of Object.entries(t)){let i=n.get(e,s);i!==void 0&&r.setAttribute(o,i)}}function cx(r,t){if(r.socketPath)throw new Error("Cannot construct a network URL: options.socketPath is specified, indicating a Unix domain socket.");let e=r.protocol??t;e&&!e.endsWith(":")&&(e+=":");let n=r.hostname,o=r.port??r.defaultPort;if(!n&&r.host){let E=r.host.split(":");n=E[0];let T=E[1];if(E.length>1&&T&&o===void 0){let l=parseInt(T,10);isNaN(l)||(o=l)}}n||(n="localhost");let s;if(o!==void 0&&o!==""){let E=parseInt(String(o),10);isNaN(E)?s=e==="https:"?443:80:s=E}else s=e==="https:"?443:80;let i=r.path||"/",a=`${e}//${n}:${s}`,_=new URL(i,a);if(r.auth){let E=r.auth.split(":");_.username=decodeURIComponent(E[0]||""),E.length>1&&(_.password=decodeURIComponent(E[1]||""))}return _}d();var jl=O(P(),1),_x="00",cs="traceparent",_s="tracestate",He=class{fields(){return[cs,_s]}inject(t,e,n){let o=c.trace.getSpanContext(t);if(!o||(0,jl.isTracingSuppressed)(t)||!(0,c.isSpanContextValid)(o))return;let s=`${_x}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||0).toString(16)}`;n.set(e,cs,s),o.traceState&&n.set(e,_s,o.traceState.serialize())}extract(t,e,n){let o=n.get(e,cs);if(!o)return t;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return t;let i=Ex(s);if(!i)return t;i.isRemote=!0;let a=n.get(e,_s);if(a){let _=Array.isArray(a)?a.join(","):a;i.traceState=(0,c.createTraceState)(typeof _=="string"?_:void 0)}return c.trace.setSpanContext(t,i)}};function Ex(r){let[t,e,n,o,s]=r.split("-");return!t||!e||!n||!o||t.length!==2||e.length!==32||n.length!==16||o.length!==2||t==="00"&&s?null:{traceId:e,spanId:n,traceFlags:parseInt(o,16)}}d();var Ln=class{fields(){return[]}inject(){}extract(t){let e=ut();if(!e?.telemetry)return c.diag.warn("@vercel/otel: Vercel telemetry extension not found."),t;let{rootSpanContext:n}=e.telemetry;return n?(c.diag.debug("@vercel/otel: Extracted root SpanContext from Vercel request context.",n),c.trace.setSpanContext(t,{...n,isRemote:!0,traceFlags:n.traceFlags||c.TraceFlags.SAMPLED})):t}};d();var In=O(P(),1),Wl=O(Wo(),1);var xn=class{export(t,e){let n=ut();if(!n?.telemetry){c.diag.warn("@vercel/otel: no telemetry context found"),e({code:In.ExportResultCode.SUCCESS,error:void 0});return}try{let o=Wl.JsonTraceSerializer.serializeRequest(t);if(!o)throw new Error("Failed to serialize spans");let s=JSON.parse(new TextDecoder().decode(o));n.telemetry.reportSpans(s),e({code:In.ExportResultCode.SUCCESS,error:void 0})}catch(o){e({code:In.ExportResultCode.FAILED,error:o instanceof Error?o:new Error(String(o))})}}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}};function Q(r){let t=process.env[r];if(!(!t||t.trim()===""))return t}function ql(r){return Q(r)?.split(",").map(t=>t.trim()).filter(t=>t!=="")}var ux={ALL:c.DiagLogLevel.ALL,VERBOSE:c.DiagLogLevel.VERBOSE,DEBUG:c.DiagLogLevel.DEBUG,INFO:c.DiagLogLevel.INFO,WARN:c.DiagLogLevel.WARN,ERROR:c.DiagLogLevel.ERROR,NONE:c.DiagLogLevel.NONE},Dn=class{constructor(t={}){this.configuration=t}start(){let t=Tx(),e=this.configuration,n=process.env.NEXT_RUNTIME||"nodejs",o=!!t.OTEL_SDK_DISABLED;if(process.env.OTEL_LOG_LEVEL&&c.diag.setLogger(new c.DiagConsoleLogger,{logLevel:ux[process.env.OTEL_LOG_LEVEL.toUpperCase()]}),o)return;let s=e.idGenerator??new Rt;this.contextManager=Rx(e.contextManager);let i=t.OTEL_SERVICE_NAME||e.serviceName||"app",a=Re(mn({[Op]:i,"node.ci":process.env.CI?!0:void 0,"node.env":"production",env:process.env.VERCEL_ENV||process.env.NEXT_PUBLIC_VERCEL_ENV,"vercel.region":process.env.VERCEL_REGION,"vercel.runtime":n,"vercel.sha":process.env.VERCEL_GIT_COMMIT_SHA||process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA,"vercel.host":process.env.VERCEL_URL||process.env.NEXT_PUBLIC_VERCEL_URL||void 0,"vercel.branch_host":process.env.VERCEL_BRANCH_URL||process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL||void 0,"vercel.deployment_id":process.env.VERCEL_DEPLOYMENT_ID||void 0,[gp]:process.env.VERCEL_DEPLOYMENT_ID,...e.attributes})),_=e.resourceDetectors??[Or];if(e.autoDetectResources??!0){let M=oo({detectors:_});a=a.merge(M)}let T=px(e.propagators,e,t),l=lx(e.traceSampler,t),A=Ax(e.spanProcessors,e,t);A.length===0&&c.diag.warn("@vercel/otel: No span processors configured. No spans will be exported.");let h=e.spanLimits,R=new ge({resource:a,idGenerator:s,sampler:l,spanLimits:h,spanProcessors:[new fn(A,e.attributesFromHeaders)]});if(c.trace.setGlobalTracerProvider(R),c.propagation.setGlobalPropagator(new Ct.CompositePropagator({propagators:T})),this.tracerProvider=R,e.logRecordProcessors){let x=new Ne({resource:a,processors:e.logRecordProcessors});this.loggerProvider=x,W.logs.setGlobalLoggerProvider(x)}if(e.metricReaders||e.views){let x=new ye({resource:a,views:e.views??[],readers:e.metricReaders??[]});c.metrics.setGlobalMeterProvider(x),this.meterProvider=x}let I=Sx(e.instrumentations,e.instrumentationConfig);this.disableInstrumentations=_o({instrumentations:I}),c.diag.info("@vercel/otel: started",i,n)}async shutdown(){let t=[];this.tracerProvider&&t.push(this.tracerProvider.shutdown()),this.loggerProvider&&t.push(this.loggerProvider.shutdown()),this.meterProvider&&t.push(this.meterProvider.shutdown()),c.diag.info("@vercel/otel: shutting down",t.length,process.env.NEXT_RUNTIME),await Promise.all(t),this.contextManager&&this.contextManager.disable();let{disableInstrumentations:e}=this;e&&e()}};function Tx(){return{OTEL_SDK_DISABLED:Q("OTEL_SDK_DISABLED"),OTEL_SERVICE_NAME:Q("OTEL_SERVICE_NAME"),OTEL_PROPAGATORS:ql("OTEL_PROPAGATORS"),OTEL_TRACES_SAMPLER:Q("OTEL_TRACES_SAMPLER"),OTEL_TRACES_SAMPLER_ARG:Q("OTEL_TRACES_SAMPLER_ARG"),OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:Q("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"),OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:Q("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"),OTEL_EXPORTER_OTLP_PROTOCOL:Q("OTEL_EXPORTER_OTLP_PROTOCOL"),OTEL_EXPORTER_OTLP_ENDPOINT:Q("OTEL_EXPORTER_OTLP_ENDPOINT"),OTEL_EXPORTER_OTLP_HEADERS:Q("OTEL_EXPORTER_OTLP_HEADERS"),OTEL_EXPORTER_OTLP_TRACES_HEADERS:Q("OTEL_EXPORTER_OTLP_TRACES_HEADERS")}}function Sx(r,t){return(r??["auto"]).map(e=>e==="auto"?(c.diag.debug("@vercel/otel: Configure instrumentations: fetch",t?.fetch),[new ue(t?.fetch)]):e==="fetch"?(c.diag.debug("@vercel/otel: Configure instrumentations: fetch",t?.fetch),new ue(t?.fetch)):e).flat()}function px(r,t,e){let n=process.env.OTEL_PROPAGATORS&&e.OTEL_PROPAGATORS&&e.OTEL_PROPAGATORS.length>0?e.OTEL_PROPAGATORS:void 0;return(r??n??["auto"]).map(o=>{if(o==="none")return[];if(o==="auto"){let s=[];return s.push({name:"tracecontext",propagator:new He}),s.push({name:"baggage",propagator:new Ct.W3CBaggagePropagator}),s.push({name:"vercel-runtime",propagator:new Ln}),c.diag.debug(`@vercel/otel: Configure propagators: ${s.map(i=>i.name).join(", ")}`),s.map(i=>i.propagator)}if(o==="tracecontext")return c.diag.debug("@vercel/otel: Configure propagator: tracecontext"),new He;if(o==="baggage")return c.diag.debug("@vercel/otel: Configure propagator: baggage"),new Ct.W3CBaggagePropagator;if(typeof o=="string")throw new Error(`Unknown propagator: "${o}"`);return o}).flat()}var $l="always_on",Te=1;function lx(r,t){if(r&&typeof r!="string")return r;let e=r&&r!=="auto"?r:t.OTEL_TRACES_SAMPLER||$l;switch(c.diag.debug("@vercel/otel: Configure sampler: ",e),e){case"always_on":return new B;case"always_off":return new k;case"parentbased_always_on":return new K({root:new B});case"parentbased_always_off":return new K({root:new k});case"traceidratio":return new At(Xl(t));case"parentbased_traceidratio":return new K({root:new At(Xl(t))});default:return c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER value "${String(t.OTEL_TRACES_SAMPLER)} invalid, defaulting to ${$l}".`),new B}}function Xl(r){if(r.OTEL_TRACES_SAMPLER_ARG===void 0||r.OTEL_TRACES_SAMPLER_ARG==="")return c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${Te}.`),Te;c.diag.debug("@vercel/otel: Configure sampler probability: ",r.OTEL_TRACES_SAMPLER_ARG);let t=Number(r.OTEL_TRACES_SAMPLER_ARG);return isNaN(t)?(c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER_ARG=${r.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${Te}.`),Te):t<0||t>1?(c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER_ARG=${r.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${Te}.`),Te):t}function Ax(r,t,e){return[...(r??["auto"]).flatMap(n=>{if(n==="auto"){let o=[new dt(new xn)];if(process.env.VERCEL_OTEL_ENDPOINTS){let s=process.env.VERCEL_OTEL_ENDPOINTS_PORT||"4318",i=process.env.VERCEL_OTEL_ENDPOINTS_PROTOCOL||"http/protobuf";c.diag.debug("@vercel/otel: Configure vercel otel collector on port: ",s,i);let a={url:`http://localhost:${s}/v1/traces`,headers:{}},_=i==="http/protobuf"?new wt(a):new ce(a);o.push(new dt(_))}else(!t.traceExporter||t.traceExporter==="auto"||e.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||e.OTEL_EXPORTER_OTLP_ENDPOINT)&&o.push(new dt(dx(e)));return o}return n}).filter(hx),...t.traceExporter&&t.traceExporter!=="auto"?[new dt(t.traceExporter)]:[]]}function dx(r){let t=r.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL??r.OTEL_EXPORTER_OTLP_PROTOCOL??"http/protobuf",e=fx(r),n={...r.OTEL_EXPORTER_OTLP_HEADERS?(0,Ct.parseKeyPairsIntoRecord)(r.OTEL_EXPORTER_OTLP_HEADERS):{},...r.OTEL_EXPORTER_OTLP_TRACES_HEADERS?(0,Ct.parseKeyPairsIntoRecord)(r.OTEL_EXPORTER_OTLP_TRACES_HEADERS):{}};switch(c.diag.debug("@vercel/otel: Configure trace exporter: ",t,e,`headers: ${Object.keys(n).join(",")||"<none>"}`),t){case"http/json":return new ce({url:e,headers:n});case"http/protobuf":return new wt({url:e,headers:n});default:return c.diag.warn(`@vercel/otel: Unsupported OTLP traces protocol: ${t}. Using http/protobuf.`),new wt}}var Ql="v1/traces",mx=`http://localhost:4318/${Ql}`;function fx(r){let t=r.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;if(t&&typeof t=="string")return t;let e=r.OTEL_EXPORTER_OTLP_ENDPOINT;return e&&typeof e=="string"?`${e}/${Ql}`:mx}function hx(r){return r!=null}function Rx(r){if(r===void 0){c.diag.debug("@vercel/otel: Configure context manager: default");let t=new zl.AsyncLocalStorageContextManager;return t.enable(),c.context.setGlobalContextManager(t),t}return c.diag.debug("@vercel/otel: Configure context manager: from configuration"),r.enable(),c.context.setGlobalContextManager(r),r}function _B(r){let t;r?typeof r=="string"?t={serviceName:r}:t=r:t={},new Dn(t).start()}export{ue as FetchInstrumentation,ce as OTLPHttpJsonTraceExporter,wt as OTLPHttpProtoTraceExporter,_B as registerOTel};
|
|
16
|
+
`,Io(s,t))}return n}};var en=class{_backingStorages;constructor(t){this._backingStorages=t}record(t,e,n,o){this._backingStorages.forEach(s=>{s.record(t,e,n,o)})}};d();d();var rn=class{_instrumentName;_valueType;_buffer=new H;constructor(t,e){this._instrumentName=t,this._valueType=e}observe(t,e={}){if(typeof t!="number"){c.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${t}`);return}this._valueType===c.ValueType.INT&&!Number.isInteger(t)&&(c.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),t=Math.trunc(t),!Number.isInteger(t))||this._buffer.set(e,t)}},nn=class{_buffer=new Map;observe(t,e,n={}){if(!be(t))return;let o=this._buffer.get(t);if(o==null&&(o=new H,this._buffer.set(t,o)),typeof e!="number"){c.diag.warn(`non-number value provided to metric ${t._descriptor.name}: ${e}`);return}t._descriptor.valueType===c.ValueType.INT&&!Number.isInteger(e)&&(c.diag.warn(`INT value type cannot accept a floating-point value for ${t._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),!Number.isInteger(e))||o.set(n,e)}};var on=class{_callbacks=[];_batchCallbacks=[];addCallback(t,e){this._findCallback(t,e)>=0||this._callbacks.push({callback:t,instrument:e})}removeCallback(t,e){let n=this._findCallback(t,e);n<0||this._callbacks.splice(n,1)}addBatchCallback(t,e){let n=new Set(e.filter(be));if(n.size===0){c.diag.error("BatchObservableCallback is not associated with valid instruments",e);return}this._findBatchCallback(t,n)>=0||this._batchCallbacks.push({callback:t,instruments:n})}removeBatchCallback(t,e){let n=new Set(e.filter(be)),o=this._findBatchCallback(t,n);o<0||this._batchCallbacks.splice(o,1)}async observe(t,e){let n=this._observeCallbacks(t,e),o=this._observeBatchCallbacks(t,e);return(await zS([...n,...o])).filter(QS).map(a=>a.reason)}_observeCallbacks(t,e){return this._callbacks.map(async({callback:n,instrument:o})=>{let s=new rn(o._descriptor.name,o._descriptor.valueType),i=Promise.resolve(n(s));e!=null&&(i=uo(i,e)),await i,o._metricStorages.forEach(a=>{a.record(s._buffer,t)})})}_observeBatchCallbacks(t,e){return this._batchCallbacks.map(async({callback:n,instruments:o})=>{let s=new nn,i=Promise.resolve(n(s));e!=null&&(i=uo(i,e)),await i,o.forEach(a=>{let _=s._buffer.get(a);_!=null&&a._metricStorages.forEach(E=>{E.record(_,t)})})})}_findCallback(t,e){return this._callbacks.findIndex(n=>n.callback===t&&n.instrument===e)}_findBatchCallback(t,e){return this._batchCallbacks.findIndex(n=>n.callback===t&&JS(n.instruments,e))}};var sn=class extends te{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(t,e,n,o,s){super(t),this._attributesProcessor=n,this._aggregationCardinalityLimit=s,this._deltaMetricStorage=new ee(e,this._aggregationCardinalityLimit),this._temporalMetricStorage=new re(e,o)}record(t,e,n,o){e=this._attributesProcessor.process(e,n),this._deltaMetricStorage.record(t,e,n,o)}collect(t,e){let n=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(t,this._instrumentDescriptor,n,e)}};var xo=class{process(t,e){return t}},Do=class{_processors;constructor(t){this._processors=t}process(t,e){let n=t;for(let o of this._processors)n=o.process(n,e);return n}};function an(){return oI}function Ep(r){return new Do(r)}var oI=new xo;var cn=class{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new tn;observableRegistry=new on;meter;constructor(t,e){this._meterProviderSharedState=t,this._instrumentationScope=e,this.meter=new Jr(this)}registerMetricStorage(t){let e=this._registerMetricStorage(t,sn);return e.length===1?e[0]:new en(e)}registerAsyncMetricStorage(t){return this._registerMetricStorage(t,Zr)}async collect(t,e,n){let o=await this.observableRegistry.observe(e,n?.timeoutMillis),s=this.metricStorageRegistry.getStorages(t);if(s.length===0)return null;let i=s.map(a=>a.collect(t,e)).filter($S);return i.length===0?{errors:o}:{scopeMetrics:{scope:this._instrumentationScope,metrics:i},errors:o}}_registerMetricStorage(t,e){let o=this._meterProviderSharedState.viewRegistry.findViews(t,this._instrumentationScope).map(s=>{let i=ap(s,t),a=this.metricStorageRegistry.findOrUpdateCompatibleStorage(i);if(a!=null)return a;let _=s.aggregation.createAggregator(i),E=new e(i,_,s.attributesProcessor,this._meterProviderSharedState.metricCollectors,s.aggregationCardinalityLimit);return this.metricStorageRegistry.register(E),E});if(o.length===0){let i=this._meterProviderSharedState.selectAggregations(t.type).map(([a,_])=>{let E=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(a,t);if(E!=null)return E;let T=_.createAggregator(t),l=a.selectCardinalityLimit(t.type),A=new e(t,T,an(),[a],l);return this.metricStorageRegistry.registerForCollector(a,A),A});o=o.concat(i)}return o}};var _n=class{resource;viewRegistry=new Kr;metricCollectors=[];meterSharedStates=new Map;constructor(t){this.resource=t}getMeterSharedState(t){let e=XS(t),n=this.meterSharedStates.get(e);return n==null&&(n=new cn(this,t),this.meterSharedStates.set(e,n)),n}selectAggregations(t){let e=[];for(let n of this.metricCollectors)e.push([n,kr(n.selectAggregation(t))]);return e}};var up=O(P()),En=class{_sharedState;_metricReader;constructor(t,e){this._sharedState=t,this._metricReader=e}async collect(t){let e=(0,up.millisToHrTime)(Date.now()),n=[],o=[],s=Array.from(this._sharedState.meterSharedStates.values()).map(async i=>{let a=await i.collect(this,e,t);a?.scopeMetrics!=null&&n.push(a.scopeMetrics),a?.errors!=null&&o.push(...a.errors)});return await Promise.all(s),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:n},errors:o}}async forceFlush(t){await this._metricReader.forceFlush(t)}async shutdown(t){await this._metricReader.shutdown(t)}selectAggregationTemporality(t){return this._metricReader.selectAggregationTemporality(t)}selectAggregation(t){return this._metricReader.selectAggregation(t)}selectCardinalityLimit(t){return this._metricReader.selectCardinalityLimit?.(t)??2e3}};var sI=/[\^$\\.+?()[\]{}|]/g,ne=class r{_matchAll;_regexp;constructor(t){t==="*"?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(r.escapePattern(t)))}match(t){return this._matchAll?!0:this._regexp.test(t)}static escapePattern(t){return`^${t.replace(sI,"\\$&").replace("*",".*")}$`}static hasWildcard(t){return t.includes("*")}},gt=class{_matchAll;_pattern;constructor(t){this._matchAll=t===void 0,this._pattern=t}match(t){return!!(this._matchAll||t===this._pattern)}};var un=class{_nameFilter;_type;_unitFilter;constructor(t){this._nameFilter=new ne(t?.name??"*"),this._type=t?.type,this._unitFilter=new gt(t?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}};var Tn=class{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(t){this._nameFilter=new gt(t?.name),this._versionFilter=new gt(t?.version),this._schemaUrlFilter=new gt(t?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}};function iI(r){return r.instrumentName==null&&r.instrumentType==null&&r.instrumentUnit==null&&r.meterName==null&&r.meterVersion==null&&r.meterSchemaUrl==null}function aI(r){if(iI(r))throw new Error("Cannot create view with no selector arguments supplied");if(r.name!=null&&(r?.instrumentName==null||ne.hasWildcard(r.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}var Sn=class{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(t){aI(t),t.attributesProcessors!=null?this.attributesProcessor=Ep(t.attributesProcessors):this.attributesProcessor=an(),this.name=t.name,this.description=t.description,this.aggregation=kr(t.aggregation??{type:_t.DEFAULT}),this.instrumentSelector=new un({name:t.instrumentName,type:t.instrumentType,unit:t.instrumentUnit}),this.meterSelector=new Tn({name:t.meterName,version:t.meterVersion,schemaUrl:t.meterSchemaUrl}),this.aggregationCardinalityLimit=t.aggregationCardinalityLimit}};var ye=class{_sharedState;_shutdown=!1;constructor(t){if(this._sharedState=new _n(t?.resource??Ut()),t?.views!=null&&t.views.length>0)for(let e of t.views)this._sharedState.viewRegistry.addView(new Sn(e));if(t?.readers!=null&&t.readers.length>0)for(let e of t.readers){let n=new En(this._sharedState,e);e.setMetricProducer(n),this._sharedState.metricCollectors.push(n)}}getMeter(t,e="",n={}){return this._shutdown?(c.diag.warn("A shutdown MeterProvider cannot provide a Meter"),(0,c.createNoopMeter)()):this._sharedState.getMeterSharedState({name:t,version:e,schemaUrl:n.schemaUrl}).meter}async shutdown(t){if(this._shutdown){c.diag.warn("shutdown may only be called once per MeterProvider");return}this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(e=>e.shutdown(t)))}async forceFlush(t){if(this._shutdown){c.diag.warn("invalid attempt to force flush after MeterProvider shutdown");return}await Promise.all(this._sharedState.metricCollectors.map(e=>e.forceFlush(t)))}};var zl=O(lp(),1),Ct=O(P(),1);var Ap="http.method",dp="http.url",dn="http.host",mp="http.scheme",Bo="http.status_code",fp="http.user_agent",wo="http.response_content_length_uncompressed",hp="net.peer.port",Rp="net.peer.name";var Op="service.name",gp="service.version";d();var mI=Symbol.for("@vercel/request-context");function ut(){return globalThis[mI]?.get()}function mn(r){return Object.fromEntries(Object.entries(r).filter(([t,e])=>e!==void 0))}function Np(r){return r?r.split("::").at(-1):void 0}function Mp(r=ut(),t){if(!r)return;let e=t?hI(t,r.headers):void 0;return mn({[dn]:r.headers.host,[fp]:r.headers["user-agent"],"http.referer":r.headers.referer,"vercel.request_id":Np(r.headers["x-vercel-id"]),"vercel.matched_path":r.headers["x-matched-path"],"vercel.edge_region":process.env.VERCEL_REGION,...e})}var fI={keys(r){return[]},get(r,t){return r[t.toLocaleLowerCase()]}};function hI(r,t){if(typeof r=="function")return r(t,fI);let e={};for(let[n,o]of Object.entries(r)){let s=t[o.toLocaleLowerCase()];s!==void 0&&(e[n]=s)}return e}d();function ie(r){return(r&c.TraceFlags.SAMPLED)!==0}var fn=class{constructor(t,e){this.processors=t;this.attributesFromHeaders=e;this.rootSpanIds=new Map;this.waitSpanEnd=new Map}forceFlush(){return Promise.all(this.processors.map(t=>t.forceFlush().catch(e=>{c.diag.error("@vercel/otel: forceFlush failed:",e)}))).then(()=>{})}shutdown(){return Promise.all(this.processors.map(t=>t.shutdown().catch(()=>{}))).then(()=>{})}onStart(t,e){let{traceId:n,spanId:o,traceFlags:s}=t.spanContext(),i=!t.parentSpanContext?.spanId||!this.rootSpanIds.has(n);if(i?this.rootSpanIds.set(n,{rootSpanId:o,open:[]}):this.rootSpanIds.get(n)?.open.push(t),i&&ie(s)){let a=ut(),_=Mp(a,this.attributesFromHeaders);_&&t.setAttributes(_),a&&a.waitUntil(async()=>{if(this.rootSpanIds.has(n)){let E=new Promise(l=>{this.waitSpanEnd.set(n,l)}),T;await Promise.race([E,new Promise(l=>{T=setTimeout(()=>{this.waitSpanEnd.delete(n),l(void 0)},50)})]),T&&clearTimeout(T)}return this.forceFlush()})}for(let a of this.processors)a.onStart(t,e)}onEnd(t){let{traceId:e,spanId:n,traceFlags:o}=t.spanContext(),s=ie(o),i=this.rootSpanIds.get(e),a=i?.rootSpanId===n;if(s){let _=OI(t);_&&Object.assign(t.attributes,_)}if(a){if(this.rootSpanIds.delete(e),i.open.length>0){for(let _ of i.open)if(!_.ended&&_.spanContext().spanId!==n)try{_.end()}catch(E){c.diag.error("@vercel/otel: onEnd failed:",E)}}}else if(i)for(let _=0;_<i.open.length;_++)i.open[_]?.spanContext().spanId===n&&i.open.splice(_,1);for(let _ of this.processors)_.onEnd(t);if(a){let _=this.waitSpanEnd.get(e);_&&(this.waitSpanEnd.delete(e),_())}}},RI={[c.SpanKind.INTERNAL]:"internal",[c.SpanKind.SERVER]:"server",[c.SpanKind.CLIENT]:"client",[c.SpanKind.PRODUCER]:"producer",[c.SpanKind.CONSUMER]:"consumer"};function OI(r){let{kind:t,attributes:e}=r,{"operation.name":n,"resource.name":o,"span.type":s,"next.span_type":i,"http.method":a,"http.route":_}=e;if(n)return;let E=o??(a&&typeof a=="string"&&_&&typeof _=="string"?`${a} ${_}`:_);if(r.kind===c.SpanKind.SERVER&&a&&_&&typeof a=="string"&&typeof _=="string")return{"operation.name":"web.request","resource.name":E};let T=r.instrumentationScope.name,l=i??s;if(l&&typeof l=="string"){let A=Pp(T,l);return _?{"operation.name":A,"resource.name":E}:{"operation.name":A}}return{"operation.name":Pp(T,t===c.SpanKind.INTERNAL?"":RI[t])}}function Pp(r,t){if(!r)return t;let e=r.replace(/[ @./]/g,"_");return e.startsWith("_")&&(e=e.slice(1)),t?`${e}.${t}`:e}var Gp=O(Wo(),1);d();var ae=class{constructor(t={}){this._shutdownOnce={isCalled:!1};this._sendingPromises=[];this.url=t.url||this.getDefaultUrl(t),t.headers&&(this._headers=t.headers),this.onInit()}onShutdown(){c.diag.debug("@vercel/otel/otlp: onShutdown")}onInit(){c.diag.debug("@vercel/otel/otlp: onInit")}export(t,e){if(this._shutdownOnce.isCalled){c.diag.debug("@vercel/otel/otlp: Shutdown already started. Cannot send objects");return}this.send(t,()=>e({code:0}),n=>e({code:1,error:n}))}async forceFlush(){await Promise.all(this._sendingPromises)}async shutdown(){this._shutdownOnce.isCalled=!0,this.onShutdown(),await this.forceFlush()}send(t,e,n){if(this._shutdownOnce.isCalled){c.diag.debug("@vercel/otel/otlp: Shutdown already started. Cannot send objects");return}let o=this.convert(t),s,i,a;try{({body:s,contentType:i,headers:a}=this.toMessage(o))}catch(E){c.diag.warn("@vercel/otel/otlp: no proto",E);return}let _=fetch(this.url,{method:"POST",body:s,headers:{...this._headers,...a,"Content-Type":i,"User-Agent":"OTel-OTLP-Exporter-JavaScript/0.46.0"},next:{internal:!0}}).then(E=>{c.diag.debug("@vercel/otel/otlp: onSuccess",E.status,E.statusText),e(),E.arrayBuffer().catch(()=>{})}).catch(E=>{c.diag.error("@vercel/otel/otlp: onError",E),n(E)}).finally(()=>{let E=this._sendingPromises.indexOf(_);this._sendingPromises.splice(E,1)});this._sendingPromises.push(_)}};var VI="v1/traces",vI=`http://localhost:4318/${VI}`;function On(r){return typeof r.url=="string"?r.url:vI}var ce=class{constructor(t={}){this.impl=new qo(t)}export(t,e){this.impl.export(t,e)}shutdown(){return this.impl.shutdown()}forceFlush(){return this.impl.forceFlush()}},qo=class extends ae{convert(t){return t}toMessage(t){let e=Gp.JsonTraceSerializer.serializeRequest(t);return{body:new TextDecoder().decode(e),contentType:"application/json"}}getDefaultUrl(t){return On(t)}};var Fl=O(jo(),1);var wl=O(Bl(),1);function Gl(r){let t=new wl.Writer;return qI(r,t),t.finish()}function qI(r,t){if(r.resourceSpans!=null&&r.resourceSpans.length)for(let e=0;e<r.resourceSpans.length;++e)$I(r.resourceSpans[e],t.uint32(10).fork()).ldelim();return t}function $I(r,t){if(r.resource!=null&&XI(r.resource,t.uint32(10).fork()).ldelim(),r.scopeSpans!=null&&r.scopeSpans.length)for(let e=0;e<r.scopeSpans.length;++e)zI(r.scopeSpans[e],t.uint32(18).fork()).ldelim();return r.schemaUrl!=null&&t.uint32(26).string(r.schemaUrl),t}function XI(r,t){if(r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(10).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(16).uint32(r.droppedAttributesCount),t}function zI(r,t){if(r.scope!=null&&ZI(r.scope,t.uint32(10).fork()).ldelim(),r.spans!=null&&r.spans.length)for(let e=0;e<r.spans.length;++e)tx(r.spans[e],t.uint32(18).fork()).ldelim();return r.schemaUrl!=null&&t.uint32(26).string(r.schemaUrl),t}function Ee(r,t){return r.key!=null&&t.uint32(10).string(r.key),r.value!=null&&Hl(r.value,t.uint32(18).fork()).ldelim(),t}function Hl(r,t){return r.stringValue!=null&&t.uint32(10).string(r.stringValue),r.boolValue!=null&&t.uint32(16).bool(r.boolValue),r.intValue!=null&&t.uint32(24).int64(r.intValue),r.doubleValue!=null&&t.uint32(33).double(r.doubleValue),r.arrayValue!=null&&QI(r.arrayValue,t.uint32(42).fork()).ldelim(),r.kvlistValue!=null&&JI(r.kvlistValue,t.uint32(50).fork()).ldelim(),r.bytesValue!=null&&t.uint32(58).bytes(r.bytesValue),t}function QI(r,t){if(r.values!=null&&r.values.length)for(let e=0;e<r.values.length;++e)Hl(r.values[e],t.uint32(10).fork()).ldelim();return t}function JI(r,t){if(r.values!=null&&r.values.length)for(let e=0;e<r.values.length;++e)Ee(r.values[e],t.uint32(10).fork()).ldelim();return t}function ZI(r,t){if(r.name!=null&&t.uint32(10).string(r.name),r.version!=null&&t.uint32(18).string(r.version),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(26).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(32).uint32(r.droppedAttributesCount),t}function tx(r,t){if(r.traceId!=null&&t.uint32(10).bytes(r.traceId),r.spanId!=null&&t.uint32(18).bytes(r.spanId),r.traceState!=null&&t.uint32(26).string(r.traceState),r.parentSpanId!=null&&t.uint32(34).bytes(r.parentSpanId),r.name!=null&&t.uint32(42).string(r.name),r.kind!=null&&t.uint32(48).int32(r.kind),r.startTimeUnixNano!=null&&t.uint32(57).fixed64(r.startTimeUnixNano),r.endTimeUnixNano!=null&&t.uint32(65).fixed64(r.endTimeUnixNano),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(74).fork()).ldelim();if(r.droppedAttributesCount!=null&&t.uint32(80).uint32(r.droppedAttributesCount),r.events!=null&&r.events.length)for(let e=0;e<r.events.length;++e)rx(r.events[e],t.uint32(90).fork()).ldelim();if(r.droppedEventsCount!=null&&t.uint32(96).uint32(r.droppedEventsCount),r.links!=null&&r.links.length)for(let e=0;e<r.links.length;++e)nx(r.links[e],t.uint32(106).fork()).ldelim();return r.droppedLinksCount!=null&&t.uint32(112).uint32(r.droppedLinksCount),r.status!=null&&ex(r.status,t.uint32(122).fork()).ldelim(),t}function ex(r,t){return r.message!=null&&t.uint32(18).string(r.message),r.code!=null&&t.uint32(24).int32(r.code),t}function rx(r,t){if(r.timeUnixNano!=null&&t.uint32(9).fixed64(r.timeUnixNano),r.name!=null&&t.uint32(18).string(r.name),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(26).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(32).uint32(r.droppedAttributesCount),t}function nx(r,t){if(r.traceId!=null&&t.uint32(10).bytes(r.traceId),r.spanId!=null&&t.uint32(18).bytes(r.spanId),r.traceState!=null&&t.uint32(26).string(r.traceState),r.attributes!=null&&r.attributes.length)for(let e=0;e<r.attributes.length;++e)Ee(r.attributes[e],t.uint32(34).fork()).ldelim();return r.droppedAttributesCount!=null&&t.uint32(40).uint32(r.droppedAttributesCount),t}var wt=class{constructor(t={}){this.impl=new as(t)}export(t,e){this.impl.export(t,e)}shutdown(){return this.impl.shutdown()}forceFlush(){return this.impl.forceFlush()}},as=class extends ae{convert(t){return(0,Fl.createExportTraceServiceRequest)(t)}toMessage(t){return{body:Gl(t),contentType:"application/x-protobuf",headers:{accept:"application/x-protobuf"}}}getDefaultUrl(t){return On(t)}};d();function Yl(r,t){return r.replace(/\{(?<temp1>[^{}]+)\}/g,(e,n)=>{let o=t[n];return o!==void 0?String(o):e})}var ue=class{constructor(t={}){this.instrumentationName="@vercel/otel/fetch";this.instrumentationVersion="1.0.0";this.config=t}getConfig(){return this.config}setConfig(){}setTracerProvider(t){this.tracerProvider=t}setMeterProvider(){}shouldIgnore(t,e){let n=this.config.ignoreUrls??[];if(e?.opentelemetry?.ignore!==void 0)return e.opentelemetry.ignore;if(n.length===0)return!1;let o=t.toString();return n.some(s=>typeof s=="string"?s==="*"?!0:o.startsWith(s):s.test(o))}shouldPropagate(t,e){let n=process.env.VERCEL_URL||process.env.NEXT_PUBLIC_VERCEL_URL||null,o=process.env.VERCEL_BRANCH_URL||process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL||null,s=this.config.propagateContextUrls??[],i=this.config.dontPropagateContextUrls??[];if(e?.opentelemetry?.propagateContext)return e.opentelemetry.propagateContext;let a=t.toString();return i.length>0&&i.some(_=>typeof _=="string"?_==="*"?!0:a.startsWith(_):_.test(a))?!1:n&&t.protocol==="https:"&&(t.host===n||t.host===o||t.host===ut()?.headers.host)||!n&&t.protocol==="http:"&&t.hostname==="localhost"?!0:s.some(_=>typeof _=="string"?_==="*"?!0:a.startsWith(_):_.test(a))}startSpan({tracer:t,url:e,fetchType:n,method:o="GET",name:s,attributes:i={}}){let a=this.config.resourceNameTemplate,_={[Ap]:o,[dp]:e.toString(),[dn]:e.host,[mp]:e.protocol.replace(":",""),[Rp]:e.hostname,[hp]:e.port},E=a?Yl(a,_):ix(e.toString()),T=s??`${n} ${o} ${e.toString()}`,l=c.context.active();return t.startSpan(T,{kind:c.SpanKind.CLIENT,attributes:{..._,"operation.name":`${n}.${o}`,"http.client.name":n,"resource.name":E,...i}},l)}instrumentHttp(t,e){let{tracerProvider:n}=this;if(!n)return;let o=n.getTracer(this.instrumentationName,this.instrumentationVersion),{attributesFromRequestHeaders:s,attributesFromResponseHeaders:i}=this.config,a=t.request,_=t.get,E=T=>(l,A,h)=>{let R,I={},x;if(typeof l=="string"||l instanceof URL?(R=new URL(l.toString()),typeof A=="function"?x=A:A&&typeof h=="function"?(I=A,x=h):A&&(I=A)):(I=l,typeof A=="function"&&(x=A),R=cx(I,e)),this.shouldIgnore(R))return T.apply(this,[R,I,x]);let M=this.startSpan({tracer:o,url:R,fetchType:"http",method:I.method||"GET"});if(!M.isRecording()||!ie(M.spanContext().traceFlags))return M.end(),T.apply(this,[R,I,x]);if(this.shouldPropagate(R)){let J=c.context.active(),Lt=c.trace.setSpan(J,M);c.propagation.inject(Lt,I.headers||{},sx)}s&&Cn(M,s,I.headers||{},Kl);try{let J=Date.now(),Lt=T.apply(this,[R,I,x]);return Lt.prependListener("response",w=>{let Jl=Date.now()-J;M.setAttribute("http.response_time",Jl),w.statusCode!==void 0?(M.setAttribute(Bo,w.statusCode),w.statusCode>=500&&Gt(M,`Status: ${w.statusCode}`)):Gt(M,"Response status code is undefined"),i&&Cn(M,i,w.headers,Kl),Lt.listenerCount("response")<=1&&w.resume(),w.on("end",()=>{let Fe,Un=w.statusCode;w.aborted&&!w.complete?Fe={code:c.SpanStatusCode.ERROR}:Un&&Un>=100&&Un<500?Fe={code:c.SpanStatusCode.UNSET}:Fe={code:c.SpanStatusCode.ERROR},M.setStatus(Fe),M.isRecording()&&(w.headers["content-length"]&&M.setAttribute(wo,w.headers["content-length"]),M.end())})}),Lt.on("error",w=>{M.isRecording()&&(Gt(M,w),M.end())}),Lt.on("close",()=>{M.isRecording()&&M.end()}),Lt}catch(J){throw Gt(M,J),M.end(),J}};t.request=E(a),t.get=E(_)}instrumentFetch(){let{tracerProvider:t}=this;if(!t)return;let e=t.getTracer(this.instrumentationName,this.instrumentationVersion),{attributesFromRequestHeaders:n,attributesFromResponseHeaders:o}=this.config;process.env.NEXT_OTEL_FETCH_DISABLED="1";let s=globalThis.fetch;this.originalFetch=s;let i=async(a,_)=>{let E=_;if(E?.next?.internal)return s(a,E);let T=new Request(a instanceof Request?a.clone():a,E),l=new URL(T.url);if(this.shouldIgnore(l,E))return s(a,E);let A=this.startSpan({tracer:e,url:l,fetchType:"fetch",method:T.method,name:E?.opentelemetry?.spanName,attributes:E?.opentelemetry?.attributes});if(!A.isRecording()||!ie(A.spanContext().traceFlags))return A.end(),s(a,E);if(this.shouldPropagate(l,E)){let h=c.context.active(),R=c.trace.setSpan(h,A);c.propagation.inject(R,T.headers,ox)}n&&Cn(A,n,T.headers,kl);try{let h=Date.now();E?.body&&E.body instanceof FormData&&T.headers.delete("content-type");let R=await s(a,{...E,headers:T.headers}),I=Date.now()-h;return A.setAttribute(Bo,R.status),A.setAttribute("http.response_time",I),o&&Cn(A,o,R.headers,kl),R.status>=500&&Gt(A,`Status: ${R.status} (${R.statusText})`),R.body?ax(R).then(x=>{A.isRecording()&&(A.setAttribute(wo,x),A.end())},x=>{A.isRecording()&&(Gt(A,x),A.end())}):A.end(),R}catch(h){throw Gt(A,h),A.end(),h}};globalThis.fetch=i}enable(){this.disable(),this.instrumentFetch();try{let t=Es("node:http"),e=Es("node:https");this.instrumentHttp(t,"http:"),this.instrumentHttp(e,"https:")}catch{}}disable(){this.originalFetch&&(globalThis.fetch=this.originalFetch)}},ox={set(r,t,e){r.set(t,e)}},kl={get(r,t){let e=r.get(t);if(e!==null)return e.includes(",")?e.split(",").map(n=>n.trimStart()):e},keys(r){let t=[];return r.forEach((e,n)=>{t.push(n)}),t}},sx={set(r,t,e){r[t.toLowerCase()]=e}},Kl={get(r,t){return r[t.toLowerCase()]},keys(r){return Object.keys(r)}};function ix(r){let t=r.indexOf("?");return t===-1?r:r.substring(0,t)}function ax(r){let t=0,n=r.clone().body?.getReader();if(!n)return Promise.resolve(0);let o=()=>n.read().then(({done:s,value:i})=>{if(!s)return t+=i.byteLength,o()});return o().then(()=>t)}function Gt(r,t){if(t instanceof Error)r.recordException(t),r.setStatus({code:c.SpanStatusCode.ERROR,message:t.message});else{let e=String(t);r.setStatus({code:c.SpanStatusCode.ERROR,message:e})}}function Cn(r,t,e,n){for(let[o,s]of Object.entries(t)){let i=n.get(e,s);i!==void 0&&r.setAttribute(o,i)}}function cx(r,t){if(r.socketPath)throw new Error("Cannot construct a network URL: options.socketPath is specified, indicating a Unix domain socket.");let e=r.protocol??t;e&&!e.endsWith(":")&&(e+=":");let n=r.hostname,o=r.port??r.defaultPort;if(!n&&r.host){let E=r.host.split(":");n=E[0];let T=E[1];if(E.length>1&&T&&o===void 0){let l=parseInt(T,10);isNaN(l)||(o=l)}}n||(n="localhost");let s;if(o!==void 0&&o!==""){let E=parseInt(String(o),10);isNaN(E)?s=e==="https:"?443:80:s=E}else s=e==="https:"?443:80;let i=r.path||"/",a=`${e}//${n}:${s}`,_=new URL(i,a);if(r.auth){let E=r.auth.split(":");_.username=decodeURIComponent(E[0]||""),E.length>1&&(_.password=decodeURIComponent(E[1]||""))}return _}d();var jl=O(P(),1),_x="00",cs="traceparent",_s="tracestate",He=class{fields(){return[cs,_s]}inject(t,e,n){let o=c.trace.getSpanContext(t);if(!o||(0,jl.isTracingSuppressed)(t)||!(0,c.isSpanContextValid)(o))return;let s=`${_x}-${o.traceId}-${o.spanId}-0${Number(o.traceFlags||0).toString(16)}`;n.set(e,cs,s),o.traceState&&n.set(e,_s,o.traceState.serialize())}extract(t,e,n){let o=n.get(e,cs);if(!o)return t;let s=Array.isArray(o)?o[0]:o;if(typeof s!="string")return t;let i=Ex(s);if(!i)return t;i.isRemote=!0;let a=n.get(e,_s);if(a){let _=Array.isArray(a)?a.join(","):a;i.traceState=(0,c.createTraceState)(typeof _=="string"?_:void 0)}return c.trace.setSpanContext(t,i)}};function Ex(r){let[t,e,n,o,s]=r.split("-");return!t||!e||!n||!o||t.length!==2||e.length!==32||n.length!==16||o.length!==2||t==="00"&&s?null:{traceId:e,spanId:n,traceFlags:parseInt(o,16)}}d();var Ln=class{fields(){return[]}inject(){}extract(t){let e=ut();if(!e?.telemetry)return c.diag.warn("@vercel/otel: Vercel telemetry extension not found."),t;let{rootSpanContext:n}=e.telemetry;return n?(c.diag.debug("@vercel/otel: Extracted root SpanContext from Vercel request context.",n),c.trace.setSpanContext(t,{...n,isRemote:!0,traceFlags:n.traceFlags||c.TraceFlags.SAMPLED})):t}};d();var In=O(P(),1),Wl=O(Wo(),1);var xn=class{export(t,e){let n=ut();if(!n?.telemetry){c.diag.warn("@vercel/otel: no telemetry context found"),e({code:In.ExportResultCode.SUCCESS,error:void 0});return}try{let o=Wl.JsonTraceSerializer.serializeRequest(t);if(!o)throw new Error("Failed to serialize spans");let s=JSON.parse(new TextDecoder().decode(o));n.telemetry.reportSpans(s),e({code:In.ExportResultCode.SUCCESS,error:void 0})}catch(o){e({code:In.ExportResultCode.FAILED,error:o instanceof Error?o:new Error(String(o))})}}shutdown(){return Promise.resolve()}forceFlush(){return Promise.resolve()}};function Q(r){let t=process.env[r];if(!(!t||t.trim()===""))return t}function ql(r){return Q(r)?.split(",").map(t=>t.trim()).filter(t=>t!=="")}var ux={ALL:c.DiagLogLevel.ALL,VERBOSE:c.DiagLogLevel.VERBOSE,DEBUG:c.DiagLogLevel.DEBUG,INFO:c.DiagLogLevel.INFO,WARN:c.DiagLogLevel.WARN,ERROR:c.DiagLogLevel.ERROR,NONE:c.DiagLogLevel.NONE},Dn=class{constructor(t={}){this.configuration=t}start(){let t=Tx(),e=this.configuration,n=process.env.NEXT_RUNTIME||"nodejs",o=!!t.OTEL_SDK_DISABLED;if(process.env.OTEL_LOG_LEVEL&&c.diag.setLogger(new c.DiagConsoleLogger,{logLevel:ux[process.env.OTEL_LOG_LEVEL.toUpperCase()]}),o)return;let s=e.idGenerator??new Rt;this.contextManager=Rx(e.contextManager);let i=t.OTEL_SERVICE_NAME||e.serviceName||"app",a=Re(mn({[Op]:i,"node.ci":process.env.CI?!0:void 0,"node.env":"production",env:process.env.VERCEL_ENV||process.env.NEXT_PUBLIC_VERCEL_ENV,"vercel.region":process.env.VERCEL_REGION,"vercel.runtime":n,"vercel.sha":process.env.VERCEL_GIT_COMMIT_SHA||process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA,"vercel.host":process.env.VERCEL_URL||process.env.NEXT_PUBLIC_VERCEL_URL||void 0,"vercel.branch_host":process.env.VERCEL_BRANCH_URL||process.env.NEXT_PUBLIC_VERCEL_BRANCH_URL||void 0,"vercel.deployment_id":process.env.VERCEL_DEPLOYMENT_ID||void 0,[gp]:process.env.VERCEL_DEPLOYMENT_ID,"vercel.project_id":process.env.VERCEL_PROJECT_ID||void 0,...e.attributes})),_=e.resourceDetectors??[Or];if(e.autoDetectResources??!0){let M=oo({detectors:_});a=a.merge(M)}let T=px(e.propagators,e,t),l=lx(e.traceSampler,t),A=Ax(e.spanProcessors,e,t);A.length===0&&c.diag.warn("@vercel/otel: No span processors configured. No spans will be exported.");let h=e.spanLimits,R=new ge({resource:a,idGenerator:s,sampler:l,spanLimits:h,spanProcessors:[new fn(A,e.attributesFromHeaders)]});if(c.trace.setGlobalTracerProvider(R),c.propagation.setGlobalPropagator(new Ct.CompositePropagator({propagators:T})),this.tracerProvider=R,e.logRecordProcessors){let x=new Ne({resource:a,processors:e.logRecordProcessors});this.loggerProvider=x,W.logs.setGlobalLoggerProvider(x)}if(e.metricReaders||e.views){let x=new ye({resource:a,views:e.views??[],readers:e.metricReaders??[]});c.metrics.setGlobalMeterProvider(x),this.meterProvider=x}let I=Sx(e.instrumentations,e.instrumentationConfig);this.disableInstrumentations=_o({instrumentations:I}),c.diag.info("@vercel/otel: started",i,n)}async shutdown(){let t=[];this.tracerProvider&&t.push(this.tracerProvider.shutdown()),this.loggerProvider&&t.push(this.loggerProvider.shutdown()),this.meterProvider&&t.push(this.meterProvider.shutdown()),c.diag.info("@vercel/otel: shutting down",t.length,process.env.NEXT_RUNTIME),await Promise.all(t),this.contextManager&&this.contextManager.disable();let{disableInstrumentations:e}=this;e&&e()}};function Tx(){return{OTEL_SDK_DISABLED:Q("OTEL_SDK_DISABLED"),OTEL_SERVICE_NAME:Q("OTEL_SERVICE_NAME"),OTEL_PROPAGATORS:ql("OTEL_PROPAGATORS"),OTEL_TRACES_SAMPLER:Q("OTEL_TRACES_SAMPLER"),OTEL_TRACES_SAMPLER_ARG:Q("OTEL_TRACES_SAMPLER_ARG"),OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:Q("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"),OTEL_EXPORTER_OTLP_TRACES_PROTOCOL:Q("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"),OTEL_EXPORTER_OTLP_PROTOCOL:Q("OTEL_EXPORTER_OTLP_PROTOCOL"),OTEL_EXPORTER_OTLP_ENDPOINT:Q("OTEL_EXPORTER_OTLP_ENDPOINT"),OTEL_EXPORTER_OTLP_HEADERS:Q("OTEL_EXPORTER_OTLP_HEADERS"),OTEL_EXPORTER_OTLP_TRACES_HEADERS:Q("OTEL_EXPORTER_OTLP_TRACES_HEADERS")}}function Sx(r,t){return(r??["auto"]).map(e=>e==="auto"?(c.diag.debug("@vercel/otel: Configure instrumentations: fetch",t?.fetch),[new ue(t?.fetch)]):e==="fetch"?(c.diag.debug("@vercel/otel: Configure instrumentations: fetch",t?.fetch),new ue(t?.fetch)):e).flat()}function px(r,t,e){let n=process.env.OTEL_PROPAGATORS&&e.OTEL_PROPAGATORS&&e.OTEL_PROPAGATORS.length>0?e.OTEL_PROPAGATORS:void 0;return(r??n??["auto"]).map(o=>{if(o==="none")return[];if(o==="auto"){let s=[];return s.push({name:"tracecontext",propagator:new He}),s.push({name:"baggage",propagator:new Ct.W3CBaggagePropagator}),s.push({name:"vercel-runtime",propagator:new Ln}),c.diag.debug(`@vercel/otel: Configure propagators: ${s.map(i=>i.name).join(", ")}`),s.map(i=>i.propagator)}if(o==="tracecontext")return c.diag.debug("@vercel/otel: Configure propagator: tracecontext"),new He;if(o==="baggage")return c.diag.debug("@vercel/otel: Configure propagator: baggage"),new Ct.W3CBaggagePropagator;if(typeof o=="string")throw new Error(`Unknown propagator: "${o}"`);return o}).flat()}var $l="always_on",Te=1;function lx(r,t){if(r&&typeof r!="string")return r;let e=r&&r!=="auto"?r:t.OTEL_TRACES_SAMPLER||$l;switch(c.diag.debug("@vercel/otel: Configure sampler: ",e),e){case"always_on":return new B;case"always_off":return new k;case"parentbased_always_on":return new K({root:new B});case"parentbased_always_off":return new K({root:new k});case"traceidratio":return new At(Xl(t));case"parentbased_traceidratio":return new K({root:new At(Xl(t))});default:return c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER value "${String(t.OTEL_TRACES_SAMPLER)} invalid, defaulting to ${$l}".`),new B}}function Xl(r){if(r.OTEL_TRACES_SAMPLER_ARG===void 0||r.OTEL_TRACES_SAMPLER_ARG==="")return c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${Te}.`),Te;c.diag.debug("@vercel/otel: Configure sampler probability: ",r.OTEL_TRACES_SAMPLER_ARG);let t=Number(r.OTEL_TRACES_SAMPLER_ARG);return isNaN(t)?(c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER_ARG=${r.OTEL_TRACES_SAMPLER_ARG} was given, but it is invalid, defaulting to ${Te}.`),Te):t<0||t>1?(c.diag.error(`@vercel/otel: OTEL_TRACES_SAMPLER_ARG=${r.OTEL_TRACES_SAMPLER_ARG} was given, but it is out of range ([0..1]), defaulting to ${Te}.`),Te):t}function Ax(r,t,e){return[...(r??["auto"]).flatMap(n=>{if(n==="auto"){let o=[new dt(new xn)];if(process.env.VERCEL_OTEL_ENDPOINTS){let s=process.env.VERCEL_OTEL_ENDPOINTS_PORT||"4318",i=process.env.VERCEL_OTEL_ENDPOINTS_PROTOCOL||"http/protobuf";c.diag.debug("@vercel/otel: Configure vercel otel collector on port: ",s,i);let a={url:`http://localhost:${s}/v1/traces`,headers:{}},_=i==="http/protobuf"?new wt(a):new ce(a);o.push(new dt(_))}else(!t.traceExporter||t.traceExporter==="auto"||e.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT||e.OTEL_EXPORTER_OTLP_ENDPOINT)&&o.push(new dt(dx(e)));return o}return n}).filter(hx),...t.traceExporter&&t.traceExporter!=="auto"?[new dt(t.traceExporter)]:[]]}function dx(r){let t=r.OTEL_EXPORTER_OTLP_TRACES_PROTOCOL??r.OTEL_EXPORTER_OTLP_PROTOCOL??"http/protobuf",e=fx(r),n={...r.OTEL_EXPORTER_OTLP_HEADERS?(0,Ct.parseKeyPairsIntoRecord)(r.OTEL_EXPORTER_OTLP_HEADERS):{},...r.OTEL_EXPORTER_OTLP_TRACES_HEADERS?(0,Ct.parseKeyPairsIntoRecord)(r.OTEL_EXPORTER_OTLP_TRACES_HEADERS):{}};switch(c.diag.debug("@vercel/otel: Configure trace exporter: ",t,e,`headers: ${Object.keys(n).join(",")||"<none>"}`),t){case"http/json":return new ce({url:e,headers:n});case"http/protobuf":return new wt({url:e,headers:n});default:return c.diag.warn(`@vercel/otel: Unsupported OTLP traces protocol: ${t}. Using http/protobuf.`),new wt}}var Ql="v1/traces",mx=`http://localhost:4318/${Ql}`;function fx(r){let t=r.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT;if(t&&typeof t=="string")return t;let e=r.OTEL_EXPORTER_OTLP_ENDPOINT;return e&&typeof e=="string"?`${e}/${Ql}`:mx}function hx(r){return r!=null}function Rx(r){if(r===void 0){c.diag.debug("@vercel/otel: Configure context manager: default");let t=new zl.AsyncLocalStorageContextManager;return t.enable(),c.context.setGlobalContextManager(t),t}return c.diag.debug("@vercel/otel: Configure context manager: from configuration"),r.enable(),c.context.setGlobalContextManager(r),r}function _B(r){let t;r?typeof r=="string"?t={serviceName:r}:t=r:t={},new Dn(t).start()}export{ue as FetchInstrumentation,ce as OTLPHttpJsonTraceExporter,wt as OTLPHttpProtoTraceExporter,_B as registerOTel};
|
|
17
17
|
//# sourceMappingURL=index.js.map
|