{"version":3,"file":"instrumentation.mjs","names":["utilTypes","HookRequire","HookImport"],"sources":["../../../src/platform/node/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as types from '../../types';\nimport * as path from 'path';\nimport { types as utilTypes } from 'util';\nimport { satisfies } from '../../semver';\nimport type { massWrap, massUnwrap } from '../../shimmer';\nimport { wrap, unwrap } from '../../shimmer';\nimport { InstrumentationAbstract } from '../../instrumentation';\nimport type { Hooked } from './RequireInTheMiddleSingleton';\nimport { RequireInTheMiddleSingleton } from './RequireInTheMiddleSingleton';\nimport type { HookFn } from 'import-in-the-middle';\nimport { Hook as HookImport } from 'import-in-the-middle';\nimport type {\n  InstrumentationConfig,\n  InstrumentationModuleDefinition,\n} from '../../types';\nimport { diag } from '@opentelemetry/api';\nimport type { OnRequireFn } from 'require-in-the-middle';\nimport { Hook as HookRequire } from 'require-in-the-middle';\nimport { readFileSync } from 'fs';\nimport { isWrapped } from '../../utils';\n\n/**\n * Base abstract class for instrumenting node plugins\n */\nexport abstract class InstrumentationBase<\n    ConfigType extends InstrumentationConfig = InstrumentationConfig,\n  >\n  extends InstrumentationAbstract<ConfigType>\n  implements types.Instrumentation<ConfigType>\n{\n  private _modules: InstrumentationModuleDefinition[];\n  private _hooks: (Hooked | HookRequire)[] = [];\n  private _requireInTheMiddleSingleton: RequireInTheMiddleSingleton =\n    RequireInTheMiddleSingleton.getInstance();\n  /** Set by the base enable() and disable(); subclasses only read it. */\n  protected _enabled = false;\n\n  constructor(\n    instrumentationName: string,\n    instrumentationVersion: string,\n    config: ConfigType\n  ) {\n    super(instrumentationName, instrumentationVersion, config);\n\n    let modules = this.init();\n\n    if (modules && !Array.isArray(modules)) {\n      modules = [modules];\n    }\n\n    this._modules = (modules as InstrumentationModuleDefinition[]) || [];\n\n    if (this._config.enabled) {\n      this.enable();\n    }\n  }\n\n  protected override _wrap: typeof wrap = (moduleExports, name, wrapper) => {\n    if (isWrapped(moduleExports[name])) {\n      this._unwrap(moduleExports, name);\n    }\n    if (!utilTypes.isProxy(moduleExports)) {\n      return wrap(moduleExports, name, wrapper);\n    } else {\n      const wrapped = wrap(Object.assign({}, moduleExports), name, wrapper);\n      Object.defineProperty(moduleExports, name, {\n        value: wrapped,\n      });\n      return wrapped;\n    }\n  };\n\n  protected override _unwrap: typeof unwrap = (moduleExports, name) => {\n    if (!utilTypes.isProxy(moduleExports)) {\n      return unwrap(moduleExports, name);\n    } else {\n      return Object.defineProperty(moduleExports, name, {\n        value: moduleExports[name],\n      });\n    }\n  };\n\n  protected override _massWrap: typeof massWrap = (\n    moduleExportsArray,\n    names,\n    wrapper\n  ) => {\n    if (!moduleExportsArray) {\n      diag.error('must provide one or more modules to patch');\n      return;\n    } else if (!Array.isArray(moduleExportsArray)) {\n      moduleExportsArray = [moduleExportsArray];\n    }\n\n    if (!(names && Array.isArray(names))) {\n      diag.error('must provide one or more functions to wrap on modules');\n      return;\n    }\n\n    moduleExportsArray.forEach(moduleExports => {\n      names.forEach(name => {\n        this._wrap(moduleExports, name, wrapper);\n      });\n    });\n  };\n\n  protected override _massUnwrap: typeof massUnwrap = (\n    moduleExportsArray,\n    names\n  ) => {\n    if (!moduleExportsArray) {\n      diag.error('must provide one or more modules to patch');\n      return;\n    } else if (!Array.isArray(moduleExportsArray)) {\n      moduleExportsArray = [moduleExportsArray];\n    }\n\n    if (!(names && Array.isArray(names))) {\n      diag.error('must provide one or more functions to wrap on modules');\n      return;\n    }\n\n    moduleExportsArray.forEach(moduleExports => {\n      names.forEach(name => {\n        this._unwrap(moduleExports, name);\n      });\n    });\n  };\n\n  private _warnOnPreloadedModules(): void {\n    // Access require via globalThis to prevent webpack from analyzing it as a dependency expression\n    const nodeRequire = globalThis.require;\n    if (!nodeRequire?.resolve || !nodeRequire?.cache) return;\n\n    this._modules.forEach((module: InstrumentationModuleDefinition) => {\n      const { name } = module;\n      try {\n        const resolvedModule = nodeRequire.resolve(name);\n        if (nodeRequire.cache[resolvedModule]?.loaded) {\n          // Module is already cached, which means the instrumentation hook might not work\n          this._diag.warn(\n            `Module ${name} has been loaded before ${this.instrumentationName} so it might not work, please initialize it before requiring ${name}`\n          );\n        }\n      } catch {\n        // Module isn't available, we can simply skip\n      }\n    });\n  }\n\n  private _extractPackageVersion(baseDir: string): string | undefined {\n    try {\n      const json = readFileSync(path.join(baseDir, 'package.json'), {\n        encoding: 'utf8',\n      });\n      const version = JSON.parse(json).version;\n      return typeof version === 'string' ? version : undefined;\n    } catch {\n      diag.warn('Failed extracting version', baseDir);\n    }\n\n    return undefined;\n  }\n\n  private _onRequire<T>(\n    module: InstrumentationModuleDefinition,\n    exports: T,\n    name: string,\n    baseDir?: string | void\n  ): T {\n    if (!baseDir) {\n      if (typeof module.patch === 'function') {\n        module.moduleExports = exports;\n        if (this._enabled) {\n          this._diag.debug(\n            'Applying instrumentation patch for nodejs core module on require hook',\n            {\n              module: module.name,\n            }\n          );\n          return module.patch(exports);\n        }\n      }\n      return exports;\n    }\n\n    const version = this._extractPackageVersion(baseDir);\n    module.moduleVersion = version;\n    if (module.name === name) {\n      // main module\n      if (\n        isSupported(module.supportedVersions, version, module.includePrerelease)\n      ) {\n        if (typeof module.patch === 'function') {\n          module.moduleExports = exports;\n          if (this._enabled) {\n            this._diag.debug(\n              'Applying instrumentation patch for module on require hook',\n              {\n                module: module.name,\n                version: module.moduleVersion,\n                baseDir,\n              }\n            );\n            return module.patch(exports, module.moduleVersion);\n          }\n        }\n      }\n      return exports;\n    }\n    // internal file\n    const files = module.files ?? [];\n    const normalizedName = path.normalize(name);\n    const supportedFileInstrumentations = files.filter(\n      f =>\n        f.name === normalizedName &&\n        isSupported(f.supportedVersions, version, module.includePrerelease)\n    );\n    return supportedFileInstrumentations.reduce<T>((patchedExports, file) => {\n      file.moduleExports = patchedExports;\n      if (this._enabled) {\n        this._diag.debug(\n          'Applying instrumentation patch for nodejs module file on require hook',\n          {\n            module: module.name,\n            version: module.moduleVersion,\n            fileName: file.name,\n            baseDir,\n          }\n        );\n\n        // patch signature is not typed, so we cast it assuming it's correct\n        return file.patch(patchedExports, module.moduleVersion) as T;\n      }\n      return patchedExports;\n    }, exports);\n  }\n\n  public enable(): void {\n    if (this._enabled) {\n      return;\n    }\n    this._enabled = true;\n\n    // already hooked, just call patch again\n    if (this._hooks.length > 0) {\n      for (const module of this._modules) {\n        if (typeof module.patch === 'function' && module.moduleExports) {\n          this._diag.debug(\n            'Applying instrumentation patch for nodejs module on instrumentation enabled',\n            {\n              module: module.name,\n              version: module.moduleVersion,\n            }\n          );\n          module.patch(module.moduleExports, module.moduleVersion);\n        }\n        for (const file of module.files) {\n          if (file.moduleExports) {\n            this._diag.debug(\n              'Applying instrumentation patch for nodejs module file on instrumentation enabled',\n              {\n                module: module.name,\n                version: module.moduleVersion,\n                fileName: file.name,\n              }\n            );\n            file.patch(file.moduleExports, module.moduleVersion);\n          }\n        }\n      }\n      return;\n    }\n\n    this._warnOnPreloadedModules();\n    for (const module of this._modules) {\n      const hookFn: HookFn = (exports, name, baseDir) => {\n        if (!baseDir && path.isAbsolute(name)) {\n          // Change IITM `name` and `baseDir` values to match what RITM returns.\n          // See \"Comparing to RITM\" on https://github.com/nodejs/import-in-the-middle/pull/241\n          // for an example of the differences.\n          const parsedPath = path.parse(name);\n          name = parsedPath.name;\n          baseDir = parsedPath.dir;\n        }\n        return this._onRequire<typeof exports>(module, exports, name, baseDir);\n      };\n      const onRequire: OnRequireFn = (exports, name, baseDir) => {\n        return this._onRequire<typeof exports>(module, exports, name, baseDir);\n      };\n\n      // `RequireInTheMiddleSingleton` does not support absolute paths.\n      // For an absolute paths, we must create a separate instance of the\n      // require-in-the-middle `Hook`.\n      const hook = path.isAbsolute(module.name)\n        ? new HookRequire([module.name], { internals: true }, onRequire)\n        : this._requireInTheMiddleSingleton.register(module.name, onRequire);\n\n      this._hooks.push(hook);\n      const esmHook = new HookImport(\n        [module.name],\n        { internals: true },\n        <HookFn>hookFn\n      );\n      this._hooks.push(esmHook);\n    }\n  }\n\n  public disable(): void {\n    if (!this._enabled) {\n      return;\n    }\n    this._enabled = false;\n\n    for (const module of this._modules) {\n      if (typeof module.unpatch === 'function' && module.moduleExports) {\n        this._diag.debug(\n          'Removing instrumentation patch for nodejs module on instrumentation disabled',\n          {\n            module: module.name,\n            version: module.moduleVersion,\n          }\n        );\n        module.unpatch(module.moduleExports, module.moduleVersion);\n      }\n      for (const file of module.files) {\n        if (file.moduleExports) {\n          this._diag.debug(\n            'Removing instrumentation patch for nodejs module file on instrumentation disabled',\n            {\n              module: module.name,\n              version: module.moduleVersion,\n              fileName: file.name,\n            }\n          );\n          file.unpatch(file.moduleExports, module.moduleVersion);\n        }\n      }\n    }\n  }\n\n  public isEnabled(): boolean {\n    return this._enabled;\n  }\n}\n\nfunction isSupported(\n  supportedVersions: string[],\n  version?: string,\n  includePrerelease?: boolean\n): boolean {\n  if (typeof version === 'undefined') {\n    // If we don't have the version, accept the wildcard case only\n    return supportedVersions.includes('*');\n  }\n\n  return supportedVersions.some(supportedVersion => {\n    return satisfies(version, supportedVersion, { includePrerelease });\n  });\n}\n"],"mappings":";;;;;;;;;;;;;;;AA6BA,IAAsB,sBAAtB,cAGU,wBAEV;CACE;CACA,SAA2C,CAAC;CAC5C,+BACE,4BAA4B,YAAY;;CAE1C,WAAqB;CAErB,YACE,qBACA,wBACA,QACA;EACA,MAAM,qBAAqB,wBAAwB,MAAM;EAEzD,IAAI,UAAU,KAAK,KAAK;EAExB,IAAI,WAAW,CAAC,MAAM,QAAQ,OAAO,GACnC,UAAU,CAAC,OAAO;EAGpB,KAAK,WAAY,WAAiD,CAAC;EAEnE,IAAI,KAAK,QAAQ,SACf,KAAK,OAAO;CAEhB;CAEA,SAAyC,eAAe,MAAM,YAAY;EACxE,IAAI,UAAU,cAAc,KAAK,GAC/B,KAAK,QAAQ,eAAe,IAAI;EAElC,IAAI,CAACA,MAAU,QAAQ,aAAa,GAClC,OAAO,KAAK,eAAe,MAAM,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