@utk09/ui-observability 0.9.1 → 0.9.2
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/CHANGELOG.md +27 -0
- package/README.md +75 -64
- package/dist/{batch-DEK4bv9N.js → batch-4xKzzSCj.js} +3 -3
- package/dist/{batch-DEK4bv9N.js.map → batch-4xKzzSCj.js.map} +1 -1
- package/dist/{batch-DEVFs28i.cjs → batch-cys7e53Q.cjs} +2 -2
- package/dist/{batch-DEVFs28i.cjs.map → batch-cys7e53Q.cjs.map} +1 -1
- package/dist/{bus-DNFvTkif.cjs → bus-B6vzPmQM.cjs} +2 -2
- package/dist/{bus-DNFvTkif.cjs.map → bus-B6vzPmQM.cjs.map} +1 -1
- package/dist/{bus-HVQ8E72V.js → bus-DrixwdiX.js} +11 -11
- package/dist/{bus-HVQ8E72V.js.map → bus-DrixwdiX.js.map} +1 -1
- package/dist/capture/network.d.ts +2 -0
- package/dist/capture/types.d.ts +3 -0
- package/dist/{console-C9Y639mn.js → console-B3vGRW5p.js} +3 -3
- package/dist/{console-C9Y639mn.js.map → console-B3vGRW5p.js.map} +1 -1
- package/dist/{console-DssDxq1B.cjs → console-ChfuJlf9.cjs} +2 -2
- package/dist/{console-DssDxq1B.cjs.map → console-ChfuJlf9.cjs.map} +1 -1
- package/dist/constants-Be83LICb.cjs +2 -0
- package/dist/constants-Be83LICb.cjs.map +1 -0
- package/dist/{constants-N99w84xy.js → constants-CQ_D7jIW.js} +39 -12
- package/dist/constants-CQ_D7jIW.js.map +1 -0
- package/dist/constants.d.ts +27 -1
- package/dist/core/diagnostics.d.ts +1 -1
- package/dist/core/meter.d.ts +45 -0
- package/dist/core/pipeline.d.ts +5 -12
- package/dist/core/record.d.ts +7 -0
- package/dist/core/runtime.d.ts +17 -0
- package/dist/core/sampling.d.ts +2 -0
- package/dist/core/sender.d.ts +2 -0
- package/dist/{errors-CQusIGWJ.js → errors-BGs5NOrw.js} +4 -4
- package/dist/{errors-CQusIGWJ.js.map → errors-BGs5NOrw.js.map} +1 -1
- package/dist/{errors-BTWuVnHZ.cjs → errors-BMJm7KZZ.cjs} +2 -2
- package/dist/{errors-BTWuVnHZ.cjs.map → errors-BMJm7KZZ.cjs.map} +1 -1
- package/dist/{identity-B1GDS1Tb.cjs → identity-DXyV86o-.cjs} +2 -2
- package/dist/{identity-B1GDS1Tb.cjs.map → identity-DXyV86o-.cjs.map} +1 -1
- package/dist/{identity-D4DPjTM9.js → identity-rpEyjvVg.js} +2 -2
- package/dist/{identity-D4DPjTM9.js.map → identity-rpEyjvVg.js.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +18 -0
- package/dist/index.js +520 -355
- package/dist/index.js.map +1 -1
- package/dist/{indexeddb-storage-ukzC82dm.cjs → indexeddb-storage-BXaPVPyG.cjs} +2 -2
- package/dist/{indexeddb-storage-ukzC82dm.cjs.map → indexeddb-storage-BXaPVPyG.cjs.map} +1 -1
- package/dist/{indexeddb-storage-B8SGUzSV.js → indexeddb-storage-Q9fDYlyn.js} +15 -15
- package/dist/{indexeddb-storage-B8SGUzSV.js.map → indexeddb-storage-Q9fDYlyn.js.map} +1 -1
- package/dist/{interactions-CnjfQgw3.js → interactions-B8zjCjga.js} +2 -2
- package/dist/{interactions-CnjfQgw3.js.map → interactions-B8zjCjga.js.map} +1 -1
- package/dist/{interactions-CcxrVzpg.cjs → interactions-BAGRmtrv.cjs} +2 -2
- package/dist/{interactions-CcxrVzpg.cjs.map → interactions-BAGRmtrv.cjs.map} +1 -1
- package/dist/{journey-DxlfdFJV.cjs → journey-BGSyy8Es.cjs} +2 -2
- package/dist/{journey-DxlfdFJV.cjs.map → journey-BGSyy8Es.cjs.map} +1 -1
- package/dist/{journey-DjvDzHyp.js → journey-_dQQ1eMP.js} +19 -19
- package/dist/{journey-DjvDzHyp.js.map → journey-_dQQ1eMP.js.map} +1 -1
- package/dist/library-request-BIG3Xpx3.cjs +2 -0
- package/dist/library-request-BIG3Xpx3.cjs.map +1 -0
- package/dist/library-request-DX6ev9oG.js +25 -0
- package/dist/library-request-DX6ev9oG.js.map +1 -0
- package/dist/{long-frames-CZk3XOkH.js → long-frames-B0tKuChx.js} +3 -3
- package/dist/{long-frames-CZk3XOkH.js.map → long-frames-B0tKuChx.js.map} +1 -1
- package/dist/{long-frames-BGik_Yhy.cjs → long-frames-Cq2LgNnp.cjs} +2 -2
- package/dist/{long-frames-BGik_Yhy.cjs.map → long-frames-Cq2LgNnp.cjs.map} +1 -1
- package/dist/models/config.d.ts +23 -0
- package/dist/models/metric.d.ts +50 -0
- package/dist/network-C6kJbW6K.cjs +2 -0
- package/dist/network-C6kJbW6K.cjs.map +1 -0
- package/dist/network-CMnEvGJB.js +211 -0
- package/dist/network-CMnEvGJB.js.map +1 -0
- package/dist/{platform-DW3GFIUE.cjs → platform-DNOJjpOm.cjs} +2 -2
- package/dist/{platform-DW3GFIUE.cjs.map → platform-DNOJjpOm.cjs.map} +1 -1
- package/dist/{platform-Cjts-8k8.js → platform-j0uMPwHi.js} +3 -3
- package/dist/{platform-Cjts-8k8.js.map → platform-j0uMPwHi.js.map} +1 -1
- package/dist/{remote-rules-ByS34k4e.cjs → remote-rules-DgoBJxZL.cjs} +2 -2
- package/dist/{remote-rules-ByS34k4e.cjs.map → remote-rules-DgoBJxZL.cjs.map} +1 -1
- package/dist/{remote-rules-M-XZ1xbe.js → remote-rules-UggoZqfP.js} +11 -11
- package/dist/{remote-rules-M-XZ1xbe.js.map → remote-rules-UggoZqfP.js.map} +1 -1
- package/dist/{sampling-BN3Oi6SV.js → sampling-BLMD8EGM.js} +28 -27
- package/dist/sampling-BLMD8EGM.js.map +1 -0
- package/dist/sampling-MthcVXXU.cjs +2 -0
- package/dist/sampling-MthcVXXU.cjs.map +1 -0
- package/dist/{sanitize-Dwj9JCkI.js → sanitize-BNwgPj_B.js} +2 -2
- package/dist/{sanitize-Dwj9JCkI.js.map → sanitize-BNwgPj_B.js.map} +1 -1
- package/dist/{sanitize-DKp5MRsa.cjs → sanitize-BqzPc4Jg.cjs} +2 -2
- package/dist/{sanitize-DKp5MRsa.cjs.map → sanitize-BqzPc4Jg.cjs.map} +1 -1
- package/dist/{sender-BBY0IcUo.js → sender--0_VzPbN.js} +408 -268
- package/dist/sender--0_VzPbN.js.map +1 -0
- package/dist/sender-SPGMqZjD.cjs +3 -0
- package/dist/sender-SPGMqZjD.cjs.map +1 -0
- package/dist/{storm-CKuaBp7i.cjs → storm-CTy1dfvs.cjs} +2 -2
- package/dist/{storm-CKuaBp7i.cjs.map → storm-CTy1dfvs.cjs.map} +1 -1
- package/dist/{storm-DhtL2eVr.js → storm-knaj4GUH.js} +2 -2
- package/dist/{storm-DhtL2eVr.js.map → storm-knaj4GUH.js.map} +1 -1
- package/dist/transport/custom-transport.d.ts +3 -2
- package/dist/transport/exit-flush.d.ts +13 -2
- package/dist/transport/http-transport.d.ts +6 -4
- package/dist/transport/retry-engine.d.ts +3 -1
- package/dist/transport/serializers/otlp-metrics.d.ts +3 -0
- package/dist/transport/serializers/otlp.d.ts +30 -0
- package/dist/transport/serializers/select.d.ts +20 -4
- package/dist/transport/status-transport.d.ts +19 -11
- package/dist/utils/library-request.d.ts +12 -0
- package/package.json +1 -1
- package/dist/constants-N99w84xy.js.map +0 -1
- package/dist/constants-X86IDwkC.cjs +0 -2
- package/dist/constants-X86IDwkC.cjs.map +0 -1
- package/dist/library-request-BZ1ekVtl.cjs +0 -2
- package/dist/library-request-BZ1ekVtl.cjs.map +0 -1
- package/dist/library-request-C8kc5YWv.js +0 -14
- package/dist/library-request-C8kc5YWv.js.map +0 -1
- package/dist/network-51iicpLl.js +0 -174
- package/dist/network-51iicpLl.js.map +0 -1
- package/dist/network-jBbjyAJP.cjs +0 -2
- package/dist/network-jBbjyAJP.cjs.map +0 -1
- package/dist/sampling-BN3Oi6SV.js.map +0 -1
- package/dist/sampling-b2ck5X98.cjs +0 -2
- package/dist/sampling-b2ck5X98.cjs.map +0 -1
- package/dist/sender-BBY0IcUo.js.map +0 -1
- package/dist/sender-BXoAZKum.cjs +0 -3
- package/dist/sender-BXoAZKum.cjs.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./error-like-gGRx2s36.cjs"),t=require("./platform-DNOJjpOm.cjs"),n=require("./library-request-BIG3Xpx3.cjs"),r=require("./patch-BX8KrPCT.cjs");function i(e,t){return typeof e==`string`&&t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}var a=1e3,o={name:`http.client.request.duration`,kind:`histogram`,unit:`s`,boundaries:[.005,.01,.025,.05,.075,.1,.25,.5,.75,1,2.5,5,7.5,10]};function s(t,n,r,i){let a=typeof location<`u`?location.href:void 0,o={"http.request.method":t,"server.address":new URL(n,a).hostname};if(r===0){let t=e.r(i)?i.name:``;return o[`error.type`]=t===``?`_OTHER`:t,o}return o[`http.response.status_code`]=r,r>=400&&(o[`error.type`]=String(r)),o}function c(){return XMLHttpRequest.prototype}function l(e){if(typeof e==`string`)return e;if(e instanceof URL)return e.href;if(typeof e==`object`&&e){let{url:t}=e;if(typeof t==`string`)return t}return String(e)}function u(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),f(n??`GET`)}function d(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function f(e){return typeof e==`string`?e.toUpperCase():String(e)}var p=class{ctx;name=`network`;installed=!1;restores=[];warnedTransport=!1;constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return n.t()||i(e,this.ctx.config.capture.ignoreUrls)}propagates(e){let t=this.ctx.config.capture.propagateTraceHeaderTo;if(t.length===0)return!1;let n=this.ctx.diagnostics.guard(`capture.header_failed`,`The library could not read the origin of a request URL. Only a RegExp target can match it.`,()=>new URL(e,location.href).origin);return t.some(t=>typeof t==`string`?t===n:t.test(e))}installFetch(){if(typeof globalThis.fetch!=`function`)return;let e=!0,t=(e,t)=>this.prepareFetch(e,t),n=(e,t,n,r,i)=>{this.record(e,t,n,r,i)},i=r.t(globalThis,`fetch`,r=>{let i=r.bind(globalThis);return async function(r,a){let o=e?t(r,a):void 0;if(!o)return i(r,a);let s=performance.now();try{let e=await i(o.input,o.init);return n(o.method,o.url,e.status,performance.now()-s,void 0),e}catch(e){throw n(o.method,o.url,0,performance.now()-s,e),e}}});this.restores.push(()=>{e=!1,i()})}prepareFetch(e,t){let n=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a fetch request. It sends the request unchanged.`,()=>{let n=l(e);if(!this.ignored(n))return{method:u(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,a={method:r,url:i,input:e,init:t};if(!n.propagate||d(e))return a;try{let n=Object.entries(this.ctx.tracing.headers());if(e instanceof Request){let t=new Headers(e.headers);for(let[e,r]of n)t.set(e,r);a.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,r]of n)e.set(t,r);a.init={...t,headers:e}}}catch(n){a.input=e,a.init=t,this.ctx.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:i},n)}return a}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,t=this.ctx,n=e=>this.ignored(e),i=e=>this.propagates(e),a=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},o=c(),s=r.t(o,`open`,n=>function(r,i,...a){e&&t.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:f(r),url:l(i),startedAt:0}}),n.apply(this,[r,i,...a])}),u=r.t(o,`send`,r=>function(...o){let s=e?this.__uiobs:void 0;s&&t.diagnostics.guard(`capture.record_failed`,`The library could not record ${s.method} ${s.url}.`,()=>{n(s.url)||(s.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{a(s.method,s.url,this.status,performance.now()-s.startedAt)}),i(s.url)&&m(this,s.url,t))}),r.apply(this,o)});this.restores.push(()=>{e=!1,s(),u()})}record(e,r,i,c,l){let u=this.ctx.config.capture.fullUrls?r:t.r(r);!this.warnedTransport&&n.n()&&(this.warnedTransport=!0,this.ctx.diagnostics.report(`capture.transport_request`,`Network capture saw ${e} ${u} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)),this.ctx.config.capture.httpMetrics&&this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record the duration of ${e} ${u}.`,()=>{let t=s(e,r,i,l);this.ctx.recordMetric(o,c/a,t)}),this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${e} ${u}.`,()=>{let t=Math.round(c);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${e} ${u} ${i===0?`failed`:String(i)}`,data:{durationMs:t}});let n={"http.request.method":e,"url.full":u,"http.response.status_code":i,"http.duration_ms":t};i===0?this.ctx.logger.error(`${e} ${u} failed`,l,n):i>=400?this.ctx.logger.warn(`${e} ${u} returned ${String(i)}`,n):this.ctx.logger.debug(`${e} ${u}`,n)})}};function m(e,t,n){try{for(let[t,r]of Object.entries(n.tracing.headers()))e.setRequestHeader(t,r)}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e)}}exports.NetworkCapture=p;
|
|
2
|
+
//# sourceMappingURL=network-C6kJbW6K.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-C6kJbW6K.cjs","names":["isErrorLike","isLibraryRequest","patch","stripUrlQuery","isTransportPending","require_error_like","require_platform","require_library_request","require_patch","matchesAny","url","patterns","pattern","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","durationMs","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","xhr"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n /** Adds a value to a counter or a histogram of the runtime. */\n recordMetric: (def: InstrumentDef, value: number, attributes?: MetricAttributes) => void;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":"gKAmHA,SAAgBS,EAAW,EAAc,EAAwC,CAM/E,OAJI,OAAOC,GAAQ,UAIZC,EAAS,KAAM,GACpB,OAAOC,GAAY,SAAWF,EAAI,SAASE,CAAO,EAAIA,EAAQ,KAAKF,CAAG,CACxE,CACF,CC7GA,IAAMG,EAAgB,IAMhBC,EAA+B,CACnC,KAAM,+BACN,KAAM,YACN,KAAM,IACN,WAAY,CAAC,KAAO,IAAM,KAAO,IAAM,KAAO,GAAK,IAAM,GAAK,IAAM,EAAG,IAAK,EAAG,IAAK,EAAE,CACxF,EAWA,SAASC,EACP,EACA,EACA,EACA,EACkB,CAElB,IAAMC,EAAO,OAAO,SAAa,IAAc,SAAS,KAAO,IAAA,GACzDC,EAA+B,CACnC,sBAAuBC,EACvB,iBAAkB,IAAI,IAAIR,EAAKM,CAAI,CAAC,CAAC,QACvC,EAEA,GAAIG,IAAW,EAAG,CAEhB,IAAMC,EAAOpB,EAAAA,EAAYqB,CAAK,EAAIA,EAAM,KAAO,GAE/C,MADA,GAAW,cAAgBD,IAAS,GAAK,SAAWA,EAC7CH,CACT,CAOA,M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{ r as t } from "./platform-j0uMPwHi.js";
|
|
3
|
+
import { n, t as r } from "./library-request-DX6ev9oG.js";
|
|
4
|
+
import { t as i } from "./patch-CCWfuEY7.js";
|
|
5
|
+
//#region src/capture/types.ts
|
|
6
|
+
function a(e, t) {
|
|
7
|
+
return typeof e == "string" && t.some((t) => typeof t == "string" ? e.includes(t) : t.test(e));
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/capture/network.ts
|
|
11
|
+
var o = 1e3, s = {
|
|
12
|
+
name: "http.client.request.duration",
|
|
13
|
+
kind: "histogram",
|
|
14
|
+
unit: "s",
|
|
15
|
+
boundaries: [
|
|
16
|
+
.005,
|
|
17
|
+
.01,
|
|
18
|
+
.025,
|
|
19
|
+
.05,
|
|
20
|
+
.075,
|
|
21
|
+
.1,
|
|
22
|
+
.25,
|
|
23
|
+
.5,
|
|
24
|
+
.75,
|
|
25
|
+
1,
|
|
26
|
+
2.5,
|
|
27
|
+
5,
|
|
28
|
+
7.5,
|
|
29
|
+
10
|
|
30
|
+
]
|
|
31
|
+
};
|
|
32
|
+
function c(t, n, r, i) {
|
|
33
|
+
let a = typeof location < "u" ? location.href : void 0, o = {
|
|
34
|
+
"http.request.method": t,
|
|
35
|
+
"server.address": new URL(n, a).hostname
|
|
36
|
+
};
|
|
37
|
+
if (r === 0) {
|
|
38
|
+
let t = e(i) ? i.name : "";
|
|
39
|
+
return o["error.type"] = t === "" ? "_OTHER" : t, o;
|
|
40
|
+
}
|
|
41
|
+
return o["http.response.status_code"] = r, r >= 400 && (o["error.type"] = String(r)), o;
|
|
42
|
+
}
|
|
43
|
+
function l() {
|
|
44
|
+
return XMLHttpRequest.prototype;
|
|
45
|
+
}
|
|
46
|
+
function u(e) {
|
|
47
|
+
if (typeof e == "string") return e;
|
|
48
|
+
if (e instanceof URL) return e.href;
|
|
49
|
+
if (typeof e == "object" && e) {
|
|
50
|
+
let { url: t } = e;
|
|
51
|
+
if (typeof t == "string") return t;
|
|
52
|
+
}
|
|
53
|
+
return String(e);
|
|
54
|
+
}
|
|
55
|
+
function d(e, t) {
|
|
56
|
+
let n = t?.method;
|
|
57
|
+
return n === void 0 && typeof e == "object" && e && (n = e.method), p(n ?? "GET");
|
|
58
|
+
}
|
|
59
|
+
function f(e) {
|
|
60
|
+
return typeof e == "object" && !(e instanceof URL) && !(e instanceof Request);
|
|
61
|
+
}
|
|
62
|
+
function p(e) {
|
|
63
|
+
return typeof e == "string" ? e.toUpperCase() : String(e);
|
|
64
|
+
}
|
|
65
|
+
var m = class {
|
|
66
|
+
ctx;
|
|
67
|
+
name = "network";
|
|
68
|
+
installed = !1;
|
|
69
|
+
restores = [];
|
|
70
|
+
warnedTransport = !1;
|
|
71
|
+
constructor(e) {
|
|
72
|
+
this.ctx = e;
|
|
73
|
+
}
|
|
74
|
+
install() {
|
|
75
|
+
this.installed || (this.installed = !0, this.ctx.config.capture.fetch && this.installFetch(), this.ctx.config.capture.xhr && this.installXhr());
|
|
76
|
+
}
|
|
77
|
+
uninstall() {
|
|
78
|
+
if (this.installed) {
|
|
79
|
+
this.installed = !1;
|
|
80
|
+
for (let e of this.restores.splice(0)) e();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
ignored(e) {
|
|
84
|
+
return r() || a(e, this.ctx.config.capture.ignoreUrls);
|
|
85
|
+
}
|
|
86
|
+
propagates(e) {
|
|
87
|
+
let t = this.ctx.config.capture.propagateTraceHeaderTo;
|
|
88
|
+
if (t.length === 0) return !1;
|
|
89
|
+
let n = this.ctx.diagnostics.guard("capture.header_failed", "The library could not read the origin of a request URL. Only a RegExp target can match it.", () => new URL(e, location.href).origin);
|
|
90
|
+
return t.some((t) => typeof t == "string" ? t === n : t.test(e));
|
|
91
|
+
}
|
|
92
|
+
installFetch() {
|
|
93
|
+
if (typeof globalThis.fetch != "function") return;
|
|
94
|
+
let e = !0, t = (e, t) => this.prepareFetch(e, t), n = (e, t, n, r, i) => {
|
|
95
|
+
this.record(e, t, n, r, i);
|
|
96
|
+
}, r = i(globalThis, "fetch", (r) => {
|
|
97
|
+
let i = r.bind(globalThis);
|
|
98
|
+
return async function(r, a) {
|
|
99
|
+
let o = e ? t(r, a) : void 0;
|
|
100
|
+
if (!o) return i(r, a);
|
|
101
|
+
let s = performance.now();
|
|
102
|
+
try {
|
|
103
|
+
let e = await i(o.input, o.init);
|
|
104
|
+
return n(o.method, o.url, e.status, performance.now() - s, void 0), e;
|
|
105
|
+
} catch (e) {
|
|
106
|
+
throw n(o.method, o.url, 0, performance.now() - s, e), e;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
this.restores.push(() => {
|
|
111
|
+
e = !1, r();
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
prepareFetch(e, t) {
|
|
115
|
+
let n = this.ctx.diagnostics.guard("capture.record_failed", "The library could not read a fetch request. It sends the request unchanged.", () => {
|
|
116
|
+
let n = u(e);
|
|
117
|
+
if (!this.ignored(n)) return {
|
|
118
|
+
method: d(e, t),
|
|
119
|
+
url: n,
|
|
120
|
+
propagate: this.propagates(n)
|
|
121
|
+
};
|
|
122
|
+
});
|
|
123
|
+
if (!n) return;
|
|
124
|
+
let { method: r, url: i } = n, a = {
|
|
125
|
+
method: r,
|
|
126
|
+
url: i,
|
|
127
|
+
input: e,
|
|
128
|
+
init: t
|
|
129
|
+
};
|
|
130
|
+
if (!n.propagate || f(e)) return a;
|
|
131
|
+
try {
|
|
132
|
+
let n = Object.entries(this.ctx.tracing.headers());
|
|
133
|
+
if (e instanceof Request) {
|
|
134
|
+
let t = new Headers(e.headers);
|
|
135
|
+
for (let [e, r] of n) t.set(e, r);
|
|
136
|
+
a.input = new Request(e, { headers: t });
|
|
137
|
+
} else {
|
|
138
|
+
let e = new Headers(t?.headers);
|
|
139
|
+
for (let [t, r] of n) e.set(t, r);
|
|
140
|
+
a.init = {
|
|
141
|
+
...t,
|
|
142
|
+
headers: e
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
} catch (n) {
|
|
146
|
+
a.input = e, a.init = t, this.ctx.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: i }, n);
|
|
147
|
+
}
|
|
148
|
+
return a;
|
|
149
|
+
}
|
|
150
|
+
installXhr() {
|
|
151
|
+
if (typeof XMLHttpRequest > "u") return;
|
|
152
|
+
let e = !0, t = this.ctx, n = (e) => this.ignored(e), r = (e) => this.propagates(e), a = (e, t, n, r) => {
|
|
153
|
+
this.record(e, t, n, r, void 0);
|
|
154
|
+
}, o = l(), s = i(o, "open", (n) => function(r, i, ...a) {
|
|
155
|
+
e && t.diagnostics.guard("capture.record_failed", "The library could not read an XMLHttpRequest. It does not record the request.", () => {
|
|
156
|
+
this.__uiobs = {
|
|
157
|
+
method: p(r),
|
|
158
|
+
url: u(i),
|
|
159
|
+
startedAt: 0
|
|
160
|
+
};
|
|
161
|
+
}), n.apply(this, [
|
|
162
|
+
r,
|
|
163
|
+
i,
|
|
164
|
+
...a
|
|
165
|
+
]);
|
|
166
|
+
}), c = i(o, "send", (i) => function(...o) {
|
|
167
|
+
let s = e ? this.__uiobs : void 0;
|
|
168
|
+
s && t.diagnostics.guard("capture.record_failed", `The library could not record ${s.method} ${s.url}.`, () => {
|
|
169
|
+
n(s.url) || (s.startedAt = performance.now(), this.addEventListener("loadend", () => {
|
|
170
|
+
a(s.method, s.url, this.status, performance.now() - s.startedAt);
|
|
171
|
+
}), r(s.url) && h(this, s.url, t));
|
|
172
|
+
}), i.apply(this, o);
|
|
173
|
+
});
|
|
174
|
+
this.restores.push(() => {
|
|
175
|
+
e = !1, s(), c();
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
record(e, r, i, a, l) {
|
|
179
|
+
let u = this.ctx.config.capture.fullUrls ? r : t(r);
|
|
180
|
+
!this.warnedTransport && n() && (this.warnedTransport = !0, this.ctx.diagnostics.report("capture.transport_request", `Network capture saw ${e} ${u} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`)), this.ctx.config.capture.httpMetrics && this.ctx.diagnostics.guard("capture.record_failed", `The library could not record the duration of ${e} ${u}.`, () => {
|
|
181
|
+
let t = c(e, r, i, l);
|
|
182
|
+
this.ctx.recordMetric(s, a / o, t);
|
|
183
|
+
}), this.ctx.diagnostics.guard("capture.record_failed", `The library could not record ${e} ${u}.`, () => {
|
|
184
|
+
let t = Math.round(a);
|
|
185
|
+
this.ctx.breadcrumbs.push({
|
|
186
|
+
t: Date.now(),
|
|
187
|
+
category: "http",
|
|
188
|
+
message: `${e} ${u} ${i === 0 ? "failed" : String(i)}`,
|
|
189
|
+
data: { durationMs: t }
|
|
190
|
+
});
|
|
191
|
+
let n = {
|
|
192
|
+
"http.request.method": e,
|
|
193
|
+
"url.full": u,
|
|
194
|
+
"http.response.status_code": i,
|
|
195
|
+
"http.duration_ms": t
|
|
196
|
+
};
|
|
197
|
+
i === 0 ? this.ctx.logger.error(`${e} ${u} failed`, l, n) : i >= 400 ? this.ctx.logger.warn(`${e} ${u} returned ${String(i)}`, n) : this.ctx.logger.debug(`${e} ${u}`, n);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
function h(e, t, n) {
|
|
202
|
+
try {
|
|
203
|
+
for (let [t, r] of Object.entries(n.tracing.headers())) e.setRequestHeader(t, r);
|
|
204
|
+
} catch (e) {
|
|
205
|
+
n.diagnostics.report("capture.header_failed", "The library could not add the traceparent header. It sends the request unchanged.", { url: t }, e);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
//#endregion
|
|
209
|
+
export { m as NetworkCapture };
|
|
210
|
+
|
|
211
|
+
//# sourceMappingURL=network-CMnEvGJB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network-CMnEvGJB.js","names":["isErrorLike","stripUrlQuery","isLibraryRequest","patch","matchesAny","url","patterns","pattern","MS_PER_SECOND","HTTP_DURATION","durationAttributes","base","attributes","method","status","name","error","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","durationMs","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","isTransportPending","rounded"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n /** Adds a value to a counter or a histogram of the runtime. */\n recordMetric: (def: InstrumentDef, value: number, attributes?: MetricAttributes) => void;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport type { InstrumentDef, MetricAttributes } from \"../models/metric\";\nimport { isErrorLike } from \"../utils/error-like\";\nimport { isLibraryRequest, isTransportPending } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Milliseconds in one second. The histogram is in seconds, as the OpenTelemetry name gives. */\nconst MS_PER_SECOND = 1000;\n\n/**\n * The HTTP client duration histogram of the OpenTelemetry semantic conventions. Its boundaries\n * are the ones that the conventions advise.\n */\nconst HTTP_DURATION: InstrumentDef = {\n name: \"http.client.request.duration\",\n kind: \"histogram\",\n unit: \"s\",\n boundaries: [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10],\n};\n\n/**\n * Gives the low-cardinality attributes of one request. The path and the query stay out. Each\n * value of an attribute makes a new series in the backend.\n * @param method Uppercase HTTP method.\n * @param url Request URL.\n * @param status HTTP status code, or 0 when no response came.\n * @param error Failure of a request without a response.\n * @returns The attribute set.\n */\nfunction durationAttributes(\n method: string,\n url: string,\n status: number,\n error: unknown,\n): MetricAttributes {\n // A relative URL needs the page URL as its base. A worker has a location too.\n const base = typeof location !== \"undefined\" ? location.href : undefined;\n const attributes: MetricAttributes = {\n \"http.request.method\": method,\n \"server.address\": new URL(url, base).hostname,\n };\n\n if (status === 0) {\n // A request without a response has the type of its error, for example TypeError.\n const name = isErrorLike(error) ? error.name : \"\";\n attributes[\"error.type\"] = name === \"\" ? \"_OTHER\" : name;\n return attributes;\n }\n\n attributes[\"http.response.status_code\"] = status;\n if (status >= 400) {\n attributes[\"error.type\"] = String(status);\n }\n\n return attributes;\n}\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /** True after the report of a request during a custom transport call. It reports one time. */\n private warnedTransport = false;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // A request of the transport after an await records a value. That value causes the next send.\n if (!this.warnedTransport && isTransportPending()) {\n this.warnedTransport = true;\n this.ctx.diagnostics.report(\n \"capture.transport_request\",\n `Network capture saw ${method} ${url} during a custom transport call. If the transport sends this request, add its URL to capture.ignoreUrls.`,\n );\n }\n\n // The histogram has its own guard. A URL that does not parse must not stop the record.\n if (this.ctx.config.capture.httpMetrics) {\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record the duration of ${method} ${url}.`,\n () => {\n const attributes = durationAttributes(method, target, status, error);\n this.ctx.recordMetric(HTTP_DURATION, durationMs / MS_PER_SECOND, attributes);\n },\n );\n }\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":";;;;;AAmHA,SAAgBI,EAAW,GAAc,GAAwC;CAM/E,OAJI,OAAOC,KAAQ,YAIZC,EAAS,MAAM,MACpB,OAAOC,KAAY,WAAWF,EAAI,SAASE,CAAO,IAAIA,EAAQ,KAAKF,CAAG,CACxE;AACF;;;AC7GA,IAAMG,IAAgB,KAMhBC,IAA+B;CACnC,MAAM;CACN,MAAM;CACN,MAAM;CACN,YAAY;EAAC;EAAO;EAAM;EAAO;EAAM;EAAO;EAAK;EAAM;EAAK;EAAM;EAAG;EAAK;EAAG;EAAK;CAAE;AACxF;AAWA,SAASC,EACP,GACA,GACA,GACA,GACkB;CAElB,IAAMC,IAAO,OAAO,WAAa,MAAc,SAAS,OAAO,KAAA,GACzDC,IAA+B;EACnC,uBAAuBC;EACvB,kBAAkB,IAAI,IAAIR,GAAKM,CAAI,CAAC,CAAC;CACvC;CAEA,IAAIG,MAAW,GAAG;EAEh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ACd,yBACA,qFACA,EAAE,OAAI,GACNA,CACF;CACF;AACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=platform-
|
|
1
|
+
const e=require("./constants-Be83LICb.cjs");var t=null;function n(e,t){let n=e[t];return n!==void 0&&e instanceof n}function r(r){if(t)return t;let o=globalThis,s=o.navigator?.userAgent??``,c=`browser`,l,u,d=!1,f=o.fin?.me;return n(o,`ServiceWorkerGlobalScope`)?(c=`service_worker`,d=!0):n(o,`SharedWorkerGlobalScope`)?(c=`shared_worker`,d=!0):n(o,`WorkerGlobalScope`)?(c=`web_worker`,d=!0):f===void 0?o.Capacitor!==void 0||o.Ionic!==void 0?c=`ionic`:o.cordova!==void 0||i(s)?c=`mobile_webview`:typeof document>`u`&&typeof process<`u`&&(c=`node`):(c=e.Et.test(s)?`openfin`:`openfin_web`,r.guard(`openfin.unavailable`,`The library could not read fin.me.identity.`,()=>{let e=f.identity;l=e?.uuid,u=e?.name})),t={platform:c,openfinUuid:l,openfinName:u,userAgent:s,isWorker:d,isTopLevelDocument:a(r)},t}function i(t){return e.t.test(t)?!0:(e.at.test(t)||e.gt.test(t)&&e.xt.test(t))&&t.includes(`AppleWebKit`)&&!t.includes(`Safari/`)}function a(e){if(typeof window>`u`)return!1;try{return window.self===window.top}catch{return e.count(`platform.api_blocked`),!1}}function o(e){try{return typeof location<`u`?location.href:``}catch{return e.count(`platform.api_blocked`),``}}function s(e){let t=e.search(/[?#]/);return t===-1?e:e.slice(0,t)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
|
|
2
|
+
//# sourceMappingURL=platform-DNOJjpOm.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-
|
|
1
|
+
{"version":3,"file":"platform-DNOJjpOm.cjs","names":["OPENFIN_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","MOBILE_UA_PATTERN","require_constants","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":"4CAiDA,IAAIM,EAAkC,KAWtC,SAASC,EAAc,EAAW,EAAuB,CACvD,IAAMC,EAAQC,EAAEC,GAIhB,OAHIF,IAAU,IAAA,IAGPC,aAAcD,CACvB,CAYA,SAAgBG,EAAe,EAA4C,CACzE,GAAIL,EACF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EAC3D,MAAQ,CAGN,OADAH,EAAY,MAAM,sBAAsB,EACjC,EACT,CACF,CAQA,SAAgBI,EAAc,EAAqB,CACjD,IAAMC,EAAMC,EAAI,OAAO,MAAM,EAE7B,OAAOD,IAAQ,GAAKC,EAAMA,EAAI,MAAM,EAAGD,CAAG,CAC5C"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Et as e, at as t, gt as n, t as r, xt as i } from "./constants-CQ_D7jIW.js";
|
|
2
2
|
//#region src/utils/platform.ts
|
|
3
3
|
var a = null;
|
|
4
4
|
function o(e, t) {
|
|
@@ -21,7 +21,7 @@ function s(t) {
|
|
|
21
21
|
}, a;
|
|
22
22
|
}
|
|
23
23
|
function c(e) {
|
|
24
|
-
return
|
|
24
|
+
return r.test(e) ? !0 : (t.test(e) || n.test(e) && i.test(e)) && e.includes("AppleWebKit") && !e.includes("Safari/");
|
|
25
25
|
}
|
|
26
26
|
function l(e) {
|
|
27
27
|
if (typeof window > "u") return !1;
|
|
@@ -45,4 +45,4 @@ function d(e) {
|
|
|
45
45
|
//#endregion
|
|
46
46
|
export { s as n, d as r, u as t };
|
|
47
47
|
|
|
48
|
-
//# sourceMappingURL=platform-
|
|
48
|
+
//# sourceMappingURL=platform-j0uMPwHi.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"platform-
|
|
1
|
+
{"version":3,"file":"platform-j0uMPwHi.js","names":["OPENFIN_UA_PATTERN","IOS_DEVICE_UA_PATTERN","MACINTOSH_UA_PATTERN","ANDROID_WEBVIEW_UA_PATTERN","MOBILE_UA_PATTERN","cached","isGlobalScope","scope","g","name","detectPlatform","ua","platform","openfinUuid","openfinName","isWorker","finMe","isWebView","diagnostics","identity","isTopLevel","currentUrl","stripUrlQuery","cut","url"],"sources":["../src/utils/platform.ts"],"sourcesContent":["// src/utils/platform.ts\n//\n// Detects host platform capabilities, OpenFin container metadata, and worker\n// execution realms. The module caches the result. The result does not change during\n// the life of a realm. A webview is also a browser. Test for a webview first.\n\nimport {\n ANDROID_WEBVIEW_UA_PATTERN,\n IOS_DEVICE_UA_PATTERN,\n MACINTOSH_UA_PATTERN,\n MOBILE_UA_PATTERN,\n OPENFIN_UA_PATTERN,\n SAFARI_UA_TOKEN,\n WEBKIT_UA_TOKEN,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\n\n/** Host runtime environment classification attached to resource attributes. */\nexport type PlatformType =\n | \"openfin\"\n | \"openfin_web\"\n | \"browser\"\n | \"mobile_webview\"\n | \"ionic\"\n | \"web_worker\"\n | \"shared_worker\"\n | \"service_worker\"\n | \"node\";\n\n/** Host environment and runtime container metadata resolved at startup. */\nexport interface PlatformMetadata {\n /** Detected platform runtime classification. */\n platform: PlatformType;\n /** OpenFin application UUID if running inside an OpenFin container. */\n openfinUuid?: string;\n /** OpenFin window or view identifier. */\n openfinName?: string;\n /** Raw navigator user agent string or empty string if unavailable. */\n userAgent: string;\n /** True if the code runs in a worker realm. */\n isWorker: boolean;\n /** True if this context is the top-level document rather than an iframe. */\n isTopLevelDocument: boolean;\n}\n\n/** Indexed globalThis type for probing runtime globals. */\ntype Global = typeof globalThis & Record<string, unknown>;\n\n/** Cached platform metadata instance. */\nlet cached: PlatformMetadata | null = null;\n\n/** Abstract constructor type for global scope prototype checks. */\ntype ScopeConstructor = abstract new (...args: never[]) => object;\n\n/**\n * Tests if globalThis is an instance of a specified global scope constructor.\n * @param g Global scope object.\n * @param name Scope constructor name to check.\n * @returns True if globalThis inherits from the named scope constructor.\n */\nfunction isGlobalScope(g: Global, name: string): boolean {\n const scope = g[name];\n if (scope === undefined) {\n return false;\n }\n return g instanceof (scope as ScopeConstructor);\n}\n\n/** Structural interface for OpenFin identity inspection. */\ninterface FinLike {\n me?: { identity?: { uuid?: string; name?: string } };\n}\n\n/**\n * Detects and caches host platform metadata for the active realm.\n * @param diagnostics Diagnostics reporter.\n * @returns Detected PlatformMetadata.\n */\nexport function detectPlatform(diagnostics: Diagnostics): PlatformMetadata {\n if (cached) {\n return cached;\n }\n const g = globalThis as Global;\n\n const ua = (g.navigator as Navigator | undefined)?.userAgent ?? \"\";\n let platform: PlatformType = \"browser\";\n let openfinUuid: string | undefined;\n let openfinName: string | undefined;\n let isWorker = false;\n\n const finMe = (g.fin as FinLike | undefined)?.me;\n\n if (isGlobalScope(g, \"ServiceWorkerGlobalScope\")) {\n platform = \"service_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"SharedWorkerGlobalScope\")) {\n platform = \"shared_worker\";\n isWorker = true;\n } else if (isGlobalScope(g, \"WorkerGlobalScope\")) {\n platform = \"web_worker\";\n isWorker = true;\n } else if (finMe !== undefined) {\n platform = OPENFIN_UA_PATTERN.test(ua) ? \"openfin\" : \"openfin_web\";\n diagnostics.guard(\"openfin.unavailable\", \"The library could not read fin.me.identity.\", () => {\n const identity = finMe.identity;\n openfinUuid = identity?.uuid;\n openfinName = identity?.name;\n });\n } else if (g.Capacitor !== undefined || g.Ionic !== undefined) {\n platform = \"ionic\";\n } else if (g.cordova !== undefined || isWebView(ua)) {\n platform = \"mobile_webview\";\n } else if (typeof document === \"undefined\" && typeof process !== \"undefined\") {\n platform = \"node\";\n }\n\n cached = {\n platform,\n openfinUuid,\n openfinName,\n userAgent: ua,\n isWorker,\n isTopLevelDocument: isTopLevel(diagnostics),\n };\n return cached;\n}\n\n/**\n * Tests if a user agent string represents an embedded mobile webview.\n * @param ua User agent string.\n * @returns True if user agent matches Android or iOS webview signatures.\n */\nfunction isWebView(ua: string): boolean {\n if (ANDROID_WEBVIEW_UA_PATTERN.test(ua)) {\n return true;\n }\n const ios =\n IOS_DEVICE_UA_PATTERN.test(ua) || (MACINTOSH_UA_PATTERN.test(ua) && MOBILE_UA_PATTERN.test(ua));\n return ios && ua.includes(WEBKIT_UA_TOKEN) && !ua.includes(SAFARI_UA_TOKEN);\n}\n\n/**\n * Tests if the current window is the top-level browsing context.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of window.top.\n * @returns True if top-level, false if framed or inaccessible due to cross-origin boundaries.\n */\nexport function isTopLevel(diagnostics: Diagnostics): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n return window.self === window.top;\n } catch {\n // A cross-origin parent blocks the read. That proves a frame. Count it. Do not report it.\n diagnostics.count(\"platform.api_blocked\");\n return false;\n }\n}\n\n/**\n * Retrieves the current document URL without caching.\n * @param diagnostics Diagnostics reporter. It counts a blocked read of location.href.\n * @returns Current location.href or empty string.\n */\nexport function currentUrl(diagnostics: Diagnostics): string {\n try {\n return typeof location !== \"undefined\" ? location.href : \"\";\n } catch {\n // A sandbox can block the read. Count the fault. A report on each record is noise.\n diagnostics.count(\"platform.api_blocked\");\n return \"\";\n }\n}\n\n/**\n * Drops the query string and fragment from a URL.\n * It cuts the string and does not parse a URL. A relative request target has no base URL.\n * @param url Absolute or relative URL.\n * @returns The URL up to the first \"?\" or \"#\".\n */\nexport function stripUrlQuery(url: string): string {\n const cut = url.search(/[?#]/);\n\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n/** Resets the cached platform metadata for testing. */\nexport function resetPlatformCache(): void {\n cached = null;\n}\n"],"mappings":";;AAiDA,IAAIK,IAAkC;AAWtC,SAASC,EAAc,GAAW,GAAuB;CACvD,IAAMC,IAAQC,EAAEC;CAIhB,OAHIF,MAAU,KAAA,KAGPC,aAAcD;AACvB;AAYA,SAAgBG,EAAe,GAA4C;CACzE,IAAIL,GACF,OAAOA;CAET,IAAMG,IAAI,YAEJG,IAAMH,EAAE,WAAqC,aAAa,IAC5DI,IAAyB,WACzBC,GACAC,GACAC,IAAW,IAETC,IAASR,EAAE,KAA6B;CAkC9C,OAhCIF,EAAcE,GAAG,0BAA0B,KAC7C,IAAW,kBACX,IAAW,MACFF,EAAcE,GAAG,yBAAyB,KACnD,IAAW,iBACX,IAAW,MACFF,EAAcE,GAAG,mBAAmB,KAC7C,IAAW,cACX,IAAW,MACFQ,MAAU,KAAA,IAOVR,EAAE,cAAc,KAAA,KAAaA,EAAE,UAAU,KAAA,IAClD,IAAW,UACFA,EAAE,YAAY,KAAA,KAAaS,EAAUN,CAAE,IAChD,IAAW,mBACF,OAAO,WAAa,OAAe,OAAO,UAAY,QAC/D,IAAW,WAXX,IAAWX,EAAmB,KAAKW,CAAE,IAAI,YAAY,eACrDO,EAAY,MAAM,uBAAuB,qDAAqD;EAC5F,IAAMC,IAAWH,EAAM;EAEvB,AADA,IAAcG,GAAU,MACxB,IAAcA,GAAU;CAC1B,CAAC,IASH,IAAS;EACP;EACA;EACA;EACA,WAAWR;EACX;EACA,oBAAoBS,EAAWF,CAAW;CAC5C,GACOb;AACT;AAOA,SAASY,EAAU,GAAqB;CAMtC,OALId,EAA2B,KAAKQ,CAAE,IAC7B,MAGPV,EAAsB,KAAKU,CAAE,KAAMT,EAAqB,KAAKS,CAAE,KAAKP,EAAkB,KAAKO,CAAE,MACjFA,EAAG,SAAA,aAAwB,KAAK,CAACA,EAAG,SAAA,SAAwB;AAC5E;AAOA,SAAgBS,EAAW,GAAmC;CAC5D,IAAI,OAAO,SAAW,KACpB,OAAO;CAET,IAAI;EACF,OAAO,OAAO,SAAS,OAAO;CAChC,QAAQ;EAGN,OADAF,EAAY,MAAM,sBAAsB,GACjC;CACT;AACF;AAOA,SAAgBG,EAAW,GAAkC;CAC3D,IAAI;EACF,OAAO,OAAO,WAAa,MAAc,SAAS,OAAO;CAC3D,QAAQ;EAGN,OADAH,EAAY,MAAM,sBAAsB,GACjC;CACT;AACF;AAQA,SAAgBI,EAAc,GAAqB;CACjD,IAAMC,IAAMC,EAAI,OAAO,MAAM;CAE7B,OAAOD,MAAQ,KAAKC,IAAMA,EAAI,MAAM,GAAGD,CAAG;AAC5C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./constants-
|
|
2
|
-
//# sourceMappingURL=remote-rules-
|
|
1
|
+
const e=require("./constants-Be83LICb.cjs");var t=class{config;rules=null;receivedAt=0;until=0;constructor(e){this.config=e}apply(e){if(!e){this.rules=null;return}let t=Date.now();this.rules=e.rules,this.receivedAt=t,this.until=t+e.ttlMs}current(){if(!this.rules)return null;let e=Date.now();return!this.config.sampling.remote||e<this.receivedAt||e>=this.until?(this.rules=null,null):this.rules}minLevel(){let{minLevel:t}=this.config,n=this.current()?.minLevel;return n!==void 0&&e.ut[n]<e.ut[t]?n:t}wire(){let e=this.current();return e?{...e,v:1,ttlMs:this.until-Date.now()}:null}},n=class extends Error{};function r(e){return typeof e==`number`&&e>=0&&e<=1}function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(t){if(t.length>4096)throw new n(`The header is longer than ${String(e.jt)} characters.`);try{return JSON.parse(t)}catch{throw new n(`The header is not valid JSON.`)}}function o(e){if(e===void 0)return{};let t=`rates must be an object with at most 100 rates from 0 to 1.`;if(!i(e))throw new n(t);let a=Object.entries(e);if(a.length>100||!a.every(([,e])=>r(e)))throw new n(t);return Object.fromEntries(a)}function s(t){if(!i(t))throw new n(`The rules must be an object.`);if(t.v!==1)throw new n(`The version must be 1.`);let{ttlMs:a,defaultRate:s,minLevel:c}=t;if(typeof a!=`number`||!(a>0&&a<=36e5))throw new n(`ttlMs must be a number more than 0 and at most ${String(e.Mt)}.`);if(s!==void 0&&!r(s))throw new n(`defaultRate must be a number from 0 to 1.`);if(c!==void 0&&!(typeof c==`string`&&Object.hasOwn(e.ut,c)))throw new n(`minLevel must be a level name, for example DEBUG.`);let l={rates:o(t.rates)};return s!==void 0&&(l.defaultRate=s),c!==void 0&&(l.minLevel=c),{rules:l,ttlMs:a}}function c(e,t){try{return s(typeof e==`string`?a(e):e)}catch(e){let r=e instanceof n?` ${e.message}`:``;return t.report(`config.invalid`,`The library ignores the sampling rules from the server.${r}`,void 0,e),null}}function l(e,n,r){r&&(e.sampling??=new t(n)),e.sampling?.apply(r)}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return l}});
|
|
2
|
+
//# sourceMappingURL=remote-rules-DgoBJxZL.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-rules-ByS34k4e.cjs","names":["LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","require_constants","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends.\n * @returns The remote level if it is lower than `minLevel`. If not, `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Tests if a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":"4CA2CA,IAAaK,EAAb,KAA4B,CAaG,OAX7B,MAAoC,KAGpC,WAAqB,EAGrB,MAAgB,EAKhB,YAAY,EAAyC,CAAxB,KAAA,OAAAC,CAAyB,CAMtD,MAAM,EAAmC,CACvC,GAAI,CAACC,EAAQ,CACX,KAAK,MAAQ,KACb,MACF,CAEA,IAAMC,EAAM,KAAK,IAAI,EAErB,KAAK,MAAQD,EAAO,MACpB,KAAK,WAAaC,EAClB,KAAK,MAAQA,EAAMD,EAAO,KAC5B,CAMA,SAA8B,CAC5B,GAAI,CAAC,KAAK,MACR,OAAO,KAGT,IAAMC,EAAM,KAAK,IAAI,EASrB,MALI,CAAC,KAAK,OAAO,SAAS,QAAUA,EAAM,KAAK,YAAcA,GAAO,KAAK,OACvE,KAAK,MAAQ,KACN,MAGF,KAAK,KACd,CAMA,UAAqB,CACnB,GAAM,CAAE,YAAa,KAAK,OACpBC,EAAS,KAAK,QAAQ,CAAC,EAAE,SAE/B,OAAOA,IAAW,IAAA,IAAaT,EAAAA,GAAYS,GAAUT,EAAAA,GAAYU,GAAYD,EAASC,CACxF,CAMA,MAA0B,CACxB,IAAMC,EAAQ,KAAK,QAAQ,EAM3B,OAJKA,EAIE,CAAE,GAAGA,EAAO,EAAA,EAA4B,MAAO,KAAK,MAAQ,KAAK,IAAI,CAAE,EAHrE,IAIX,CACF,EC9FMC,EAAN,cAAwB,KAAM,CAAC,EAO/B,SAASC,EAAO,EAAiC,CAC/C,OAAO,OAAOC,GAAU,UAAYA,GAAA,GAA8BA,GAAA,CACpE,CAOA,SAASC,EAA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,CAAE,EAU3D,OARIU,IAAgB,IAAA,KAClB,EAAM,YAAcA,GAGlBd,IAAa,IAAA,KACf,EAAM,SAAWA,GAGZ,CAAE,QAAO,OAAM,CACxB,CAQA,SAAgBe,EAAiB,EAAc,EAA+C,CAC5F,GAAI,CACF,OAAOH,EAAU,OAAOI,GAAQ,SAAWV,EAAUU,CAAG,EAAIA,CAAG,CACjE,OAASC,EAAO,CACd,IAAMC,EAASD,aAAiBf,EAAY,IAAIe,EAAM,UAAY,GAQlE,OANAE,EAAY,OACV,iBACA,0DAA0DD,IAC1D,IAAA,GACAD,CACF,EACO,IACT,CACF,CAQA,SAAgBG,EACd,EACA,EACA,EACM,CACFvB,IACF,EAAK,WAAa,IAAIF,EAAeC,CAAM,GAG7CyB,EAAK,UAAU,MAAMxB,CAAM,CAC7B"}
|
|
1
|
+
{"version":3,"file":"remote-rules-DgoBJxZL.cjs","names":["LEVEL_ORDER","REMOTE_SAMPLING_MAX_CHARS","REMOTE_SAMPLING_MAX_TTL_MS","LEVEL_ORDER","require_constants","RemoteSampling","config","update","now","remote","minLevel","rules","RuleError","isRate","value","isObject","parseText","text","readRates","rule","entries","rate","readRules","ttlMs","defaultRate","parseRemoteRules","raw","error","reason","diagnostics","applyRemote","slot"],"sources":["../src/core/remote-sampling.ts","../src/core/remote-rules.ts"],"sourcesContent":["// src/core/remote-sampling.ts\n//\n// Holds the sampling rules from the ingest server for their TTL. The rules are an overlay.\n// The library does not write them into the config. A later configure() and the TTL then stay simple.\n// Only the lazy chunks import this class. The main bundle imports the types.\n\nimport { LEVEL_ORDER, REMOTE_SAMPLING_VERSION } from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\n\n/** Sampling rules from the ingest server, after validation. */\nexport interface RemoteRules {\n /** Rate when no namespace rate matches. Without it, the config rate applies. */\n defaultRate?: number;\n /** Rate for each namespace prefix. They apply over the config rates. */\n rates: Record<string, number>;\n /** Lowest level that the library sends. It can only lower `minLevel`. */\n minLevel?: LogLevel;\n}\n\n/** Rules and their TTL, after validation. */\nexport interface RemoteUpdate {\n /** Validated rules. */\n rules: RemoteRules;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Rules in the shape of the header. A context sends them to a forwarder over the bus. */\nexport interface RemoteWire extends RemoteRules {\n /** Rules version. */\n v: typeof REMOTE_SAMPLING_VERSION;\n /** Time that the rules stay in force, in milliseconds. */\n ttlMs: number;\n}\n\n/** Slot of the runtime for the overlay. The sender or the bus fills it when the first rules arrive. */\nexport interface RemoteSlot {\n /** Overlay, or null before the first rules. */\n sampling: RemoteSampling | null;\n}\n\n/** Remote sampling rules in force for this context. */\nexport class RemoteSampling {\n /** Rules in force, or null. */\n private rules: RemoteRules | null = null;\n\n /** Time that the rules arrived, in epoch milliseconds. */\n private receivedAt = 0;\n\n /** Time that the rules end, in epoch milliseconds. */\n private until = 0;\n\n /**\n * @param config Active configuration instance. A reconfigure changes it in place.\n */\n constructor(private readonly config: ResolvedConfig) {}\n\n /**\n * Puts new rules in force. They replace the rules in force.\n * @param update Validated rules and their TTL, or null when the upstream has no rules.\n */\n apply(update: RemoteUpdate | null): void {\n if (!update) {\n this.rules = null;\n return;\n }\n\n const now = Date.now();\n\n this.rules = update.rules;\n this.receivedAt = now;\n this.until = now + update.ttlMs;\n }\n\n /**\n * Returns the rules in force.\n * @returns The rules, or null after the TTL or when `sampling.remote` is off.\n */\n current(): RemoteRules | null {\n if (!this.rules) {\n return null;\n }\n\n const now = Date.now();\n\n // Drop the rules when remote sampling is off. Turning it on again must not bring them back.\n // Guard against a clock that moves back. The rules then stay longer than their TTL.\n if (!this.config.sampling.remote || now < this.receivedAt || now >= this.until) {\n this.rules = null;\n return null;\n }\n\n return this.rules;\n }\n\n /**\n * Returns the lowest level that the library sends.\n * @returns The remote level if it is lower than `minLevel`. If not, `minLevel`.\n */\n minLevel(): LogLevel {\n const { minLevel } = this.config;\n const remote = this.current()?.minLevel;\n\n return remote !== undefined && LEVEL_ORDER[remote] < LEVEL_ORDER[minLevel] ? remote : minLevel;\n }\n\n /**\n * Returns the rules in force in the shape of the header, with the remaining TTL.\n * @returns The rules, or null if no rules are in force.\n */\n wire(): RemoteWire | null {\n const rules = this.current();\n\n if (!rules) {\n return null;\n }\n\n return { ...rules, v: REMOTE_SAMPLING_VERSION, ttlMs: this.until - Date.now() };\n }\n}\n","// src/core/remote-rules.ts\n//\n// Validates the sampling rules from the ingest server and puts them in force.\n// The sender and the bus import this module.\n// The main bundle does not include it.\n\nimport {\n LEVEL_ORDER,\n REMOTE_SAMPLING_MAX_CHARS,\n REMOTE_SAMPLING_MAX_RATES,\n REMOTE_SAMPLING_MAX_TTL_MS,\n REMOTE_SAMPLING_VERSION,\n SAMPLING_RATE_MAX,\n SAMPLING_RATE_MIN,\n} from \"../constants\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { LogLevel } from \"../models/log-record\";\nimport type { Diagnostics } from \"./diagnostics\";\nimport {\n type RemoteRules,\n RemoteSampling,\n type RemoteSlot,\n type RemoteUpdate,\n} from \"./remote-sampling\";\n\n/** Failure of one validation step. The message states the rule. */\nclass RuleError extends Error {}\n\n/**\n * Tests if a value is a rate.\n * @param value Value to test.\n * @returns True for a number from 0 to 1. NaN fails.\n */\nfunction isRate(value: unknown): value is number {\n return typeof value === \"number\" && value >= SAMPLING_RATE_MIN && value <= SAMPLING_RATE_MAX;\n}\n\n/**\n * Tests if a value is a plain object.\n * @param value Value to test.\n * @returns True for an object that is not null and not an array.\n */\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Reads the header text as JSON.\n * @param text Header text.\n * @returns The parsed value.\n * @throws RuleError when the text is too long or is not JSON.\n */\nfunction parseText(text: string): unknown {\n if (text.length > REMOTE_SAMPLING_MAX_CHARS) {\n throw new RuleError(\n `The header is longer than ${String(REMOTE_SAMPLING_MAX_CHARS)} characters.`,\n );\n }\n\n try {\n return JSON.parse(text);\n } catch {\n // The caller reports the RuleError.\n throw new RuleError(\"The header is not valid JSON.\");\n }\n}\n\n/**\n * Reads the namespace rates.\n * @param value Value of `rates`.\n * @returns The rates.\n * @throws RuleError when a rate is not valid.\n */\nfunction readRates(value: unknown): Record<string, number> {\n if (value === undefined) {\n return {};\n }\n\n const rule = `rates must be an object with at most ${String(REMOTE_SAMPLING_MAX_RATES)} rates from 0 to 1.`;\n\n if (!isObject(value)) {\n throw new RuleError(rule);\n }\n\n const entries = Object.entries(value);\n\n if (entries.length > REMOTE_SAMPLING_MAX_RATES || !entries.every(([, rate]) => isRate(rate))) {\n throw new RuleError(rule);\n }\n\n // fromEntries makes own properties. A \"__proto__\" key then cannot change the prototype.\n return Object.fromEntries(entries) as Record<string, number>;\n}\n\n/**\n * Validates the rules. Sampling applies `remoteMaxRate` when it reads them.\n * @param value Parsed header value.\n * @param maxRate Highest rate that a remote rule can set.\n * @returns The rules and their TTL.\n * @throws RuleError when a field is not valid.\n */\nfunction readRules(value: unknown): RemoteUpdate {\n if (!isObject(value)) {\n throw new RuleError(\"The rules must be an object.\");\n }\n\n if (value.v !== REMOTE_SAMPLING_VERSION) {\n throw new RuleError(`The version must be ${String(REMOTE_SAMPLING_VERSION)}.`);\n }\n\n const { ttlMs, defaultRate, minLevel } = value;\n\n if (typeof ttlMs !== \"number\" || !(ttlMs > 0 && ttlMs <= REMOTE_SAMPLING_MAX_TTL_MS)) {\n throw new RuleError(\n `ttlMs must be a number more than 0 and at most ${String(REMOTE_SAMPLING_MAX_TTL_MS)}.`,\n );\n }\n\n if (defaultRate !== undefined && !isRate(defaultRate)) {\n throw new RuleError(\"defaultRate must be a number from 0 to 1.\");\n }\n\n if (\n minLevel !== undefined &&\n !(typeof minLevel === \"string\" && Object.hasOwn(LEVEL_ORDER, minLevel))\n ) {\n throw new RuleError(\"minLevel must be a level name, for example DEBUG.\");\n }\n\n const rules: RemoteRules = { rates: readRates(value.rates) };\n\n if (defaultRate !== undefined) {\n rules.defaultRate = defaultRate;\n }\n\n if (minLevel !== undefined) {\n rules.minLevel = minLevel as LogLevel;\n }\n\n return { rules, ttlMs };\n}\n\n/**\n * Validates sampling rules from the server. A rule that is not valid rejects all the rules.\n * @param raw Header text, or a parsed object from a custom transport or the bus.\n * @param diagnostics Diagnostics reporter.\n * @returns The rules and their TTL, or null if they are not valid.\n */\nexport function parseRemoteRules(raw: unknown, diagnostics: Diagnostics): RemoteUpdate | null {\n try {\n return readRules(typeof raw === \"string\" ? parseText(raw) : raw);\n } catch (error) {\n const reason = error instanceof RuleError ? ` ${error.message}` : \"\";\n\n diagnostics.report(\n \"config.invalid\",\n `The library ignores the sampling rules from the server.${reason}`,\n undefined,\n error,\n );\n return null;\n }\n}\n\n/**\n * Puts rules in force in the slot of the runtime. It makes the overlay for the first rules.\n * @param slot Slot of the runtime.\n * @param config Active configuration instance.\n * @param update Validated rules, or null when the upstream has no rules.\n */\nexport function applyRemote(\n slot: RemoteSlot,\n config: ResolvedConfig,\n update: RemoteUpdate | null,\n): void {\n if (update) {\n slot.sampling ??= new RemoteSampling(config);\n }\n\n slot.sampling?.apply(update);\n}\n"],"mappings":"4CA2CA,IAAaK,EAAb,KAA4B,CAaG,OAX7B,MAAoC,KAGpC,WAAqB,EAGrB,MAAgB,EAKhB,YAAY,EAAyC,CAAxB,KAAA,OAAAC,CAAyB,CAMtD,MAAM,EAAmC,CACvC,GAAI,CAACC,EAAQ,CACX,KAAK,MAAQ,KACb,MACF,CAEA,IAAMC,EAAM,KAAK,IAAI,EAErB,KAAK,MAAQD,EAAO,MACpB,KAAK,WAAaC,EAClB,KAAK,MAAQA,EAAMD,EAAO,KAC5B,CAMA,SAA8B,CAC5B,GAAI,CAAC,KAAK,MACR,OAAO,KAGT,IAAMC,EAAM,KAAK,IAAI,EASrB,MALI,CAAC,KAAK,OAAO,SAAS,QAAUA,EAAM,KAAK,YAAcA,GAAO,KAAK,OACvE,KAAK,MAAQ,KACN,MAGF,KAAK,KACd,CA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