UNPKG

nstdlib-nightly

Version:

Node.js standard library converted to runtime-agnostic ES modules.

89 lines (71 loc) 2.24 kB
// Source: https://github.com/nodejs/node/blob/65eff1eb/lib/trace_events.js import { hasTracing } from "nstdlib/stub/binding/config"; import { codes as __codes__ } from "nstdlib/lib/internal/errors"; import { ownsProcessState } from "nstdlib/lib/internal/worker"; import { CategorySet, getEnabledCategories, } from "nstdlib/stub/binding/trace_events"; import { customInspectSymbol } from "nstdlib/lib/internal/util"; import { format } from "nstdlib/lib/internal/util/inspect"; import { validateObject, validateStringArray, } from "nstdlib/lib/internal/validators"; const kMaxTracingCount = 10; const { ERR_TRACE_EVENTS_CATEGORY_REQUIRED, ERR_TRACE_EVENTS_UNAVAILABLE } = __codes__; if (!hasTracing || !ownsProcessState) throw new ERR_TRACE_EVENTS_UNAVAILABLE(); const enabledTracingObjects = new Set(); class Tracing { #handle; #categories; #enabled = false; constructor(categories) { this.#handle = new CategorySet(categories); this.#categories = categories; } enable() { if (!this.#enabled) { this.#enabled = true; this.#handle.enable(); enabledTracingObjects.add(this); if (enabledTracingObjects.size > kMaxTracingCount) { process.emitWarning( "Possible trace_events memory leak detected. There are more than " + `${kMaxTracingCount} enabled Tracing objects.`, ); } } } disable() { if (this.#enabled) { this.#enabled = false; this.#handle.disable(); enabledTracingObjects.delete(this); } } get enabled() { return this.#enabled; } get categories() { return Array.prototype.join.call(this.#categories, ","); } [customInspectSymbol](depth, opts) { if (typeof depth === "number" && depth < 0) return this; const obj = { enabled: this.enabled, categories: this.categories, }; return `Tracing ${format(obj)}`; } } function createTracing(options) { validateObject(options, "options"); validateStringArray(options.categories, "options.categories"); if (options.categories.length <= 0) throw new ERR_TRACE_EVENTS_CATEGORY_REQUIRED(); return new Tracing(options.categories); } export { createTracing }; export { getEnabledCategories };