{"version":3,"file":"ZoneContextManager.cjs","names":["ROOT_CONTEXT","isListenerObject"],"sources":["../src/ZoneContextManager.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/// <reference types=\"zone.js\" />\nimport type { Context, ContextManager } from '@opentelemetry/api';\nimport { ROOT_CONTEXT } from '@opentelemetry/api';\nimport type { TargetWithEvents } from './types';\nimport { isListenerObject } from './util';\n\n/* Key name to be used to save a context reference in Zone */\nconst ZONE_CONTEXT_KEY = 'OT_ZONE_CONTEXT';\n\n/**\n * ZoneContextManager\n * This module provides an easy functionality for tracing action between asynchronous operations in web.\n * It was not possible with standard [StackContextManager]{@link https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/sdk-trace/src/StackContextManager.ts}.\n * It heavily depends on [zone.js]{@link https://www.npmjs.com/package/zone.js}.\n * It stores the information about context in zone. Each Context will have always new Zone;\n * It also supports binding a certain Span to a target that has \"addEventListener\" and \"removeEventListener\".\n * When this happens a new zone is being created and the provided Span is being assigned to this zone.\n */\nexport class ZoneContextManager implements ContextManager {\n  /**\n   * whether the context manager is enabled or not\n   */\n  private _enabled = false;\n\n  /**\n   * @param context A context (span) to be executed within target function\n   * @param target Function to be executed within the context\n   */\n  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n  private _bindFunction<T extends Function>(context: Context, target: T): T {\n    const manager = this;\n    const contextWrapper = function (this: unknown, ...args: unknown[]) {\n      return manager.with(context, () => target.apply(this, args));\n    };\n    Object.defineProperty(contextWrapper, 'length', {\n      enumerable: false,\n      configurable: true,\n      writable: false,\n      value: target.length,\n    });\n    return contextWrapper as unknown as T;\n  }\n\n  /**\n   * @param context A context (span) to be bind to target\n   * @param obj target object on which the listeners will be patched\n   */\n  private _bindListener<T>(context: Context, obj: T): T {\n    const target = obj as unknown as TargetWithEvents;\n    if (target.__ot_listeners !== undefined) {\n      return obj;\n    }\n    target.__ot_listeners = {};\n\n    if (typeof target.addEventListener === 'function') {\n      target.addEventListener = this._patchAddEventListener(\n        target,\n        target.addEventListener,\n        context\n      );\n    }\n\n    if (typeof target.removeEventListener === 'function') {\n      target.removeEventListener = this._patchRemoveEventListener(\n        target,\n        target.removeEventListener\n      );\n    }\n\n    return obj;\n  }\n\n  /**\n   * Creates a new zone\n   * @param zoneName zone name\n   * @param context A context (span) to be bind with Zone\n   */\n  private _createZone(zoneName: string, context: unknown): Zone {\n    return Zone.current.fork({\n      name: zoneName,\n      properties: {\n        [ZONE_CONTEXT_KEY]: context,\n      },\n      onCancelTask(\n        parentZoneDelegate: ZoneDelegate,\n        currentZone: Zone,\n        targetZone: Zone,\n        task: Task\n      ): Task {\n        if (task.state === 'notScheduled' || task.state === 'running') {\n          return task;\n        }\n        return parentZoneDelegate.cancelTask(targetZone, task);\n      },\n    });\n  }\n\n  /**\n   * Patches addEventListener method\n   * @param target any target that has \"addEventListener\" method\n   * @param original reference to the patched method\n   * @param [context] context to be bind to the listener\n   */\n  private _patchAddEventListener(\n    target: TargetWithEvents,\n    original: NonNullable<TargetWithEvents['addEventListener']>,\n    context: Context\n  ) {\n    const contextManager = this;\n\n    return function (this: TargetWithEvents, event, listener, opts) {\n      if (target.__ot_listeners === undefined) {\n        target.__ot_listeners = {};\n      }\n      let listeners = target.__ot_listeners[event];\n      if (listeners === undefined) {\n        listeners = new WeakMap();\n        target.__ot_listeners[event] = listeners;\n      }\n      const patchedListener = contextManager.bind(context, listener);\n      // store a weak reference of the user listener to ours\n      listeners.set(listener, patchedListener);\n      return original.call(this, event, patchedListener, opts);\n    } as TargetWithEvents['addEventListener'];\n  }\n\n  /**\n   * Patches removeEventListener method\n   * @param target any target that has \"removeEventListener\" method\n   * @param original reference to the patched method\n   */\n  private _patchRemoveEventListener(\n    target: TargetWithEvents,\n    original: NonNullable<TargetWithEvents['removeEventListener']>\n  ) {\n    return function (this: TargetWithEvents, event, listener) {\n      if (\n        target.__ot_listeners === undefined ||\n        target.__ot_listeners[event] === undefined\n      ) {\n        return original.call(this, event, listener);\n      }\n      const events = target.__ot_listeners[event];\n      const patchedListener = events.get(listener);\n      events.delete(listener);\n      return original.call(this, event, patchedListener || listener);\n    } as TargetWithEvents['removeEventListener'];\n  }\n\n  /**\n   * Returns the active context\n   */\n  active(): Context {\n    if (!this._enabled || !Zone.current) {\n      return ROOT_CONTEXT;\n    }\n    return Zone.current.get(ZONE_CONTEXT_KEY) || ROOT_CONTEXT;\n  }\n\n  /**\n   * Binds a the certain context or the active one to the target function and then returns the target\n   * @param context A context (span) to be bind to target\n   * @param target a function or event emitter. When target or one of its callbacks is called,\n   *  the provided context will be used as the active context for the duration of the call.\n   */\n  bind<T>(context: Context, target: T | TargetWithEvents): T {\n    if (typeof target === 'function') {\n      return this._bindFunction(context, target);\n    } else if (isListenerObject(target)) {\n      this._bindListener(context, target);\n    }\n    return target as unknown as T;\n  }\n\n  /**\n   * Disable the context manager (clears all the contexts)\n   */\n  disable(): this {\n    this._enabled = false;\n    return this;\n  }\n\n  /**\n   * Enables the context manager and creates a default(root) context\n   */\n  enable(): this {\n    this._enabled = true;\n    return this;\n  }\n\n  /**\n   * Calls the callback function [fn] with the provided [context].\n   *     If [context] is undefined then it will use the active context.\n   *     The context will be set as active\n   * @param context A context (span) to be called with provided callback\n   * @param fn Callback function\n   * @param thisArg optional receiver to be used for calling fn\n   * @param args optional arguments forwarded to fn\n   */\n  with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n    context: Context | null,\n    fn: F,\n    thisArg?: ThisParameterType<F>,\n    ...args: A\n  ): ReturnType<F> {\n    let zoneName = 'otel:with';\n    if (fn.name) {\n      zoneName += `:${fn.name}`;\n    }\n    return this._createZone(zoneName, context).run(fn, thisArg, args);\n  }\n}\n"],"mappings":";;;AAYA,MAAM,mBAAmB;;;;;;;;;;AAWzB,IAAa,qBAAb,MAA0D;;;;CAIxD,WAAmB;;;;;CAOnB,cAA0C,SAAkB,QAAc;EACxE,MAAM,UAAU;EAChB,MAAM,iBAAiB,SAAyB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