|
| 1 | +import type { Client } from '@sentry/core'; |
| 2 | +import { addNonEnumerableProperty } from '@sentry/core'; |
| 3 | +import { getOrchestrionInjectedModules } from './detect'; |
| 4 | + |
| 5 | +const INSTRUMENTATION_FN_SYMBOL = Symbol.for('InstrumentationFn'); |
| 6 | +type InstrumentationFn = (() => void) & { [INSTRUMENTATION_FN_SYMBOL]?: boolean }; |
| 7 | + |
| 8 | +/** |
| 9 | + * Instrument the provided callback to run when one of the provided module names has been orchestrion-injected already. |
| 10 | + * Make sure to pass the same callback instance to this as is passed to `instrumentOrchestrionLazy`. |
| 11 | + */ |
| 12 | +export function instrumentOrchestrion(moduleNames: string[], callback: InstrumentationFn) { |
| 13 | + if (hasBeenInjected(callback)) { |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + const modules = getOrchestrionInjectedModules(); |
| 18 | + if (moduleNames.some(name => modules.includes(name))) { |
| 19 | + callback(); |
| 20 | + markAsInjected(callback); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Run the provided instrumentation callback when one of the provided module names has been orchestrion-injected at runtime. |
| 26 | + * This listens to the `orchestrion.module-runtime-injected` event and runs the callback when the event is emitted. |
| 27 | + * Make sure to pass the same callback instance to this as is passed to `instrumentOrchestrion`. |
| 28 | + */ |
| 29 | +export function instrumentOrchestrionLazy(client: Client, moduleNames: string[], callback: InstrumentationFn) { |
| 30 | + if (hasBeenInjected(callback)) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + const cleanup = client.on('orchestrion.module-runtime-injected', (moduleName: string) => { |
| 35 | + if (moduleNames.includes(moduleName)) { |
| 36 | + if (hasBeenInjected(callback)) { |
| 37 | + cleanup(); |
| 38 | + return; |
| 39 | + } |
| 40 | + callback(); |
| 41 | + markAsInjected(callback); |
| 42 | + cleanup(); |
| 43 | + } |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +function hasBeenInjected(callback: InstrumentationFn) { |
| 48 | + return callback[INSTRUMENTATION_FN_SYMBOL] ?? false; |
| 49 | +} |
| 50 | + |
| 51 | +function markAsInjected(callback: InstrumentationFn) { |
| 52 | + addNonEnumerableProperty(callback, INSTRUMENTATION_FN_SYMBOL, true); |
| 53 | +} |
0 commit comments