Update test framework: fix run_tests.py to support all test files, add auto-import-check for test files

This commit is contained in:
qiaoxinjiu
2026-05-09 15:11:30 +08:00
parent eb053a347f
commit eaba8328da
21739 changed files with 2236758 additions and 719 deletions

View File

@@ -0,0 +1,9 @@
import { AutoLoaderOptions } from './types_internal';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export declare function registerInstrumentations(options: AutoLoaderOptions): () => void;
//# sourceMappingURL=autoLoader.d.ts.map

View File

@@ -0,0 +1,35 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { trace, metrics } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import { disableInstrumentations, enableInstrumentations, } from './autoLoaderUtils';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export function registerInstrumentations(options) {
const tracerProvider = options.tracerProvider || trace.getTracerProvider();
const meterProvider = options.meterProvider || metrics.getMeterProvider();
const loggerProvider = options.loggerProvider || logs.getLoggerProvider();
const instrumentations = options.instrumentations?.flat() ?? [];
enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider);
return () => {
disableInstrumentations(instrumentations);
};
}
//# sourceMappingURL=autoLoader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoader.js","sourceRoot":"","sources":["../../src/autoLoader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAG3B;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,OAA0B;IAE1B,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;IAC3E,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAC1E,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;IAC1E,MAAM,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAEhE,sBAAsB,CACpB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,cAAc,CACf,CAAC;IAEF,OAAO,GAAG,EAAE;QACV,uBAAuB,CAAC,gBAAgB,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { trace, metrics } from '@opentelemetry/api';\nimport { logs } from '@opentelemetry/api-logs';\nimport {\n disableInstrumentations,\n enableInstrumentations,\n} from './autoLoaderUtils';\nimport { AutoLoaderOptions } from './types_internal';\n\n/**\n * It will register instrumentations and plugins\n * @param options\n * @return returns function to unload instrumentation and plugins that were\n * registered\n */\nexport function registerInstrumentations(\n options: AutoLoaderOptions\n): () => void {\n const tracerProvider = options.tracerProvider || trace.getTracerProvider();\n const meterProvider = options.meterProvider || metrics.getMeterProvider();\n const loggerProvider = options.loggerProvider || logs.getLoggerProvider();\n const instrumentations = options.instrumentations?.flat() ?? [];\n\n enableInstrumentations(\n instrumentations,\n tracerProvider,\n meterProvider,\n loggerProvider\n );\n\n return () => {\n disableInstrumentations(instrumentations);\n };\n}\n"]}

View File

@@ -0,0 +1,16 @@
import { TracerProvider, MeterProvider } from '@opentelemetry/api';
import { Instrumentation } from './types';
import { LoggerProvider } from '@opentelemetry/api-logs';
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export declare function enableInstrumentations(instrumentations: Instrumentation[], tracerProvider?: TracerProvider, meterProvider?: MeterProvider, loggerProvider?: LoggerProvider): void;
/**
* Disable instrumentations
* @param instrumentations
*/
export declare function disableInstrumentations(instrumentations: Instrumentation[]): void;
//# sourceMappingURL=autoLoaderUtils.d.ts.map

View File

@@ -0,0 +1,50 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) {
for (let i = 0, j = instrumentations.length; i < j; i++) {
const instrumentation = instrumentations[i];
if (tracerProvider) {
instrumentation.setTracerProvider(tracerProvider);
}
if (meterProvider) {
instrumentation.setMeterProvider(meterProvider);
}
if (loggerProvider && instrumentation.setLoggerProvider) {
instrumentation.setLoggerProvider(loggerProvider);
}
// instrumentations have been already enabled during creation
// so enable only if user prevented that by setting enabled to false
// this is to prevent double enabling but when calling register all
// instrumentations should be now enabled
if (!instrumentation.getConfig().enabled) {
instrumentation.enable();
}
}
}
/**
* Disable instrumentations
* @param instrumentations
*/
export function disableInstrumentations(instrumentations) {
instrumentations.forEach(instrumentation => instrumentation.disable());
}
//# sourceMappingURL=autoLoaderUtils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoaderUtils.js","sourceRoot":"","sources":["../../src/autoLoaderUtils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAMH;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,gBAAmC,EACnC,cAA+B,EAC/B,aAA6B,EAC7B,cAA+B;IAE/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACvD,MAAM,eAAe,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC;QAC5C,IAAI,cAAc,EAAE;YAClB,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,IAAI,aAAa,EAAE;YACjB,eAAe,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;SACjD;QACD,IAAI,cAAc,IAAI,eAAe,CAAC,iBAAiB,EAAE;YACvD,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,6DAA6D;QAC7D,oEAAoE;QACpE,mEAAmE;QACnE,yCAAyC;QACzC,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE;YACxC,eAAe,CAAC,MAAM,EAAE,CAAC;SAC1B;KACF;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CACrC,gBAAmC;IAEnC,gBAAgB,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,eAAe,CAAC,OAAO,EAAE,CAAC,CAAC;AACzE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TracerProvider, MeterProvider } from '@opentelemetry/api';\nimport { Instrumentation } from './types';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\n/**\n * Enable instrumentations\n * @param instrumentations\n * @param tracerProvider\n * @param meterProvider\n */\nexport function enableInstrumentations(\n instrumentations: Instrumentation[],\n tracerProvider?: TracerProvider,\n meterProvider?: MeterProvider,\n loggerProvider?: LoggerProvider\n): void {\n for (let i = 0, j = instrumentations.length; i < j; i++) {\n const instrumentation = instrumentations[i];\n if (tracerProvider) {\n instrumentation.setTracerProvider(tracerProvider);\n }\n if (meterProvider) {\n instrumentation.setMeterProvider(meterProvider);\n }\n if (loggerProvider && instrumentation.setLoggerProvider) {\n instrumentation.setLoggerProvider(loggerProvider);\n }\n // instrumentations have been already enabled during creation\n // so enable only if user prevented that by setting enabled to false\n // this is to prevent double enabling but when calling register all\n // instrumentations should be now enabled\n if (!instrumentation.getConfig().enabled) {\n instrumentation.enable();\n }\n }\n}\n\n/**\n * Disable instrumentations\n * @param instrumentations\n */\nexport function disableInstrumentations(\n instrumentations: Instrumentation[]\n): void {\n instrumentations.forEach(instrumentation => instrumentation.disable());\n}\n"]}

View File

@@ -0,0 +1,8 @@
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { Instrumentation, InstrumentationConfig, InstrumentationModuleDefinition, InstrumentationModuleFile, ShimWrapped, SpanCustomizationHook, } from './types';
export { AutoLoaderOptions, AutoLoaderResult } from './types_internal';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,21 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAUhF,OAAO,EACL,SAAS,EACT,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { registerInstrumentations } from './autoLoader';\nexport { InstrumentationBase } from './platform/index';\nexport { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';\nexport { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';\nexport {\n Instrumentation,\n InstrumentationConfig,\n InstrumentationModuleDefinition,\n InstrumentationModuleFile,\n ShimWrapped,\n SpanCustomizationHook,\n} from './types';\nexport { AutoLoaderOptions, AutoLoaderResult } from './types_internal';\nexport {\n isWrapped,\n safeExecuteInTheMiddle,\n safeExecuteInTheMiddleAsync,\n} from './utils';\n"]}

View File

@@ -0,0 +1,74 @@
import { DiagLogger, Meter, MeterProvider, Tracer, TracerProvider, Span } from '@opentelemetry/api';
import { Logger, LoggerProvider } from '@opentelemetry/api-logs';
import { InstrumentationModuleDefinition, Instrumentation, InstrumentationConfig, SpanCustomizationHook } from './types';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export declare abstract class InstrumentationAbstract<ConfigType extends InstrumentationConfig = InstrumentationConfig> implements Instrumentation<ConfigType> {
readonly instrumentationName: string;
readonly instrumentationVersion: string;
protected _config: ConfigType;
private _tracer;
private _meter;
private _logger;
protected _diag: DiagLogger;
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
protected _wrap: <Nodule extends object, FieldName extends keyof Nodule>(nodule: Nodule, name: FieldName, wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _unwrap: <Nodule extends object>(nodule: Nodule, name: keyof Nodule) => void;
protected _massWrap: <Nodule extends object, FieldName extends keyof Nodule>(nodules: Nodule[], names: FieldName[], wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _massUnwrap: <Nodule extends object>(nodules: Nodule[], names: (keyof Nodule)[]) => void;
protected get meter(): Meter;
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider: MeterProvider): void;
protected get logger(): Logger;
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider: LoggerProvider): void;
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions(): InstrumentationModuleDefinition[];
/**
* Sets the new metric instruments with the current Meter.
*/
protected _updateMetricInstruments(): void;
getConfig(): ConfigType;
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config: ConfigType): void;
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider: TracerProvider): void;
protected get tracer(): Tracer;
abstract enable(): void;
abstract disable(): void;
/**
* Init method in which plugin should define _modules and patches for
* methods.
*/
protected abstract init(): InstrumentationModuleDefinition | InstrumentationModuleDefinition[] | void;
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
protected _runSpanCustomizationHook<SpanCustomizationInfoType>(hookHandler: SpanCustomizationHook<SpanCustomizationInfoType> | undefined, triggerName: string, span: Span, info: SpanCustomizationInfoType): void;
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,141 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag, metrics, trace, } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import * as shimmer from 'shimmer';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export class InstrumentationAbstract {
instrumentationName;
instrumentationVersion;
_config = {};
_tracer;
_meter;
_logger;
_diag;
constructor(instrumentationName, instrumentationVersion, config) {
this.instrumentationName = instrumentationName;
this.instrumentationVersion = instrumentationVersion;
this.setConfig(config);
this._diag = diag.createComponentLogger({
namespace: instrumentationName,
});
this._tracer = trace.getTracer(instrumentationName, instrumentationVersion);
this._meter = metrics.getMeter(instrumentationName, instrumentationVersion);
this._logger = logs.getLogger(instrumentationName, instrumentationVersion);
this._updateMetricInstruments();
}
/* Api to wrap instrumented method */
_wrap = shimmer.wrap;
/* Api to unwrap instrumented methods */
_unwrap = shimmer.unwrap;
/* Api to mass wrap instrumented method */
_massWrap = shimmer.massWrap;
/* Api to mass unwrap instrumented methods */
_massUnwrap = shimmer.massUnwrap;
/* Returns meter */
get meter() {
return this._meter;
}
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider) {
this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion);
this._updateMetricInstruments();
}
/* Returns logger */
get logger() {
return this._logger;
}
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider) {
this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion);
}
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions() {
const initResult = this.init() ?? [];
if (!Array.isArray(initResult)) {
return [initResult];
}
return initResult;
}
/**
* Sets the new metric instruments with the current Meter.
*/
_updateMetricInstruments() {
return;
}
/* Returns InstrumentationConfig */
getConfig() {
return this._config;
}
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config) {
// copy config first level properties to ensure they are immutable.
// nested properties are not copied, thus are mutable from the outside.
this._config = {
enabled: true,
...config,
};
}
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider) {
this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
}
/* Returns tracer */
get tracer() {
return this._tracer;
}
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
_runSpanCustomizationHook(hookHandler, triggerName, span, info) {
if (!hookHandler) {
return;
}
try {
hookHandler(span, info);
}
catch (e) {
this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e);
}
}
}
//# sourceMappingURL=instrumentation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
import { InstrumentationModuleDefinition, InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleDefinition implements InstrumentationModuleDefinition {
name: string;
supportedVersions: string[];
patch?: ((exports: any, moduleVersion?: string) => any) | undefined;
unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined;
files: InstrumentationModuleFile[];
constructor(name: string, supportedVersions: string[], patch?: ((exports: any, moduleVersion?: string) => any) | undefined, unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined, files?: InstrumentationModuleFile[]);
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.d.ts.map

View File

@@ -0,0 +1,34 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class InstrumentationNodeModuleDefinition {
name;
supportedVersions;
patch;
unpatch;
files;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch, files) {
this.name = name;
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.files = files || [];
}
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleDefinition.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleDefinition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,MAAM,OAAO,mCAAmC;IAKrC;IACA;IAEA;IAEA;IAPT,KAAK,CAA8B;IACnC,YACS,IAAY,EACZ,iBAA2B;IAClC,8DAA8D;IACvD,KAAqD;IAC5D,8DAA8D;IACvD,OAAwD,EAC/D,KAAmC;QAN5B,SAAI,GAAJ,IAAI,CAAQ;QACZ,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAgD;QAErD,YAAO,GAAP,OAAO,CAAiD;QAG/D,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n InstrumentationModuleDefinition,\n InstrumentationModuleFile,\n} from './types';\n\nexport class InstrumentationNodeModuleDefinition\n implements InstrumentationModuleDefinition\n{\n files: InstrumentationModuleFile[];\n constructor(\n public name: string,\n public supportedVersions: string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public patch?: (exports: any, moduleVersion?: string) => any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public unpatch?: (exports: any, moduleVersion?: string) => void,\n files?: InstrumentationModuleFile[]\n ) {\n this.files = files || [];\n }\n}\n"]}

View File

@@ -0,0 +1,9 @@
import { InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleFile implements InstrumentationModuleFile {
supportedVersions: string[];
patch: (moduleExports: any, moduleVersion?: string) => any;
unpatch: (moduleExports?: any, moduleVersion?: string) => void;
name: string;
constructor(name: string, supportedVersions: string[], patch: (moduleExports: any, moduleVersion?: string) => any, unpatch: (moduleExports?: any, moduleVersion?: string) => void);
}
//# sourceMappingURL=instrumentationNodeModuleFile.d.ts.map

View File

@@ -0,0 +1,33 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { normalize } from './platform/index';
export class InstrumentationNodeModuleFile {
supportedVersions;
patch;
unpatch;
name;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch) {
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.name = normalize(name);
}
}
//# sourceMappingURL=instrumentationNodeModuleFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleFile.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleFile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,MAAM,OAAO,6BAA6B;IAM/B;IAEA;IAEA;IAPF,IAAI,CAAS;IACpB,YACE,IAAY,EACL,iBAA2B;IAClC,8DAA8D;IACvD,KAA0D;IACjE,8DAA8D;IACvD,OAA8D;QAJ9D,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAqD;QAE1D,YAAO,GAAP,OAAO,CAAuD;QAErE,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentationModuleFile } from './types';\nimport { normalize } from './platform/index';\n\nexport class InstrumentationNodeModuleFile\n implements InstrumentationModuleFile\n{\n public name: string;\n constructor(\n name: string,\n public supportedVersions: string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public patch: (moduleExports: any, moduleVersion?: string) => any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public unpatch: (moduleExports?: any, moduleVersion?: string) => void\n ) {\n this.name = normalize(name);\n }\n}\n"]}

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase } from './instrumentation';\nexport { normalize } from './noop-normalize';\n"]}

View File

@@ -0,0 +1,10 @@
import { InstrumentationAbstract } from '../../instrumentation';
import * as types from '../../types';
import { InstrumentationConfig } from '../../types';
/**
* Base abstract class for instrumenting web plugins
*/
export declare abstract class InstrumentationBase<ConfigType extends InstrumentationConfig = InstrumentationConfig> extends InstrumentationAbstract<ConfigType> implements types.Instrumentation<ConfigType> {
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,28 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { InstrumentationAbstract } from '../../instrumentation';
/**
* Base abstract class for instrumenting web plugins
*/
export class InstrumentationBase extends InstrumentationAbstract {
constructor(instrumentationName, instrumentationVersion, config) {
super(instrumentationName, instrumentationVersion, config);
if (this._config.enabled) {
this.enable();
}
}
}
//# sourceMappingURL=instrumentation.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../../../src/platform/browser/instrumentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAIhE;;GAEG;AACH,MAAM,OAAgB,mBAGpB,SAAQ,uBAAmC;IAG3C,YACE,mBAA2B,EAC3B,sBAA8B,EAC9B,MAAkB;QAElB,KAAK,CAAC,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,CAAC,CAAC;QAE3D,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACxB,IAAI,CAAC,MAAM,EAAE,CAAC;SACf;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentationAbstract } from '../../instrumentation';\nimport * as types from '../../types';\nimport { InstrumentationConfig } from '../../types';\n\n/**\n * Base abstract class for instrumenting web plugins\n */\nexport abstract class InstrumentationBase<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n >\n extends InstrumentationAbstract<ConfigType>\n implements types.Instrumentation<ConfigType>\n{\n constructor(\n instrumentationName: string,\n instrumentationVersion: string,\n config: ConfigType\n ) {\n super(instrumentationName, instrumentationVersion, config);\n\n if (this._config.enabled) {\n this.enable();\n }\n }\n}\n"]}

View File

@@ -0,0 +1,13 @@
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export declare function normalize(path: string): string;
//# sourceMappingURL=noop-normalize.d.ts.map

View File

@@ -0,0 +1,32 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag } from '@opentelemetry/api';
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export function normalize(path) {
diag.warn('Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)');
return path;
}
//# sourceMappingURL=noop-normalize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"noop-normalize.js","sourceRoot":"","sources":["../../../../src/platform/browser/noop-normalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,CAAC,IAAI,CACP,yOAAyO,CAC1O,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Placeholder normalize function to replace the node variant in browser runtimes,\n * this should never be called and will perform a no-op and warn if it is called regardless.\n *\n * This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation\n * package can be made node-only.\n *\n * @param path input path\n * @return unmodified path\n * @internal\n */\nexport function normalize(path: string): string {\n diag.warn(\n 'Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)'\n );\n return path;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase, normalize } from './node';\n"]}

View File

@@ -0,0 +1,36 @@
import type { Hooked } from './RequireInTheMiddleSingleton';
export declare const ModuleNameSeparator = "/";
type ModuleNameTrieSearchOptions = {
/**
* Whether to return the results in insertion order
*/
maintainInsertionOrder?: boolean;
/**
* Whether to return only full matches
*/
fullOnly?: boolean;
};
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export declare class ModuleNameTrie {
private _trie;
private _counter;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook: Hooked): void;
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName: string, { maintainInsertionOrder, fullOnly }?: ModuleNameTrieSearchOptions): Hooked[];
}
export {};
//# sourceMappingURL=ModuleNameTrie.d.ts.map

View File

@@ -0,0 +1,85 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const ModuleNameSeparator = '/';
/**
* Node in a `ModuleNameTrie`
*/
class ModuleNameTrieNode {
hooks = [];
children = new Map();
}
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export class ModuleNameTrie {
_trie = new ModuleNameTrieNode();
_counter = 0;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook) {
let trieNode = this._trie;
for (const moduleNamePart of hook.moduleName.split(ModuleNameSeparator)) {
let nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
nextNode = new ModuleNameTrieNode();
trieNode.children.set(moduleNamePart, nextNode);
}
trieNode = nextNode;
}
trieNode.hooks.push({ hook, insertedId: this._counter++ });
}
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName, { maintainInsertionOrder, fullOnly } = {}) {
let trieNode = this._trie;
const results = [];
let foundFull = true;
for (const moduleNamePart of moduleName.split(ModuleNameSeparator)) {
const nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
foundFull = false;
break;
}
if (!fullOnly) {
results.push(...nextNode.hooks);
}
trieNode = nextNode;
}
if (fullOnly && foundFull) {
results.push(...trieNode.hooks);
}
if (results.length === 0) {
return [];
}
if (results.length === 1) {
return [results[0].hook];
}
if (maintainInsertionOrder) {
results.sort((a, b) => a.insertedId - b.insertedId);
}
return results.map(({ hook }) => hook);
}
}
//# sourceMappingURL=ModuleNameTrie.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
import type { OnRequireFn } from 'require-in-the-middle';
export type Hooked = {
moduleName: string;
onRequire: OnRequireFn;
};
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export declare class RequireInTheMiddleSingleton {
private _moduleNameTrie;
private static _instance?;
private constructor();
private _initialize;
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName: string, onRequire: OnRequireFn): Hooked;
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance(): RequireInTheMiddleSingleton;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.d.ts.map

View File

@@ -0,0 +1,107 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Hook } from 'require-in-the-middle';
import * as path from 'path';
import { ModuleNameTrie, ModuleNameSeparator } from './ModuleNameTrie';
/**
* Whether Mocha is running in this process
* Inspired by https://github.com/AndreasPizsa/detect-mocha
*
* @type {boolean}
*/
const isMocha = [
'afterEach',
'after',
'beforeEach',
'before',
'describe',
'it',
].every(fn => {
// @ts-expect-error TS7053: Element implicitly has an 'any' type
return typeof global[fn] === 'function';
});
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export class RequireInTheMiddleSingleton {
_moduleNameTrie = new ModuleNameTrie();
static _instance;
constructor() {
this._initialize();
}
_initialize() {
new Hook(
// Intercept all `require` calls; we will filter the matching ones below
null, { internals: true }, (exports, name, basedir) => {
// For internal files on Windows, `name` will use backslash as the path separator
const normalizedModuleName = normalizePathSeparators(name);
const matches = this._moduleNameTrie.search(normalizedModuleName, {
maintainInsertionOrder: true,
// For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises').
// This matches the behavior of `require-in-the-middle`.
// `basedir` is always `undefined` for core modules.
fullOnly: basedir === undefined,
});
for (const { onRequire } of matches) {
exports = onRequire(exports, name, basedir);
}
return exports;
});
}
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName, onRequire) {
const hooked = { moduleName, onRequire };
this._moduleNameTrie.insert(hooked);
return hooked;
}
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance() {
// Mocha runs all test suites in the same process
// This prevents test suites from sharing a singleton
if (isMocha)
return new RequireInTheMiddleSingleton();
return (this._instance =
this._instance ?? new RequireInTheMiddleSingleton());
}
}
/**
* Normalize the path separators to forward slash in a module name or path
*
* @param {string} moduleNameOrPath Module name or path
* @returns {string} Normalized module name or path
*/
function normalizePathSeparators(moduleNameOrPath) {
return path.sep !== ModuleNameSeparator
? moduleNameOrPath.split(path.sep).join(ModuleNameSeparator)
: moduleNameOrPath;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { InstrumentationBase } from './instrumentation';\nexport { normalize } from './normalize';\n"]}

View File

@@ -0,0 +1,25 @@
import * as types from '../../types';
import { wrap, unwrap, massWrap, massUnwrap } from 'shimmer';
import { InstrumentationAbstract } from '../../instrumentation';
import { InstrumentationConfig } from '../../types';
/**
* Base abstract class for instrumenting node plugins
*/
export declare abstract class InstrumentationBase<ConfigType extends InstrumentationConfig = InstrumentationConfig> extends InstrumentationAbstract<ConfigType> implements types.Instrumentation<ConfigType> {
private _modules;
private _hooks;
private _requireInTheMiddleSingleton;
private _enabled;
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
protected _wrap: typeof wrap;
protected _unwrap: typeof unwrap;
protected _massWrap: typeof massWrap;
protected _massUnwrap: typeof massUnwrap;
private _warnOnPreloadedModules;
private _extractPackageVersion;
private _onRequire;
enable(): void;
disable(): void;
isEnabled(): boolean;
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,278 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as path from 'path';
import { types as utilTypes } from 'util';
import { satisfies } from '../../semver';
import { wrap, unwrap } from 'shimmer';
import { InstrumentationAbstract } from '../../instrumentation';
import { RequireInTheMiddleSingleton, } from './RequireInTheMiddleSingleton';
import { Hook as HookImport } from 'import-in-the-middle';
import { diag } from '@opentelemetry/api';
import { Hook as HookRequire } from 'require-in-the-middle';
import { readFileSync } from 'fs';
import { isWrapped } from '../../utils';
/**
* Base abstract class for instrumenting node plugins
*/
export class InstrumentationBase extends InstrumentationAbstract {
_modules;
_hooks = [];
_requireInTheMiddleSingleton = RequireInTheMiddleSingleton.getInstance();
_enabled = false;
constructor(instrumentationName, instrumentationVersion, config) {
super(instrumentationName, instrumentationVersion, config);
let modules = this.init();
if (modules && !Array.isArray(modules)) {
modules = [modules];
}
this._modules = modules || [];
if (this._config.enabled) {
this.enable();
}
}
_wrap = (moduleExports, name, wrapper) => {
if (isWrapped(moduleExports[name])) {
this._unwrap(moduleExports, name);
}
if (!utilTypes.isProxy(moduleExports)) {
return wrap(moduleExports, name, wrapper);
}
else {
const wrapped = wrap(Object.assign({}, moduleExports), name, wrapper);
Object.defineProperty(moduleExports, name, {
value: wrapped,
});
return wrapped;
}
};
_unwrap = (moduleExports, name) => {
if (!utilTypes.isProxy(moduleExports)) {
return unwrap(moduleExports, name);
}
else {
return Object.defineProperty(moduleExports, name, {
value: moduleExports[name],
});
}
};
_massWrap = (moduleExportsArray, names, wrapper) => {
if (!moduleExportsArray) {
diag.error('must provide one or more modules to patch');
return;
}
else if (!Array.isArray(moduleExportsArray)) {
moduleExportsArray = [moduleExportsArray];
}
if (!(names && Array.isArray(names))) {
diag.error('must provide one or more functions to wrap on modules');
return;
}
moduleExportsArray.forEach(moduleExports => {
names.forEach(name => {
this._wrap(moduleExports, name, wrapper);
});
});
};
_massUnwrap = (moduleExportsArray, names) => {
if (!moduleExportsArray) {
diag.error('must provide one or more modules to patch');
return;
}
else if (!Array.isArray(moduleExportsArray)) {
moduleExportsArray = [moduleExportsArray];
}
if (!(names && Array.isArray(names))) {
diag.error('must provide one or more functions to wrap on modules');
return;
}
moduleExportsArray.forEach(moduleExports => {
names.forEach(name => {
this._unwrap(moduleExports, name);
});
});
};
_warnOnPreloadedModules() {
this._modules.forEach((module) => {
const { name } = module;
try {
const resolvedModule = require.resolve(name);
if (require.cache[resolvedModule]) {
// Module is already cached, which means the instrumentation hook might not work
this._diag.warn(`Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`);
}
}
catch {
// Module isn't available, we can simply skip
}
});
}
_extractPackageVersion(baseDir) {
try {
const json = readFileSync(path.join(baseDir, 'package.json'), {
encoding: 'utf8',
});
const version = JSON.parse(json).version;
return typeof version === 'string' ? version : undefined;
}
catch (error) {
diag.warn('Failed extracting version', baseDir);
}
return undefined;
}
_onRequire(module, exports, name, baseDir) {
if (!baseDir) {
if (typeof module.patch === 'function') {
module.moduleExports = exports;
if (this._enabled) {
this._diag.debug('Applying instrumentation patch for nodejs core module on require hook', {
module: module.name,
});
return module.patch(exports);
}
}
return exports;
}
const version = this._extractPackageVersion(baseDir);
module.moduleVersion = version;
if (module.name === name) {
// main module
if (isSupported(module.supportedVersions, version, module.includePrerelease)) {
if (typeof module.patch === 'function') {
module.moduleExports = exports;
if (this._enabled) {
this._diag.debug('Applying instrumentation patch for module on require hook', {
module: module.name,
version: module.moduleVersion,
baseDir,
});
return module.patch(exports, module.moduleVersion);
}
}
}
return exports;
}
// internal file
const files = module.files ?? [];
const normalizedName = path.normalize(name);
const supportedFileInstrumentations = files
.filter(f => f.name === normalizedName)
.filter(f => isSupported(f.supportedVersions, version, module.includePrerelease));
return supportedFileInstrumentations.reduce((patchedExports, file) => {
file.moduleExports = patchedExports;
if (this._enabled) {
this._diag.debug('Applying instrumentation patch for nodejs module file on require hook', {
module: module.name,
version: module.moduleVersion,
fileName: file.name,
baseDir,
});
// patch signature is not typed, so we cast it assuming it's correct
return file.patch(patchedExports, module.moduleVersion);
}
return patchedExports;
}, exports);
}
enable() {
if (this._enabled) {
return;
}
this._enabled = true;
// already hooked, just call patch again
if (this._hooks.length > 0) {
for (const module of this._modules) {
if (typeof module.patch === 'function' && module.moduleExports) {
this._diag.debug('Applying instrumentation patch for nodejs module on instrumentation enabled', {
module: module.name,
version: module.moduleVersion,
});
module.patch(module.moduleExports, module.moduleVersion);
}
for (const file of module.files) {
if (file.moduleExports) {
this._diag.debug('Applying instrumentation patch for nodejs module file on instrumentation enabled', {
module: module.name,
version: module.moduleVersion,
fileName: file.name,
});
file.patch(file.moduleExports, module.moduleVersion);
}
}
}
return;
}
this._warnOnPreloadedModules();
for (const module of this._modules) {
const hookFn = (exports, name, baseDir) => {
if (!baseDir && path.isAbsolute(name)) {
const parsedPath = path.parse(name);
name = parsedPath.name;
baseDir = parsedPath.dir;
}
return this._onRequire(module, exports, name, baseDir);
};
const onRequire = (exports, name, baseDir) => {
return this._onRequire(module, exports, name, baseDir);
};
// `RequireInTheMiddleSingleton` does not support absolute paths.
// For an absolute paths, we must create a separate instance of the
// require-in-the-middle `Hook`.
const hook = path.isAbsolute(module.name)
? new HookRequire([module.name], { internals: true }, onRequire)
: this._requireInTheMiddleSingleton.register(module.name, onRequire);
this._hooks.push(hook);
const esmHook = new HookImport([module.name], { internals: false }, hookFn);
this._hooks.push(esmHook);
}
}
disable() {
if (!this._enabled) {
return;
}
this._enabled = false;
for (const module of this._modules) {
if (typeof module.unpatch === 'function' && module.moduleExports) {
this._diag.debug('Removing instrumentation patch for nodejs module on instrumentation disabled', {
module: module.name,
version: module.moduleVersion,
});
module.unpatch(module.moduleExports, module.moduleVersion);
}
for (const file of module.files) {
if (file.moduleExports) {
this._diag.debug('Removing instrumentation patch for nodejs module file on instrumentation disabled', {
module: module.name,
version: module.moduleVersion,
fileName: file.name,
});
file.unpatch(file.moduleExports, module.moduleVersion);
}
}
}
}
isEnabled() {
return this._enabled;
}
}
function isSupported(supportedVersions, version, includePrerelease) {
if (typeof version === 'undefined') {
// If we don't have the version, accept the wildcard case only
return supportedVersions.includes('*');
}
return supportedVersions.some(supportedVersion => {
return satisfies(version, supportedVersion, { includePrerelease });
});
}
//# sourceMappingURL=instrumentation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,2 @@
export { normalize } from 'path';
//# sourceMappingURL=normalize.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { normalize } from 'path';
//# sourceMappingURL=normalize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"normalize.js","sourceRoot":"","sources":["../../../../src/platform/node/normalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { normalize } from 'path';\n"]}

View File

@@ -0,0 +1,16 @@
/** Interface for the options to configure semantic versioning satisfy check. */
export interface SatisfiesOptions {
/**
* If set to true, the pre-release checks will be included
* as described [here](https://github.com/npm/node-semver#prerelease-tags).
*/
includePrerelease?: boolean;
}
/**
* Checks given version whether it satisfies given range expression.
* @param version the [version](https://github.com/npm/node-semver#versions) to be checked
* @param range the [range](https://github.com/npm/node-semver#ranges) expression for version check
* @param options options to configure semver satisfy check
*/
export declare function satisfies(version: string, range: string, options?: SatisfiesOptions): boolean;
//# sourceMappingURL=semver.d.ts.map

View File

@@ -0,0 +1,514 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This is a custom semantic versioning implementation compatible with the
// `satisfies(version, range, options?)` function from the `semver` npm package;
// with the exception that the `loose` option is not supported.
//
// The motivation for the custom semver implementation is that
// `semver` package has some initialization delay (lots of RegExp init and compile)
// and this leads to coldstart overhead for the OTEL Lambda Node.js layer.
// Hence, we have implemented lightweight version of it internally with required functionalities.
import { diag } from '@opentelemetry/api';
const VERSION_REGEXP = /^(?:v)?(?<version>(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*))(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
const RANGE_REGEXP = /^(?<op><|>|=|==|<=|>=|~|\^|~>)?\s*(?:v)?(?<version>(?<major>x|X|\*|0|[1-9]\d*)(?:\.(?<minor>x|X|\*|0|[1-9]\d*))?(?:\.(?<patch>x|X|\*|0|[1-9]\d*))?)(?:-(?<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<build>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
const operatorResMap = {
'>': [1],
'>=': [0, 1],
'=': [0],
'<=': [-1, 0],
'<': [-1],
'!=': [-1, 1],
};
/**
* Checks given version whether it satisfies given range expression.
* @param version the [version](https://github.com/npm/node-semver#versions) to be checked
* @param range the [range](https://github.com/npm/node-semver#ranges) expression for version check
* @param options options to configure semver satisfy check
*/
export function satisfies(version, range, options) {
// Strict semver format check
if (!_validateVersion(version)) {
diag.error(`Invalid version: ${version}`);
return false;
}
// If range is empty, satisfy check succeeds regardless what version is
if (!range) {
return true;
}
// Cleanup range
range = range.replace(/([<>=~^]+)\s+/g, '$1');
// Parse version
const parsedVersion = _parseVersion(version);
if (!parsedVersion) {
return false;
}
const allParsedRanges = [];
// Check given version whether it satisfies given range expression
const checkResult = _doSatisfies(parsedVersion, range, allParsedRanges, options);
// If check result is OK,
// do another final check for pre-release, if pre-release check is included by option
if (checkResult && !options?.includePrerelease) {
return _doPreleaseCheck(parsedVersion, allParsedRanges);
}
return checkResult;
}
function _validateVersion(version) {
return typeof version === 'string' && VERSION_REGEXP.test(version);
}
function _doSatisfies(parsedVersion, range, allParsedRanges, options) {
if (range.includes('||')) {
// A version matches a range if and only if
// every comparator in at least one of the ||-separated comparator sets is satisfied by the version
const ranges = range.trim().split('||');
for (const r of ranges) {
if (_checkRange(parsedVersion, r, allParsedRanges, options)) {
return true;
}
}
return false;
}
else if (range.includes(' - ')) {
// Hyphen ranges: https://github.com/npm/node-semver#hyphen-ranges-xyz---abc
range = replaceHyphen(range, options);
}
else if (range.includes(' ')) {
// Multiple separated ranges and all needs to be satisfied for success
const ranges = range
.trim()
.replace(/\s{2,}/g, ' ')
.split(' ');
for (const r of ranges) {
if (!_checkRange(parsedVersion, r, allParsedRanges, options)) {
return false;
}
}
return true;
}
// Check given parsed version with given range
return _checkRange(parsedVersion, range, allParsedRanges, options);
}
function _checkRange(parsedVersion, range, allParsedRanges, options) {
range = _normalizeRange(range, options);
if (range.includes(' ')) {
// If there are multiple ranges separated, satisfy each of them
return _doSatisfies(parsedVersion, range, allParsedRanges, options);
}
else {
// Validate and parse range
const parsedRange = _parseRange(range);
allParsedRanges.push(parsedRange);
// Check parsed version by parsed range
return _satisfies(parsedVersion, parsedRange);
}
}
function _satisfies(parsedVersion, parsedRange) {
// If range is invalid, satisfy check fails (no error throw)
if (parsedRange.invalid) {
return false;
}
// If range is empty or wildcard, satisfy check succeeds regardless what version is
if (!parsedRange.version || _isWildcard(parsedRange.version)) {
return true;
}
// Compare version segment first
let comparisonResult = _compareVersionSegments(parsedVersion.versionSegments || [], parsedRange.versionSegments || []);
// If versions segments are equal, compare by pre-release segments
if (comparisonResult === 0) {
const versionPrereleaseSegments = parsedVersion.prereleaseSegments || [];
const rangePrereleaseSegments = parsedRange.prereleaseSegments || [];
if (!versionPrereleaseSegments.length && !rangePrereleaseSegments.length) {
comparisonResult = 0;
}
else if (!versionPrereleaseSegments.length &&
rangePrereleaseSegments.length) {
comparisonResult = 1;
}
else if (versionPrereleaseSegments.length &&
!rangePrereleaseSegments.length) {
comparisonResult = -1;
}
else {
comparisonResult = _compareVersionSegments(versionPrereleaseSegments, rangePrereleaseSegments);
}
}
// Resolve check result according to comparison operator
return operatorResMap[parsedRange.op]?.includes(comparisonResult);
}
function _doPreleaseCheck(parsedVersion, allParsedRanges) {
if (parsedVersion.prerelease) {
return allParsedRanges.some(r => r.prerelease && r.version === parsedVersion.version);
}
return true;
}
function _normalizeRange(range, options) {
range = range.trim();
range = replaceCaret(range, options);
range = replaceTilde(range);
range = replaceXRange(range, options);
range = range.trim();
return range;
}
function isX(id) {
return !id || id.toLowerCase() === 'x' || id === '*';
}
function _parseVersion(versionString) {
const match = versionString.match(VERSION_REGEXP);
if (!match) {
diag.error(`Invalid version: ${versionString}`);
return undefined;
}
const version = match.groups.version;
const prerelease = match.groups.prerelease;
const build = match.groups.build;
const versionSegments = version.split('.');
const prereleaseSegments = prerelease?.split('.');
return {
op: undefined,
version,
versionSegments,
versionSegmentCount: versionSegments.length,
prerelease,
prereleaseSegments,
prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
build,
};
}
function _parseRange(rangeString) {
if (!rangeString) {
return {};
}
const match = rangeString.match(RANGE_REGEXP);
if (!match) {
diag.error(`Invalid range: ${rangeString}`);
return {
invalid: true,
};
}
let op = match.groups.op;
const version = match.groups.version;
const prerelease = match.groups.prerelease;
const build = match.groups.build;
const versionSegments = version.split('.');
const prereleaseSegments = prerelease?.split('.');
if (op === '==') {
op = '=';
}
return {
op: op || '=',
version,
versionSegments,
versionSegmentCount: versionSegments.length,
prerelease,
prereleaseSegments,
prereleaseSegmentCount: prereleaseSegments ? prereleaseSegments.length : 0,
build,
};
}
function _isWildcard(s) {
return s === '*' || s === 'x' || s === 'X';
}
function _parseVersionString(v) {
const n = parseInt(v, 10);
return isNaN(n) ? v : n;
}
function _normalizeVersionType(a, b) {
if (typeof a === typeof b) {
if (typeof a === 'number') {
return [a, b];
}
else if (typeof a === 'string') {
return [a, b];
}
else {
throw new Error('Version segments can only be strings or numbers');
}
}
else {
return [String(a), String(b)];
}
}
function _compareVersionStrings(v1, v2) {
if (_isWildcard(v1) || _isWildcard(v2)) {
return 0;
}
const [parsedV1, parsedV2] = _normalizeVersionType(_parseVersionString(v1), _parseVersionString(v2));
if (parsedV1 > parsedV2) {
return 1;
}
else if (parsedV1 < parsedV2) {
return -1;
}
return 0;
}
function _compareVersionSegments(v1, v2) {
for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
const res = _compareVersionStrings(v1[i] || '0', v2[i] || '0');
if (res !== 0) {
return res;
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
// The rest of this file is adapted from portions of https://github.com/npm/node-semver/tree/868d4bb
// License:
/*
* The ISC License
*
* Copyright (c) Isaac Z. Schlueter and Contributors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
const LETTERDASHNUMBER = '[a-zA-Z0-9-]';
const NUMERICIDENTIFIER = '0|[1-9]\\d*';
const NONNUMERICIDENTIFIER = `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`;
const GTLT = '((?:<|>)?=?)';
const PRERELEASEIDENTIFIER = `(?:${NUMERICIDENTIFIER}|${NONNUMERICIDENTIFIER})`;
const PRERELEASE = `(?:-(${PRERELEASEIDENTIFIER}(?:\\.${PRERELEASEIDENTIFIER})*))`;
const BUILDIDENTIFIER = `${LETTERDASHNUMBER}+`;
const BUILD = `(?:\\+(${BUILDIDENTIFIER}(?:\\.${BUILDIDENTIFIER})*))`;
const XRANGEIDENTIFIER = `${NUMERICIDENTIFIER}|x|X|\\*`;
const XRANGEPLAIN = `[v=\\s]*(${XRANGEIDENTIFIER})` +
`(?:\\.(${XRANGEIDENTIFIER})` +
`(?:\\.(${XRANGEIDENTIFIER})` +
`(?:${PRERELEASE})?${BUILD}?` +
`)?)?`;
const XRANGE = `^${GTLT}\\s*${XRANGEPLAIN}$`;
const XRANGE_REGEXP = new RegExp(XRANGE);
const HYPHENRANGE = `^\\s*(${XRANGEPLAIN})` + `\\s+-\\s+` + `(${XRANGEPLAIN})` + `\\s*$`;
const HYPHENRANGE_REGEXP = new RegExp(HYPHENRANGE);
const LONETILDE = '(?:~>?)';
const TILDE = `^${LONETILDE}${XRANGEPLAIN}$`;
const TILDE_REGEXP = new RegExp(TILDE);
const LONECARET = '(?:\\^)';
const CARET = `^${LONECARET}${XRANGEPLAIN}$`;
const CARET_REGEXP = new RegExp(CARET);
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L285
//
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
function replaceTilde(comp) {
const r = TILDE_REGEXP;
return comp.replace(r, (_, M, m, p, pr) => {
let ret;
if (isX(M)) {
ret = '';
}
else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
}
else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
}
else if (pr) {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
}
else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
}
return ret;
});
}
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L329
//
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
function replaceCaret(comp, options) {
const r = CARET_REGEXP;
const z = options?.includePrerelease ? '-0' : '';
return comp.replace(r, (_, M, m, p, pr) => {
let ret;
if (isX(M)) {
ret = '';
}
else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
}
else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
}
else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
}
}
else if (pr) {
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
}
else {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
}
}
else {
ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
}
}
else {
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
}
else {
ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
}
}
else {
ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
}
}
return ret;
});
}
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L390
function replaceXRange(comp, options) {
const r = XRANGE_REGEXP;
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
const xM = isX(M);
const xm = xM || isX(m);
const xp = xm || isX(p);
const anyX = xp;
if (gtlt === '=' && anyX) {
gtlt = '';
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options?.includePrerelease ? '-0' : '';
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0';
}
else {
// nothing is forbidden
ret = '*';
}
}
else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0;
}
p = 0;
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>=';
if (xm) {
M = +M + 1;
m = 0;
p = 0;
}
else {
m = +m + 1;
p = 0;
}
}
else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<';
if (xm) {
M = +M + 1;
}
else {
m = +m + 1;
}
}
if (gtlt === '<') {
pr = '-0';
}
ret = `${gtlt + M}.${m}.${p}${pr}`;
}
else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
}
else if (xp) {
ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
}
return ret;
});
}
// Borrowed from https://github.com/npm/node-semver/blob/868d4bbe3d318c52544f38d5f9977a1103e924c2/classes/range.js#L488
//
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
function replaceHyphen(comp, options) {
const r = HYPHENRANGE_REGEXP;
return comp.replace(r, (_, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => {
if (isX(fM)) {
from = '';
}
else if (isX(fm)) {
from = `>=${fM}.0.0${options?.includePrerelease ? '-0' : ''}`;
}
else if (isX(fp)) {
from = `>=${fM}.${fm}.0${options?.includePrerelease ? '-0' : ''}`;
}
else if (fpr) {
from = `>=${from}`;
}
else {
from = `>=${from}${options?.includePrerelease ? '-0' : ''}`;
}
if (isX(tM)) {
to = '';
}
else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`;
}
else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`;
}
else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`;
}
else if (options?.includePrerelease) {
to = `<${tM}.${tm}.${+tp + 1}-0`;
}
else {
to = `<=${to}`;
}
return `${from} ${to}`.trim();
});
}
//# sourceMappingURL=semver.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,116 @@
import { TracerProvider, MeterProvider, Span } from '@opentelemetry/api';
import { LoggerProvider } from '@opentelemetry/api-logs';
/** Interface Instrumentation to apply patch. */
export interface Instrumentation<ConfigType extends InstrumentationConfig = InstrumentationConfig> {
/** Instrumentation Name */
instrumentationName: string;
/** Instrumentation Version */
instrumentationVersion: string;
/** Method to disable the instrumentation */
disable(): void;
/** Method to enable the instrumentation */
enable(): void;
/** Method to set tracer provider */
setTracerProvider(tracerProvider: TracerProvider): void;
/** Method to set meter provider */
setMeterProvider(meterProvider: MeterProvider): void;
/** Method to set logger provider */
setLoggerProvider?(loggerProvider: LoggerProvider): void;
/** Method to set instrumentation config */
setConfig(config: ConfigType): void;
/** Method to get instrumentation config */
getConfig(): ConfigType;
}
/**
* Base interface for configuration options common to all instrumentations.
* This interface can be extended by individual instrumentations to include
* additional configuration options specific to that instrumentation.
* All configuration options must be optional.
*/
export interface InstrumentationConfig {
/**
* Whether to enable the plugin.
* @default true
*/
enabled?: boolean;
}
/**
* This interface defines the params that are be added to the wrapped function
* using the "shimmer.wrap"
*/
export interface ShimWrapped extends Function {
__wrapped: boolean;
__unwrap: Function;
__original: Function;
}
export interface InstrumentationModuleFile {
/** Name of file to be patched with relative path */
name: string;
moduleExports?: unknown;
/** Supported versions for the file.
*
* A module version is supported if one of the supportedVersions in the array satisfies the module version.
* The syntax of the version is checked with a function compatible
* with [node-semver's `satisfies()` function](https://github.com/npm/node-semver#ranges-1).
* If the version is not supported, we won't apply instrumentation patch.
* If omitted, all versions of the module will be patched.
*
* It is recommended to always specify a range that is bound to a major version, to avoid breaking changes.
* New major versions should be reviewed and tested before being added to the supportedVersions array.
*
* Example: ['>=1.2.3 <3']
*/
supportedVersions: string[];
/** Method to patch the instrumentation */
patch(moduleExports: unknown, moduleVersion?: string): unknown;
/** Method to unpatch the instrumentation */
unpatch(moduleExports?: unknown, moduleVersion?: string): void;
}
export interface InstrumentationModuleDefinition {
/** Module name or path */
name: string;
moduleExports?: any;
/** Instrumented module version */
moduleVersion?: string;
/** Supported version of module.
*
* A module version is supported if one of the supportedVersions in the array satisfies the module version.
* The syntax of the version is checked with the `satisfies` function of
* "The [semantic versioner](https://semver.org) for npm".
* If the version is not supported, we won't apply instrumentation patch (see `enable` method).
* If omitted, all versions of the module will be patched.
*
* It is recommended to always specify a range that is bound to a major version, to avoid breaking changes.
* New major versions should be reviewed and tested before being added to the supportedVersions array.
*
* Example: ['>=1.2.3 <3']
*/
supportedVersions: string[];
/** Module internal files to be patched */
files: InstrumentationModuleFile[];
/** If set to true, the includePrerelease check will be included when calling semver.satisfies */
includePrerelease?: boolean;
/** Method to patch the instrumentation */
patch?: // eslint-disable-next-line @typescript-eslint/no-explicit-any
((moduleExports: any, moduleVersion?: string | undefined) => any) | undefined;
/** Method to unpatch the instrumentation */
unpatch?: ((moduleExports: any, moduleVersion?: string | undefined) => void) | undefined;
}
/**
* SpanCustomizationHook is a common way for instrumentations to expose extension points
* where users can add custom behavior to a span based on info object passed to the hook at different times of the span lifecycle.
* This is an advanced feature, commonly used to add additional or non-spec-compliant attributes to the span,
* capture payloads, modify the span in some way, or carry some other side effect.
*
* The hook is registered with the instrumentation specific config by implementing an handler function with this signature,
* and if the hook is present, it will be called with the span and the event information
* when the event is emitted.
*
* When and under what conditions the hook is called and what data is passed
* in the info argument, is specific to each instrumentation and life-cycle event
* and should be documented where it is used.
*
* Instrumentation may define multiple hooks, for different spans, or different span life-cycle events.
*/
export type SpanCustomizationHook<SpanCustomizationInfoType> = (span: Span, info: SpanCustomizationInfoType) => void;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=types.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,13 @@
import { TracerProvider, MeterProvider } from '@opentelemetry/api';
import { Instrumentation } from './types';
import { LoggerProvider } from '@opentelemetry/api-logs';
export interface AutoLoaderResult {
instrumentations: Instrumentation[];
}
export interface AutoLoaderOptions {
instrumentations?: (Instrumentation | Instrumentation[])[];
tracerProvider?: TracerProvider;
meterProvider?: MeterProvider;
loggerProvider?: LoggerProvider;
}
//# sourceMappingURL=types_internal.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=types_internal.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types_internal.js","sourceRoot":"","sources":["../../src/types_internal.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TracerProvider, MeterProvider } from '@opentelemetry/api';\nimport { Instrumentation } from './types';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\nexport interface AutoLoaderResult {\n instrumentations: Instrumentation[];\n}\n\nexport interface AutoLoaderOptions {\n instrumentations?: (Instrumentation | Instrumentation[])[];\n tracerProvider?: TracerProvider;\n meterProvider?: MeterProvider;\n loggerProvider?: LoggerProvider;\n}\n"]}

View File

@@ -0,0 +1,19 @@
import { ShimWrapped } from './types';
/**
* function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export declare function safeExecuteInTheMiddle<T>(execute: () => T, onFinish: (e: Error | undefined, result: T | undefined) => void, preventThrowingError?: boolean): T;
/**
* Async function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export declare function safeExecuteInTheMiddleAsync<T>(execute: () => T, onFinish: (e: Error | undefined, result: T | undefined) => void, preventThrowingError?: boolean): Promise<T>;
/**
* Checks if certain function has been already wrapped
* @param func
*/
export declare function isWrapped(func: unknown): func is ShimWrapped;
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1,74 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) {
let error;
let result;
try {
result = execute();
}
catch (e) {
error = e;
}
finally {
onFinish(error, result);
if (error && !preventThrowingError) {
// eslint-disable-next-line no-unsafe-finally
throw error;
}
// eslint-disable-next-line no-unsafe-finally
return result;
}
}
/**
* Async function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
export async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) {
let error;
let result;
try {
result = await execute();
}
catch (e) {
error = e;
}
finally {
onFinish(error, result);
if (error && !preventThrowingError) {
// eslint-disable-next-line no-unsafe-finally
throw error;
}
// eslint-disable-next-line no-unsafe-finally
return result;
}
}
/**
* Checks if certain function has been already wrapped
* @param func
*/
export function isWrapped(func) {
return (typeof func === 'function' &&
typeof func.__original === 'function' &&
typeof func.__unwrap === 'function' &&
func.__wrapped === true);
}
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH;;;;GAIG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAgB,EAChB,QAA+D,EAC/D,oBAA8B;IAE9B,IAAI,KAAwB,CAAC;IAC7B,IAAI,MAAqB,CAAC;IAC1B,IAAI;QACF,MAAM,GAAG,OAAO,EAAE,CAAC;KACpB;IAAC,OAAO,CAAC,EAAE;QACV,KAAK,GAAG,CAAC,CAAC;KACX;YAAS;QACR,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACxB,IAAI,KAAK,IAAI,CAAC,oBAAoB,EAAE;YAClC,6CAA6C;YAC7C,MAAM,KAAK,CAAC;SACb;QACD,6CAA6C;QAC7C,OAAO,MAAW,CAAC;KACpB;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,OAAgB,EAChB,QAA+D,EAC/D,oBAA8B;IAE9B,IAAI,KAAwB,CAAC;IAC7B,IAAI,MAAqB,CAAC;IAC1B,IAAI;QACF,MAAM,GAAG,MAAM,OAAO,EAAE,CAAC;KAC1B;IAAC,OAAO,CAAC,EAAE;QACV,KAAK,GAAG,CAAC,CAAC;KACX;YAAS;QACR,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACxB,IAAI,KAAK,IAAI,CAAC,oBAAoB,EAAE;YAClC,6CAA6C;YAC7C,MAAM,KAAK,CAAC;SACb;QACD,6CAA6C;QAC7C,OAAO,MAAW,CAAC;KACpB;AACH,CAAC;AACD;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,IAAa;IACrC,OAAO,CACL,OAAO,IAAI,KAAK,UAAU;QAC1B,OAAQ,IAAoB,CAAC,UAAU,KAAK,UAAU;QACtD,OAAQ,IAAoB,CAAC,QAAQ,KAAK,UAAU;QACnD,IAAoB,CAAC,SAAS,KAAK,IAAI,CACzC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ShimWrapped } from './types';\n\n/**\n * function to execute patched function and being able to catch errors\n * @param execute - function to be executed\n * @param onFinish - callback to run when execute finishes\n */\nexport function safeExecuteInTheMiddle<T>(\n execute: () => T,\n onFinish: (e: Error | undefined, result: T | undefined) => void,\n preventThrowingError?: boolean\n): T {\n let error: Error | undefined;\n let result: T | undefined;\n try {\n result = execute();\n } catch (e) {\n error = e;\n } finally {\n onFinish(error, result);\n if (error && !preventThrowingError) {\n // eslint-disable-next-line no-unsafe-finally\n throw error;\n }\n // eslint-disable-next-line no-unsafe-finally\n return result as T;\n }\n}\n\n/**\n * Async function to execute patched function and being able to catch errors\n * @param execute - function to be executed\n * @param onFinish - callback to run when execute finishes\n */\nexport async function safeExecuteInTheMiddleAsync<T>(\n execute: () => T,\n onFinish: (e: Error | undefined, result: T | undefined) => void,\n preventThrowingError?: boolean\n): Promise<T> {\n let error: Error | undefined;\n let result: T | undefined;\n try {\n result = await execute();\n } catch (e) {\n error = e;\n } finally {\n onFinish(error, result);\n if (error && !preventThrowingError) {\n // eslint-disable-next-line no-unsafe-finally\n throw error;\n }\n // eslint-disable-next-line no-unsafe-finally\n return result as T;\n }\n}\n/**\n * Checks if certain function has been already wrapped\n * @param func\n */\nexport function isWrapped(func: unknown): func is ShimWrapped {\n return (\n typeof func === 'function' &&\n typeof (func as ShimWrapped).__original === 'function' &&\n typeof (func as ShimWrapped).__unwrap === 'function' &&\n (func as ShimWrapped).__wrapped === true\n );\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare const VERSION = "0.200.0";
//# sourceMappingURL=version.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// this is autogenerated file, see scripts/version-update.js
export const VERSION = '0.200.0';
//# sourceMappingURL=version.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,OAAO,GAAG,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.200.0';\n"]}

View File

@@ -0,0 +1,9 @@
import { AutoLoaderOptions } from './types_internal';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export declare function registerInstrumentations(options: AutoLoaderOptions): () => void;
//# sourceMappingURL=autoLoader.d.ts.map

View File

@@ -0,0 +1,35 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { trace, metrics } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import { disableInstrumentations, enableInstrumentations, } from './autoLoaderUtils';
/**
* It will register instrumentations and plugins
* @param options
* @return returns function to unload instrumentation and plugins that were
* registered
*/
export function registerInstrumentations(options) {
const tracerProvider = options.tracerProvider || trace.getTracerProvider();
const meterProvider = options.meterProvider || metrics.getMeterProvider();
const loggerProvider = options.loggerProvider || logs.getLoggerProvider();
const instrumentations = options.instrumentations?.flat() ?? [];
enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider);
return () => {
disableInstrumentations(instrumentations);
};
}
//# sourceMappingURL=autoLoader.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoader.js","sourceRoot":"","sources":["../../src/autoLoader.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,yBAAyB,CAAC;AAC/C,OAAO,EACL,uBAAuB,EACvB,sBAAsB,GACvB,MAAM,mBAAmB,CAAC;AAG3B;;;;;GAKG;AACH,MAAM,UAAU,wBAAwB,CACtC,OAA0B;IAE1B,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,KAAK,CAAC,iBAAiB,EAAE,CAAC;IAC3E,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAC1E,MAAM,cAAc,GAAG,OAAO,CAAC,cAAc,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;IAC1E,MAAM,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IAEhE,sBAAsB,CACpB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,cAAc,CACf,CAAC;IAEF,OAAO,GAAG,EAAE;QACV,uBAAuB,CAAC,gBAAgB,CAAC,CAAC;IAC5C,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { trace, metrics } from '@opentelemetry/api';\nimport { logs } from '@opentelemetry/api-logs';\nimport {\n disableInstrumentations,\n enableInstrumentations,\n} from './autoLoaderUtils';\nimport { AutoLoaderOptions } from './types_internal';\n\n/**\n * It will register instrumentations and plugins\n * @param options\n * @return returns function to unload instrumentation and plugins that were\n * registered\n */\nexport function registerInstrumentations(\n options: AutoLoaderOptions\n): () => void {\n const tracerProvider = options.tracerProvider || trace.getTracerProvider();\n const meterProvider = options.meterProvider || metrics.getMeterProvider();\n const loggerProvider = options.loggerProvider || logs.getLoggerProvider();\n const instrumentations = options.instrumentations?.flat() ?? [];\n\n enableInstrumentations(\n instrumentations,\n tracerProvider,\n meterProvider,\n loggerProvider\n );\n\n return () => {\n disableInstrumentations(instrumentations);\n };\n}\n"]}

View File

@@ -0,0 +1,16 @@
import { TracerProvider, MeterProvider } from '@opentelemetry/api';
import { Instrumentation } from './types';
import { LoggerProvider } from '@opentelemetry/api-logs';
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export declare function enableInstrumentations(instrumentations: Instrumentation[], tracerProvider?: TracerProvider, meterProvider?: MeterProvider, loggerProvider?: LoggerProvider): void;
/**
* Disable instrumentations
* @param instrumentations
*/
export declare function disableInstrumentations(instrumentations: Instrumentation[]): void;
//# sourceMappingURL=autoLoaderUtils.d.ts.map

View File

@@ -0,0 +1,50 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Enable instrumentations
* @param instrumentations
* @param tracerProvider
* @param meterProvider
*/
export function enableInstrumentations(instrumentations, tracerProvider, meterProvider, loggerProvider) {
for (let i = 0, j = instrumentations.length; i < j; i++) {
const instrumentation = instrumentations[i];
if (tracerProvider) {
instrumentation.setTracerProvider(tracerProvider);
}
if (meterProvider) {
instrumentation.setMeterProvider(meterProvider);
}
if (loggerProvider && instrumentation.setLoggerProvider) {
instrumentation.setLoggerProvider(loggerProvider);
}
// instrumentations have been already enabled during creation
// so enable only if user prevented that by setting enabled to false
// this is to prevent double enabling but when calling register all
// instrumentations should be now enabled
if (!instrumentation.getConfig().enabled) {
instrumentation.enable();
}
}
}
/**
* Disable instrumentations
* @param instrumentations
*/
export function disableInstrumentations(instrumentations) {
instrumentations.forEach(instrumentation => instrumentation.disable());
}
//# sourceMappingURL=autoLoaderUtils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoaderUtils.js","sourceRoot":"","sources":["../../src/autoLoaderUtils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAMH;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,gBAAmC,EACnC,cAA+B,EAC/B,aAA6B,EAC7B,cAA+B;IAE/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACvD,MAAM,eAAe,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC;QAC5C,IAAI,cAAc,EAAE;YAClB,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,IAAI,aAAa,EAAE;YACjB,eAAe,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;SACjD;QACD,IAAI,cAAc,IAAI,eAAe,CAAC,iBAAiB,EAAE;YACvD,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,6DAA6D;QAC7D,oEAAoE;QACpE,mEAAmE;QACnE,yCAAyC;QACzC,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE;YACxC,eAAe,CAAC,MAAM,EAAE,CAAC;SAC1B;KACF;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CACrC,gBAAmC;IAEnC,gBAAgB,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,eAAe,CAAC,OAAO,EAAE,CAAC,CAAC;AACzE,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TracerProvider, MeterProvider } from '@opentelemetry/api';\nimport { Instrumentation } from './types';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\n/**\n * Enable instrumentations\n * @param instrumentations\n * @param tracerProvider\n * @param meterProvider\n */\nexport function enableInstrumentations(\n instrumentations: Instrumentation[],\n tracerProvider?: TracerProvider,\n meterProvider?: MeterProvider,\n loggerProvider?: LoggerProvider\n): void {\n for (let i = 0, j = instrumentations.length; i < j; i++) {\n const instrumentation = instrumentations[i];\n if (tracerProvider) {\n instrumentation.setTracerProvider(tracerProvider);\n }\n if (meterProvider) {\n instrumentation.setMeterProvider(meterProvider);\n }\n if (loggerProvider && instrumentation.setLoggerProvider) {\n instrumentation.setLoggerProvider(loggerProvider);\n }\n // instrumentations have been already enabled during creation\n // so enable only if user prevented that by setting enabled to false\n // this is to prevent double enabling but when calling register all\n // instrumentations should be now enabled\n if (!instrumentation.getConfig().enabled) {\n instrumentation.enable();\n }\n }\n}\n\n/**\n * Disable instrumentations\n * @param instrumentations\n */\nexport function disableInstrumentations(\n instrumentations: Instrumentation[]\n): void {\n instrumentations.forEach(instrumentation => instrumentation.disable());\n}\n"]}

View File

@@ -0,0 +1,8 @@
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { Instrumentation, InstrumentationConfig, InstrumentationModuleDefinition, InstrumentationModuleFile, ShimWrapped, SpanCustomizationHook, } from './types';
export { AutoLoaderOptions, AutoLoaderResult } from './types_internal';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,21 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { registerInstrumentations } from './autoLoader';
export { InstrumentationBase } from './platform/index';
export { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';
export { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';
export { isWrapped, safeExecuteInTheMiddle, safeExecuteInTheMiddleAsync, } from './utils';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAUhF,OAAO,EACL,SAAS,EACT,sBAAsB,EACtB,2BAA2B,GAC5B,MAAM,SAAS,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { registerInstrumentations } from './autoLoader';\nexport { InstrumentationBase } from './platform/index';\nexport { InstrumentationNodeModuleDefinition } from './instrumentationNodeModuleDefinition';\nexport { InstrumentationNodeModuleFile } from './instrumentationNodeModuleFile';\nexport {\n Instrumentation,\n InstrumentationConfig,\n InstrumentationModuleDefinition,\n InstrumentationModuleFile,\n ShimWrapped,\n SpanCustomizationHook,\n} from './types';\nexport { AutoLoaderOptions, AutoLoaderResult } from './types_internal';\nexport {\n isWrapped,\n safeExecuteInTheMiddle,\n safeExecuteInTheMiddleAsync,\n} from './utils';\n"]}

View File

@@ -0,0 +1,74 @@
import { DiagLogger, Meter, MeterProvider, Tracer, TracerProvider, Span } from '@opentelemetry/api';
import { Logger, LoggerProvider } from '@opentelemetry/api-logs';
import { InstrumentationModuleDefinition, Instrumentation, InstrumentationConfig, SpanCustomizationHook } from './types';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export declare abstract class InstrumentationAbstract<ConfigType extends InstrumentationConfig = InstrumentationConfig> implements Instrumentation<ConfigType> {
readonly instrumentationName: string;
readonly instrumentationVersion: string;
protected _config: ConfigType;
private _tracer;
private _meter;
private _logger;
protected _diag: DiagLogger;
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
protected _wrap: <Nodule extends object, FieldName extends keyof Nodule>(nodule: Nodule, name: FieldName, wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _unwrap: <Nodule extends object>(nodule: Nodule, name: keyof Nodule) => void;
protected _massWrap: <Nodule extends object, FieldName extends keyof Nodule>(nodules: Nodule[], names: FieldName[], wrapper: (original: Nodule[FieldName]) => Nodule[FieldName]) => void;
protected _massUnwrap: <Nodule extends object>(nodules: Nodule[], names: (keyof Nodule)[]) => void;
protected get meter(): Meter;
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider: MeterProvider): void;
protected get logger(): Logger;
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider: LoggerProvider): void;
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions(): InstrumentationModuleDefinition[];
/**
* Sets the new metric instruments with the current Meter.
*/
protected _updateMetricInstruments(): void;
getConfig(): ConfigType;
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config: ConfigType): void;
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider: TracerProvider): void;
protected get tracer(): Tracer;
abstract enable(): void;
abstract disable(): void;
/**
* Init method in which plugin should define _modules and patches for
* methods.
*/
protected abstract init(): InstrumentationModuleDefinition | InstrumentationModuleDefinition[] | void;
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
protected _runSpanCustomizationHook<SpanCustomizationInfoType>(hookHandler: SpanCustomizationHook<SpanCustomizationInfoType> | undefined, triggerName: string, span: Span, info: SpanCustomizationInfoType): void;
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,141 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag, metrics, trace, } from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import * as shimmer from 'shimmer';
/**
* Base abstract internal class for instrumenting node and web plugins
*/
export class InstrumentationAbstract {
instrumentationName;
instrumentationVersion;
_config = {};
_tracer;
_meter;
_logger;
_diag;
constructor(instrumentationName, instrumentationVersion, config) {
this.instrumentationName = instrumentationName;
this.instrumentationVersion = instrumentationVersion;
this.setConfig(config);
this._diag = diag.createComponentLogger({
namespace: instrumentationName,
});
this._tracer = trace.getTracer(instrumentationName, instrumentationVersion);
this._meter = metrics.getMeter(instrumentationName, instrumentationVersion);
this._logger = logs.getLogger(instrumentationName, instrumentationVersion);
this._updateMetricInstruments();
}
/* Api to wrap instrumented method */
_wrap = shimmer.wrap;
/* Api to unwrap instrumented methods */
_unwrap = shimmer.unwrap;
/* Api to mass wrap instrumented method */
_massWrap = shimmer.massWrap;
/* Api to mass unwrap instrumented methods */
_massUnwrap = shimmer.massUnwrap;
/* Returns meter */
get meter() {
return this._meter;
}
/**
* Sets MeterProvider to this plugin
* @param meterProvider
*/
setMeterProvider(meterProvider) {
this._meter = meterProvider.getMeter(this.instrumentationName, this.instrumentationVersion);
this._updateMetricInstruments();
}
/* Returns logger */
get logger() {
return this._logger;
}
/**
* Sets LoggerProvider to this plugin
* @param loggerProvider
*/
setLoggerProvider(loggerProvider) {
this._logger = loggerProvider.getLogger(this.instrumentationName, this.instrumentationVersion);
}
/**
* @experimental
*
* Get module definitions defined by {@link init}.
* This can be used for experimental compile-time instrumentation.
*
* @returns an array of {@link InstrumentationModuleDefinition}
*/
getModuleDefinitions() {
const initResult = this.init() ?? [];
if (!Array.isArray(initResult)) {
return [initResult];
}
return initResult;
}
/**
* Sets the new metric instruments with the current Meter.
*/
_updateMetricInstruments() {
return;
}
/* Returns InstrumentationConfig */
getConfig() {
return this._config;
}
/**
* Sets InstrumentationConfig to this plugin
* @param config
*/
setConfig(config) {
// copy config first level properties to ensure they are immutable.
// nested properties are not copied, thus are mutable from the outside.
this._config = {
enabled: true,
...config,
};
}
/**
* Sets TraceProvider to this plugin
* @param tracerProvider
*/
setTracerProvider(tracerProvider) {
this._tracer = tracerProvider.getTracer(this.instrumentationName, this.instrumentationVersion);
}
/* Returns tracer */
get tracer() {
return this._tracer;
}
/**
* Execute span customization hook, if configured, and log any errors.
* Any semantics of the trigger and info are defined by the specific instrumentation.
* @param hookHandler The optional hook handler which the user has configured via instrumentation config
* @param triggerName The name of the trigger for executing the hook for logging purposes
* @param span The span to which the hook should be applied
* @param info The info object to be passed to the hook, with useful data the hook may use
*/
_runSpanCustomizationHook(hookHandler, triggerName, span, info) {
if (!hookHandler) {
return;
}
try {
hookHandler(span, info);
}
catch (e) {
this._diag.error(`Error running span customization hook due to exception in handler`, { triggerName }, e);
}
}
}
//# sourceMappingURL=instrumentation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,10 @@
import { InstrumentationModuleDefinition, InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleDefinition implements InstrumentationModuleDefinition {
name: string;
supportedVersions: string[];
patch?: ((exports: any, moduleVersion?: string) => any) | undefined;
unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined;
files: InstrumentationModuleFile[];
constructor(name: string, supportedVersions: string[], patch?: ((exports: any, moduleVersion?: string) => any) | undefined, unpatch?: ((exports: any, moduleVersion?: string) => void) | undefined, files?: InstrumentationModuleFile[]);
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.d.ts.map

View File

@@ -0,0 +1,34 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class InstrumentationNodeModuleDefinition {
name;
supportedVersions;
patch;
unpatch;
files;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch, files) {
this.name = name;
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.files = files || [];
}
}
//# sourceMappingURL=instrumentationNodeModuleDefinition.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleDefinition.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleDefinition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,MAAM,OAAO,mCAAmC;IAKrC;IACA;IAEA;IAEA;IAPT,KAAK,CAA8B;IACnC,YACS,IAAY,EACZ,iBAA2B;IAClC,8DAA8D;IACvD,KAAqD;IAC5D,8DAA8D;IACvD,OAAwD,EAC/D,KAAmC;QAN5B,SAAI,GAAJ,IAAI,CAAQ;QACZ,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAgD;QAErD,YAAO,GAAP,OAAO,CAAiD;QAG/D,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,EAAE,CAAC;IAC3B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n InstrumentationModuleDefinition,\n InstrumentationModuleFile,\n} from './types';\n\nexport class InstrumentationNodeModuleDefinition\n implements InstrumentationModuleDefinition\n{\n files: InstrumentationModuleFile[];\n constructor(\n public name: string,\n public supportedVersions: string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public patch?: (exports: any, moduleVersion?: string) => any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public unpatch?: (exports: any, moduleVersion?: string) => void,\n files?: InstrumentationModuleFile[]\n ) {\n this.files = files || [];\n }\n}\n"]}

View File

@@ -0,0 +1,9 @@
import { InstrumentationModuleFile } from './types';
export declare class InstrumentationNodeModuleFile implements InstrumentationModuleFile {
supportedVersions: string[];
patch: (moduleExports: any, moduleVersion?: string) => any;
unpatch: (moduleExports?: any, moduleVersion?: string) => void;
name: string;
constructor(name: string, supportedVersions: string[], patch: (moduleExports: any, moduleVersion?: string) => any, unpatch: (moduleExports?: any, moduleVersion?: string) => void);
}
//# sourceMappingURL=instrumentationNodeModuleFile.d.ts.map

View File

@@ -0,0 +1,33 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { normalize } from './platform/index';
export class InstrumentationNodeModuleFile {
supportedVersions;
patch;
unpatch;
name;
constructor(name, supportedVersions,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
patch,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
unpatch) {
this.supportedVersions = supportedVersions;
this.patch = patch;
this.unpatch = unpatch;
this.name = normalize(name);
}
}
//# sourceMappingURL=instrumentationNodeModuleFile.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentationNodeModuleFile.js","sourceRoot":"","sources":["../../src/instrumentationNodeModuleFile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAE7C,MAAM,OAAO,6BAA6B;IAM/B;IAEA;IAEA;IAPF,IAAI,CAAS;IACpB,YACE,IAAY,EACL,iBAA2B;IAClC,8DAA8D;IACvD,KAA0D;IACjE,8DAA8D;IACvD,OAA8D;QAJ9D,sBAAiB,GAAjB,iBAAiB,CAAU;QAE3B,UAAK,GAAL,KAAK,CAAqD;QAE1D,YAAO,GAAP,OAAO,CAAuD;QAErE,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentationModuleFile } from './types';\nimport { normalize } from './platform/index';\n\nexport class InstrumentationNodeModuleFile\n implements InstrumentationModuleFile\n{\n public name: string;\n constructor(\n name: string,\n public supportedVersions: string[],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public patch: (moduleExports: any, moduleVersion?: string) => any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public unpatch: (moduleExports?: any, moduleVersion?: string) => void\n ) {\n this.name = normalize(name);\n }\n}\n"]}

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './noop-normalize';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/browser/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase } from './instrumentation';\nexport { normalize } from './noop-normalize';\n"]}

View File

@@ -0,0 +1,10 @@
import { InstrumentationAbstract } from '../../instrumentation';
import * as types from '../../types';
import { InstrumentationConfig } from '../../types';
/**
* Base abstract class for instrumenting web plugins
*/
export declare abstract class InstrumentationBase<ConfigType extends InstrumentationConfig = InstrumentationConfig> extends InstrumentationAbstract<ConfigType> implements types.Instrumentation<ConfigType> {
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
}
//# sourceMappingURL=instrumentation.d.ts.map

View File

@@ -0,0 +1,28 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { InstrumentationAbstract } from '../../instrumentation';
/**
* Base abstract class for instrumenting web plugins
*/
export class InstrumentationBase extends InstrumentationAbstract {
constructor(instrumentationName, instrumentationVersion, config) {
super(instrumentationName, instrumentationVersion, config);
if (this._config.enabled) {
this.enable();
}
}
}
//# sourceMappingURL=instrumentation.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../../../src/platform/browser/instrumentation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAIhE;;GAEG;AACH,MAAM,OAAgB,mBAGpB,SAAQ,uBAAmC;IAG3C,YACE,mBAA2B,EAC3B,sBAA8B,EAC9B,MAAkB;QAElB,KAAK,CAAC,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,CAAC,CAAC;QAE3D,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACxB,IAAI,CAAC,MAAM,EAAE,CAAC;SACf;IACH,CAAC;CACF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentationAbstract } from '../../instrumentation';\nimport * as types from '../../types';\nimport { InstrumentationConfig } from '../../types';\n\n/**\n * Base abstract class for instrumenting web plugins\n */\nexport abstract class InstrumentationBase<\n ConfigType extends InstrumentationConfig = InstrumentationConfig,\n >\n extends InstrumentationAbstract<ConfigType>\n implements types.Instrumentation<ConfigType>\n{\n constructor(\n instrumentationName: string,\n instrumentationVersion: string,\n config: ConfigType\n ) {\n super(instrumentationName, instrumentationVersion, config);\n\n if (this._config.enabled) {\n this.enable();\n }\n }\n}\n"]}

View File

@@ -0,0 +1,13 @@
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export declare function normalize(path: string): string;
//# sourceMappingURL=noop-normalize.d.ts.map

View File

@@ -0,0 +1,32 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag } from '@opentelemetry/api';
/**
* Placeholder normalize function to replace the node variant in browser runtimes,
* this should never be called and will perform a no-op and warn if it is called regardless.
*
* This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation
* package can be made node-only.
*
* @param path input path
* @return unmodified path
* @internal
*/
export function normalize(path) {
diag.warn('Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)');
return path;
}
//# sourceMappingURL=noop-normalize.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"noop-normalize.js","sourceRoot":"","sources":["../../../../src/platform/browser/noop-normalize.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAE1C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,CAAC,IAAI,CACP,yOAAyO,CAC1O,CAAC;IACF,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { diag } from '@opentelemetry/api';\n\n/**\n * Placeholder normalize function to replace the node variant in browser runtimes,\n * this should never be called and will perform a no-op and warn if it is called regardless.\n *\n * This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/4373 until the instrumentation\n * package can be made node-only.\n *\n * @param path input path\n * @return unmodified path\n * @internal\n */\nexport function normalize(path: string): string {\n diag.warn(\n 'Path normalization is not implemented for this platform. To silence this warning, ensure no node-specific instrumentations are loaded, and node-specific types (e.g. InstrumentationNodeModuleFile), are not used in a browser context)'\n );\n return path;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase, normalize } from './node';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/platform/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { InstrumentationBase, normalize } from './node';\n"]}

View File

@@ -0,0 +1,36 @@
import type { Hooked } from './RequireInTheMiddleSingleton';
export declare const ModuleNameSeparator = "/";
type ModuleNameTrieSearchOptions = {
/**
* Whether to return the results in insertion order
*/
maintainInsertionOrder?: boolean;
/**
* Whether to return only full matches
*/
fullOnly?: boolean;
};
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export declare class ModuleNameTrie {
private _trie;
private _counter;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook: Hooked): void;
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName: string, { maintainInsertionOrder, fullOnly }?: ModuleNameTrieSearchOptions): Hooked[];
}
export {};
//# sourceMappingURL=ModuleNameTrie.d.ts.map

View File

@@ -0,0 +1,85 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const ModuleNameSeparator = '/';
/**
* Node in a `ModuleNameTrie`
*/
class ModuleNameTrieNode {
hooks = [];
children = new Map();
}
/**
* Trie containing nodes that represent a part of a module name (i.e. the parts separated by forward slash)
*/
export class ModuleNameTrie {
_trie = new ModuleNameTrieNode();
_counter = 0;
/**
* Insert a module hook into the trie
*
* @param {Hooked} hook Hook
*/
insert(hook) {
let trieNode = this._trie;
for (const moduleNamePart of hook.moduleName.split(ModuleNameSeparator)) {
let nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
nextNode = new ModuleNameTrieNode();
trieNode.children.set(moduleNamePart, nextNode);
}
trieNode = nextNode;
}
trieNode.hooks.push({ hook, insertedId: this._counter++ });
}
/**
* Search for matching hooks in the trie
*
* @param {string} moduleName Module name
* @param {boolean} maintainInsertionOrder Whether to return the results in insertion order
* @param {boolean} fullOnly Whether to return only full matches
* @returns {Hooked[]} Matching hooks
*/
search(moduleName, { maintainInsertionOrder, fullOnly } = {}) {
let trieNode = this._trie;
const results = [];
let foundFull = true;
for (const moduleNamePart of moduleName.split(ModuleNameSeparator)) {
const nextNode = trieNode.children.get(moduleNamePart);
if (!nextNode) {
foundFull = false;
break;
}
if (!fullOnly) {
results.push(...nextNode.hooks);
}
trieNode = nextNode;
}
if (fullOnly && foundFull) {
results.push(...trieNode.hooks);
}
if (results.length === 0) {
return [];
}
if (results.length === 1) {
return [results[0].hook];
}
if (maintainInsertionOrder) {
results.sort((a, b) => a.insertedId - b.insertedId);
}
return results.map(({ hook }) => hook);
}
}
//# sourceMappingURL=ModuleNameTrie.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,35 @@
import type { OnRequireFn } from 'require-in-the-middle';
export type Hooked = {
moduleName: string;
onRequire: OnRequireFn;
};
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export declare class RequireInTheMiddleSingleton {
private _moduleNameTrie;
private static _instance?;
private constructor();
private _initialize;
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName: string, onRequire: OnRequireFn): Hooked;
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance(): RequireInTheMiddleSingleton;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.d.ts.map

View File

@@ -0,0 +1,107 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Hook } from 'require-in-the-middle';
import * as path from 'path';
import { ModuleNameTrie, ModuleNameSeparator } from './ModuleNameTrie';
/**
* Whether Mocha is running in this process
* Inspired by https://github.com/AndreasPizsa/detect-mocha
*
* @type {boolean}
*/
const isMocha = [
'afterEach',
'after',
'beforeEach',
'before',
'describe',
'it',
].every(fn => {
// @ts-expect-error TS7053: Element implicitly has an 'any' type
return typeof global[fn] === 'function';
});
/**
* Singleton class for `require-in-the-middle`
* Allows instrumentation plugins to patch modules with only a single `require` patch
* WARNING: Because this class will create its own `require-in-the-middle` (RITM) instance,
* we should minimize the number of new instances of this class.
* Multiple instances of `@opentelemetry/instrumentation` (e.g. multiple versions) in a single process
* will result in multiple instances of RITM, which will have an impact
* on the performance of instrumentation hooks being applied.
*/
export class RequireInTheMiddleSingleton {
_moduleNameTrie = new ModuleNameTrie();
static _instance;
constructor() {
this._initialize();
}
_initialize() {
new Hook(
// Intercept all `require` calls; we will filter the matching ones below
null, { internals: true }, (exports, name, basedir) => {
// For internal files on Windows, `name` will use backslash as the path separator
const normalizedModuleName = normalizePathSeparators(name);
const matches = this._moduleNameTrie.search(normalizedModuleName, {
maintainInsertionOrder: true,
// For core modules (e.g. `fs`), do not match on sub-paths (e.g. `fs/promises').
// This matches the behavior of `require-in-the-middle`.
// `basedir` is always `undefined` for core modules.
fullOnly: basedir === undefined,
});
for (const { onRequire } of matches) {
exports = onRequire(exports, name, basedir);
}
return exports;
});
}
/**
* Register a hook with `require-in-the-middle`
*
* @param {string} moduleName Module name
* @param {OnRequireFn} onRequire Hook function
* @returns {Hooked} Registered hook
*/
register(moduleName, onRequire) {
const hooked = { moduleName, onRequire };
this._moduleNameTrie.insert(hooked);
return hooked;
}
/**
* Get the `RequireInTheMiddleSingleton` singleton
*
* @returns {RequireInTheMiddleSingleton} Singleton of `RequireInTheMiddleSingleton`
*/
static getInstance() {
// Mocha runs all test suites in the same process
// This prevents test suites from sharing a singleton
if (isMocha)
return new RequireInTheMiddleSingleton();
return (this._instance =
this._instance ?? new RequireInTheMiddleSingleton());
}
}
/**
* Normalize the path separators to forward slash in a module name or path
*
* @param {string} moduleNameOrPath Module name or path
* @returns {string} Normalized module name or path
*/
function normalizePathSeparators(moduleNameOrPath) {
return path.sep !== ModuleNameSeparator
? moduleNameOrPath.split(path.sep).join(ModuleNameSeparator)
: moduleNameOrPath;
}
//# sourceMappingURL=RequireInTheMiddleSingleton.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,18 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export { InstrumentationBase } from './instrumentation';
export { normalize } from './normalize';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/platform/node/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport { InstrumentationBase } from './instrumentation';\nexport { normalize } from './normalize';\n"]}

View File

@@ -0,0 +1,25 @@
import * as types from '../../types';
import { wrap, unwrap, massWrap, massUnwrap } from 'shimmer';
import { InstrumentationAbstract } from '../../instrumentation';
import { InstrumentationConfig } from '../../types';
/**
* Base abstract class for instrumenting node plugins
*/
export declare abstract class InstrumentationBase<ConfigType extends InstrumentationConfig = InstrumentationConfig> extends InstrumentationAbstract<ConfigType> implements types.Instrumentation<ConfigType> {
private _modules;
private _hooks;
private _requireInTheMiddleSingleton;
private _enabled;
constructor(instrumentationName: string, instrumentationVersion: string, config: ConfigType);
protected _wrap: typeof wrap;
protected _unwrap: typeof unwrap;
protected _massWrap: typeof massWrap;
protected _massUnwrap: typeof massUnwrap;
private _warnOnPreloadedModules;
private _extractPackageVersion;
private _onRequire;
enable(): void;
disable(): void;
isEnabled(): boolean;
}
//# sourceMappingURL=instrumentation.d.ts.map

Some files were not shown because too many files have changed in this diff Show More