_handlers.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { DEBUG_BUILD } from '../debug-build.js';
  2. import { logger } from '../logger.js';
  3. import { getFunctionName } from '../stacktrace.js';
  4. // We keep the handlers globally
  5. const handlers = {};
  6. const instrumented = {};
  7. /** Add a handler function. */
  8. function addHandler(type, handler) {
  9. handlers[type] = handlers[type] || [];
  10. (handlers[type] ).push(handler);
  11. }
  12. /**
  13. * Reset all instrumentation handlers.
  14. * This can be used by tests to ensure we have a clean slate of instrumentation handlers.
  15. */
  16. function resetInstrumentationHandlers() {
  17. Object.keys(handlers).forEach(key => {
  18. handlers[key ] = undefined;
  19. });
  20. }
  21. /** Maybe run an instrumentation function, unless it was already called. */
  22. function maybeInstrument(type, instrumentFn) {
  23. if (!instrumented[type]) {
  24. instrumentFn();
  25. instrumented[type] = true;
  26. }
  27. }
  28. /** Trigger handlers for a given instrumentation type. */
  29. function triggerHandlers(type, data) {
  30. const typeHandlers = type && handlers[type];
  31. if (!typeHandlers) {
  32. return;
  33. }
  34. for (const handler of typeHandlers) {
  35. try {
  36. handler(data);
  37. } catch (e) {
  38. DEBUG_BUILD &&
  39. logger.error(
  40. `Error while triggering instrumentation handler.\nType: ${type}\nName: ${getFunctionName(handler)}\nError:`,
  41. e,
  42. );
  43. }
  44. }
  45. }
  46. export { addHandler, maybeInstrument, resetInstrumentationHandlers, triggerHandlers };
  47. //# sourceMappingURL=_handlers.js.map