@code-pushup/utils 0.109.0 → 0.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,11 @@
1
+ import { type PerformanceObserverOptions } from '../performance-observer.js';
1
2
  import { type ActionTrackConfigs, type MeasureCtxOptions, type MeasureOptions } from '../user-timing-extensibility-api-utils.js';
2
3
  import type { ActionTrackEntryPayload, DevToolsColor, EntryMeta } from '../user-timing-extensibility-api.type.js';
4
+ import type { AppendableSink } from '../wal.js';
5
+ /**
6
+ * Generates a unique profiler ID based on performance time origin, process ID, thread ID, and instance count.
7
+ */
8
+ export declare function getProfilerId(): string;
3
9
  /**
4
10
  * Configuration options for creating a Profiler instance.
5
11
  *
@@ -41,6 +47,8 @@ export type ProfilerOptions<T extends ActionTrackConfigs = ActionTrackConfigs> =
41
47
  */
42
48
  export declare class Profiler<T extends ActionTrackConfigs> {
43
49
  #private;
50
+ static instanceCount: number;
51
+ readonly id: string;
44
52
  readonly tracks: Record<keyof T, ActionTrackEntryPayload> | undefined;
45
53
  /**
46
54
  * Creates a new Profiler instance with the specified configuration.
@@ -131,4 +139,84 @@ export declare class Profiler<T extends ActionTrackConfigs> {
131
139
  */
132
140
  measureAsync<R>(event: string, work: () => Promise<R>, options?: MeasureOptions<R>): Promise<R>;
133
141
  }
142
+ /**
143
+ * Options for configuring a NodejsProfiler instance.
144
+ *
145
+ * Extends ProfilerOptions with a required sink parameter.
146
+ *
147
+ * @template Tracks - Record type defining available track names and their configurations
148
+ */
149
+ export type NodejsProfilerOptions<DomainEvents, Tracks extends Record<string, ActionTrackEntryPayload>> = ProfilerOptions<Tracks> & Omit<PerformanceObserverOptions<DomainEvents>, 'sink'> & {
150
+ /**
151
+ * Sink for buffering and flushing performance data
152
+ */
153
+ sink: AppendableSink<DomainEvents>;
154
+ /**
155
+ * Name of the environment variable to check for debug mode.
156
+ * When the env var is set to 'true', profiler state transitions create performance marks for debugging.
157
+ *
158
+ * @default 'CP_PROFILER_DEBUG'
159
+ */
160
+ debugEnvVar?: string;
161
+ };
162
+ /**
163
+ * Performance profiler with automatic process exit handling for buffered performance data.
164
+ *
165
+ * This class extends the base {@link Profiler} with automatic flushing of performance data
166
+ * when the process exits. It accepts a {@link PerformanceObserverSink} that buffers performance
167
+ * entries and ensures they are written out during process termination, even for unexpected exits.
168
+ *
169
+ * The sink defines the output format for performance data, enabling flexible serialization
170
+ * to various formats such as DevTools TraceEvent JSON, OpenTelemetry protocol buffers,
171
+ * or custom domain-specific formats.
172
+ *
173
+ * The profiler automatically subscribes to the performance observer when enabled and installs
174
+ * exit handlers that flush buffered data on process termination (signals, fatal errors, or normal exit).
175
+ *
176
+ */
177
+ export declare class NodejsProfiler<DomainEvents, Tracks extends Record<string, ActionTrackEntryPayload> = Record<string, ActionTrackEntryPayload>> extends Profiler<Tracks> {
178
+ #private;
179
+ /**
180
+ * Creates a NodejsProfiler instance.
181
+ * @param options - Configuration with required sink
182
+ */
183
+ constructor(options: NodejsProfilerOptions<DomainEvents, Tracks>);
184
+ /**
185
+ * Returns whether debug mode is enabled for profiler state transitions.
186
+ *
187
+ * Debug mode is determined by the environment variable specified by `debugEnvVar`
188
+ * (defaults to 'CP_PROFILER_DEBUG'). When enabled, profiler state transitions create
189
+ * performance marks for debugging.
190
+ *
191
+ * @returns true if debug mode is enabled, false otherwise
192
+ */
193
+ get debug(): boolean;
194
+ /**
195
+ * Closes profiler and releases resources. Idempotent, safe for exit handlers.
196
+ * **Exit Handler Usage**: Call only this method from process exit handlers.
197
+ */
198
+ close(): void;
199
+ /** @returns Current profiler state */
200
+ get state(): 'idle' | 'running' | 'closed';
201
+ /** @returns Whether profiler is in 'running' state */
202
+ isEnabled(): boolean;
203
+ /** Enables profiling (start/stop) */
204
+ setEnabled(enabled: boolean): void;
205
+ /** @returns Queue statistics and profiling state for monitoring */
206
+ get stats(): {
207
+ debug: boolean;
208
+ state: "idle" | "running" | "closed";
209
+ walOpen: boolean;
210
+ isSubscribed: boolean;
211
+ queued: number;
212
+ dropped: number;
213
+ written: number;
214
+ maxQueueSize: number;
215
+ flushThreshold: number;
216
+ addedSinceLastFlush: number;
217
+ buffered: boolean;
218
+ };
219
+ /** Flushes buffered performance data to sink. */
220
+ flush(): void;
221
+ }
134
222
  export {};
@@ -1,7 +1,18 @@
1
+ import { performance } from 'node:perf_hooks';
1
2
  import process from 'node:process';
3
+ import { threadId } from 'node:worker_threads';
2
4
  import { isEnvVarEnabled } from '../env.js';
5
+ import { PerformanceObserverSink, } from '../performance-observer.js';
6
+ import { objectToEntries } from '../transform.js';
3
7
  import { asOptions, markerPayload, measureCtx, setupTracks, } from '../user-timing-extensibility-api-utils.js';
4
- import { PROFILER_ENABLED_ENV_VAR } from './constants.js';
8
+ import { PROFILER_DEBUG_ENV_VAR, PROFILER_ENABLED_ENV_VAR, } from './constants.js';
9
+ /**
10
+ * Generates a unique profiler ID based on performance time origin, process ID, thread ID, and instance count.
11
+ */
12
+ export function getProfilerId() {
13
+ // eslint-disable-next-line functional/immutable-data
14
+ return `${Math.round(performance.timeOrigin)}.${process.pid}.${threadId}.${++Profiler.instanceCount}`;
15
+ }
5
16
  /**
6
17
  * Performance profiler that creates structured timing measurements with Chrome DevTools Extensibility API payloads.
7
18
  *
@@ -10,7 +21,9 @@ import { PROFILER_ENABLED_ENV_VAR } from './constants.js';
10
21
  *
11
22
  */
12
23
  export class Profiler {
13
- #enabled;
24
+ static instanceCount = 0;
25
+ id = getProfilerId();
26
+ #enabled = false;
14
27
  #defaults;
15
28
  tracks;
16
29
  #ctxOf;
@@ -86,7 +99,7 @@ export class Profiler {
86
99
  * });
87
100
  */
88
101
  marker(name, opt) {
89
- if (!this.#enabled) {
102
+ if (!this.isEnabled()) {
90
103
  return;
91
104
  }
92
105
  performance.mark(name, asOptions(markerPayload({
@@ -112,7 +125,7 @@ export class Profiler {
112
125
  *
113
126
  */
114
127
  measure(event, work, options) {
115
- if (!this.#enabled) {
128
+ if (!this.isEnabled()) {
116
129
  return work();
117
130
  }
118
131
  const { start, success, error } = this.#ctxOf(event, options);
@@ -144,7 +157,7 @@ export class Profiler {
144
157
  *
145
158
  */
146
159
  async measureAsync(event, work, options) {
147
- if (!this.#enabled) {
160
+ if (!this.isEnabled()) {
148
161
  return await work();
149
162
  }
150
163
  const { start, success, error } = this.#ctxOf(event, options);
@@ -160,4 +173,143 @@ export class Profiler {
160
173
  }
161
174
  }
162
175
  }
176
+ /**
177
+ * Performance profiler with automatic process exit handling for buffered performance data.
178
+ *
179
+ * This class extends the base {@link Profiler} with automatic flushing of performance data
180
+ * when the process exits. It accepts a {@link PerformanceObserverSink} that buffers performance
181
+ * entries and ensures they are written out during process termination, even for unexpected exits.
182
+ *
183
+ * The sink defines the output format for performance data, enabling flexible serialization
184
+ * to various formats such as DevTools TraceEvent JSON, OpenTelemetry protocol buffers,
185
+ * or custom domain-specific formats.
186
+ *
187
+ * The profiler automatically subscribes to the performance observer when enabled and installs
188
+ * exit handlers that flush buffered data on process termination (signals, fatal errors, or normal exit).
189
+ *
190
+ */
191
+ export class NodejsProfiler extends Profiler {
192
+ #sink;
193
+ #performanceObserverSink;
194
+ #state = 'idle';
195
+ #debug;
196
+ /**
197
+ * Creates a NodejsProfiler instance.
198
+ * @param options - Configuration with required sink
199
+ */
200
+ constructor(options) {
201
+ const { sink, encodePerfEntry, captureBufferedEntries, flushThreshold, maxQueueSize, enabled, debugEnvVar = PROFILER_DEBUG_ENV_VAR, ...profilerOptions } = options;
202
+ const initialEnabled = enabled ?? isEnvVarEnabled(PROFILER_ENABLED_ENV_VAR);
203
+ super({ ...profilerOptions, enabled: initialEnabled });
204
+ this.#sink = sink;
205
+ this.#debug = isEnvVarEnabled(debugEnvVar);
206
+ this.#performanceObserverSink = new PerformanceObserverSink({
207
+ sink,
208
+ encodePerfEntry,
209
+ captureBufferedEntries,
210
+ flushThreshold,
211
+ maxQueueSize,
212
+ debugEnvVar,
213
+ });
214
+ if (initialEnabled) {
215
+ this.#transition('running');
216
+ }
217
+ }
218
+ /**
219
+ * Returns whether debug mode is enabled for profiler state transitions.
220
+ *
221
+ * Debug mode is determined by the environment variable specified by `debugEnvVar`
222
+ * (defaults to 'CP_PROFILER_DEBUG'). When enabled, profiler state transitions create
223
+ * performance marks for debugging.
224
+ *
225
+ * @returns true if debug mode is enabled, false otherwise
226
+ */
227
+ get debug() {
228
+ return this.#debug;
229
+ }
230
+ /**
231
+ * Creates a performance marker for a profiler state transition.
232
+ * @param transition - The state transition that occurred
233
+ */
234
+ #transitionMarker(transition) {
235
+ const transitionMarkerPayload = {
236
+ dataType: 'marker',
237
+ color: 'primary',
238
+ tooltipText: `Profiler state transition: ${transition}`,
239
+ properties: [['Transition', transition], ...objectToEntries(this.stats)],
240
+ };
241
+ this.marker(transition, transitionMarkerPayload);
242
+ }
243
+ #transition(next) {
244
+ if (this.#state === next) {
245
+ return;
246
+ }
247
+ if (this.#state === 'closed') {
248
+ throw new Error('Profiler already closed');
249
+ }
250
+ const transition = `${this.#state}->${next}`;
251
+ switch (transition) {
252
+ case 'idle->running':
253
+ super.setEnabled(true);
254
+ this.#sink.open?.();
255
+ this.#performanceObserverSink.subscribe();
256
+ break;
257
+ case 'running->idle':
258
+ case 'running->closed':
259
+ super.setEnabled(false);
260
+ this.#performanceObserverSink.unsubscribe();
261
+ this.#sink.close?.();
262
+ break;
263
+ case 'idle->closed':
264
+ // No-op, was not open
265
+ break;
266
+ default:
267
+ throw new Error(`Invalid transition: ${this.#state} -> ${next}`);
268
+ }
269
+ this.#state = next;
270
+ if (this.#debug) {
271
+ this.#transitionMarker(transition);
272
+ }
273
+ }
274
+ /**
275
+ * Closes profiler and releases resources. Idempotent, safe for exit handlers.
276
+ * **Exit Handler Usage**: Call only this method from process exit handlers.
277
+ */
278
+ close() {
279
+ this.#transition('closed');
280
+ }
281
+ /** @returns Current profiler state */
282
+ get state() {
283
+ return this.#state;
284
+ }
285
+ /** @returns Whether profiler is in 'running' state */
286
+ isEnabled() {
287
+ return this.#state === 'running';
288
+ }
289
+ /** Enables profiling (start/stop) */
290
+ setEnabled(enabled) {
291
+ if (enabled) {
292
+ this.#transition('running');
293
+ }
294
+ else {
295
+ this.#transition('idle');
296
+ }
297
+ }
298
+ /** @returns Queue statistics and profiling state for monitoring */
299
+ get stats() {
300
+ return {
301
+ ...this.#performanceObserverSink.getStats(),
302
+ debug: this.#debug,
303
+ state: this.#state,
304
+ walOpen: !this.#sink.isClosed(),
305
+ };
306
+ }
307
+ /** Flushes buffered performance data to sink. */
308
+ flush() {
309
+ if (this.#state === 'closed') {
310
+ return; // No-op if closed
311
+ }
312
+ this.#performanceObserverSink.flush();
313
+ }
314
+ }
163
315
  //# sourceMappingURL=profiler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"profiler.js","sourceRoot":"","sources":["../../../../src/lib/profiler/profiler.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAIL,SAAS,EACT,aAAa,EACb,UAAU,EACV,WAAW,GACZ,MAAM,2CAA2C,CAAC;AAMnD,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAqC1D;;;;;;GAMG;AACH,MAAM,OAAO,QAAQ;IACnB,QAAQ,CAAU;IACT,SAAS,CAA0B;IACnC,MAAM,CAAuD;IAC7D,MAAM,CAAgC;IAE/C;;;;;;;;;;;OAWG;IACH,YAAY,OAA2B;QACrC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,QAAQ,EAAE,GAAG,OAAO,CAAC;QACzD,MAAM,QAAQ,GAAG,aAAa,CAAC;QAE/B,IAAI,CAAC,QAAQ,GAAG,OAAO,IAAI,eAAe,CAAC,wBAAwB,CAAC,CAAC;QACrE,IAAI,CAAC,SAAS,GAAG,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,CAAC;QAC3C,IAAI,CAAC,MAAM,GAAG,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ark, PerformanceMeasure } from 'node:perf_hooks';
2
- import type { BeginEvent, CompleteEvent, EndEvent, InstantEvent, InstantEventArgs, InstantEventTracingStartedInBrowser, SpanEventArgs, TraceEvent, TraceEventContainer } from './trace-file.type.js';
1
+ import type { PerformanceEntry, PerformanceMark, PerformanceMeasure } from 'node:perf_hooks';
2
+ import type { UserTimingDetail } from '../user-timing-extensibility-api.type.js';
3
+ import type { BeginEvent, CompleteEvent, EndEvent, InstantEvent, InstantEventArgs, InstantEventTracingStartedInBrowser, SpanEventArgs, TraceEvent, TraceEventContainer, TraceEventRaw, TraceMetadata, UserTimingTraceEvent } from './trace-file.type.js';
3
4
  /**
4
5
  * Generates a unique ID for linking begin and end span events in Chrome traces.
5
6
  * @returns Object with local ID string for the id2 field
@@ -121,6 +122,26 @@ export declare const measureToSpanEvents: (entry: PerformanceMeasure, opt?: {
121
122
  pid?: number;
122
123
  tid?: number;
123
124
  }) => [BeginEvent, EndEvent];
125
+ /**
126
+ * Converts a PerformanceEntry to an array of UserTimingTraceEvents.
127
+ * A mark is converted to an instant event, and a measure is converted to a pair of span events.
128
+ * Other entry types are ignored.
129
+ * @param entry - Performance entry
130
+ * @returns UserTimingTraceEvent[]
131
+ */
132
+ export declare function entryToTraceEvents(entry: PerformanceEntry): UserTimingTraceEvent[];
133
+ /**
134
+ * Creates trace metadata object with standard DevTools fields and custom metadata.
135
+ * @param startDate - Optional start date for the trace, defaults to current date
136
+ * @param metadata - Optional additional metadata to merge into the trace metadata
137
+ * @returns TraceMetadata object with source, startTime, and merged custom metadata
138
+ */
139
+ export declare function getTraceMetadata(startDate?: Date, metadata?: Record<string, unknown>): {
140
+ source: string;
141
+ startTime: string;
142
+ hardwareConcurrency: number;
143
+ dataOrigin: string;
144
+ };
124
145
  /**
125
146
  * Creates a complete trace file container with metadata.
126
147
  * @param opt - Trace file configuration
@@ -129,5 +150,34 @@ export declare const measureToSpanEvents: (entry: PerformanceMeasure, opt?: {
129
150
  export declare const getTraceFile: (opt: {
130
151
  traceEvents: TraceEvent[];
131
152
  startTime?: string;
153
+ metadata?: Partial<TraceMetadata>;
132
154
  }) => TraceEventContainer;
155
+ /**
156
+ * Decodes a JSON string detail property back to its original object form.
157
+ * @param target - Object containing a detail property as a JSON string
158
+ * @returns UserTimingDetail with the detail property parsed from JSON
159
+ */
160
+ export declare function decodeDetail(target: {
161
+ detail: string;
162
+ }): UserTimingDetail;
163
+ /**
164
+ * Encodes object detail properties to JSON strings for storage/transmission.
165
+ * @param target - UserTimingDetail object with detail property to encode
166
+ * @returns UserTimingDetail with object details converted to JSON strings
167
+ */
168
+ export declare function encodeDetail(target: UserTimingDetail): UserTimingDetail;
169
+ /**
170
+ * Decodes a raw trace event with JSON string details back to typed UserTimingTraceEvent.
171
+ * Parses detail properties from JSON strings to objects.
172
+ * @param event - Raw trace event with string-encoded details
173
+ * @returns UserTimingTraceEvent with parsed detail objects
174
+ */
175
+ export declare function decodeTraceEvent({ args, ...rest }: TraceEventRaw): UserTimingTraceEvent;
176
+ /**
177
+ * Encodes a UserTimingTraceEvent to raw format with JSON string details.
178
+ * Converts object details to JSON strings for storage/transmission.
179
+ * @param event - UserTimingTraceEvent with object details
180
+ * @returns TraceEventRaw with string-encoded details
181
+ */
182
+ export declare function encodeTraceEvent({ args, ...rest }: UserTimingTraceEvent): TraceEventRaw;
133
183
  export {};
@@ -1,6 +1,5 @@
1
- import os from 'node:os';
2
1
  import { threadId } from 'node:worker_threads';
3
- import { defaultClock } from './clock-epoch.js';
2
+ import { defaultClock } from '../clock-epoch.js';
4
3
  /** Global counter for generating unique span IDs within a trace */
5
4
  // eslint-disable-next-line functional/no-let
6
5
  let id2Count = 0;
@@ -11,8 +10,11 @@ let id2Count = 0;
11
10
  export const nextId2 = () => ({ local: `0x${++id2Count}` });
12
11
  /**
13
12
  * Provides default values for trace event properties.
14
- * @param opt - Optional overrides for pid, tid, and timestamp
15
- * @returns Object with pid, tid, and timestamp
13
+ * @param opt - Optional overrides for process ID, thread ID, and timestamp
14
+ * @param opt.pid - Process ID override, defaults to current process PID
15
+ * @param opt.tid - Thread ID override, defaults to current thread ID
16
+ * @param opt.ts - Timestamp override in microseconds, defaults to current epoch time
17
+ * @returns Object containing pid, tid, and ts with defaults applied
16
18
  */
17
19
  const defaults = (opt) => ({
18
20
  pid: opt?.pid ?? process.pid,
@@ -162,6 +164,37 @@ export const measureToSpanEvents = (entry, opt) => getSpan({
162
164
  tsE: defaultClock.fromEntry(entry, true),
163
165
  args: entry.detail ? { data: { detail: entry.detail } } : undefined,
164
166
  });
167
+ /**
168
+ * Converts a PerformanceEntry to an array of UserTimingTraceEvents.
169
+ * A mark is converted to an instant event, and a measure is converted to a pair of span events.
170
+ * Other entry types are ignored.
171
+ * @param entry - Performance entry
172
+ * @returns UserTimingTraceEvent[]
173
+ */
174
+ export function entryToTraceEvents(entry) {
175
+ if (entry.entryType === 'mark') {
176
+ return [markToInstantEvent(entry)];
177
+ }
178
+ if (entry.entryType === 'measure') {
179
+ return measureToSpanEvents(entry);
180
+ }
181
+ return [];
182
+ }
183
+ /**
184
+ * Creates trace metadata object with standard DevTools fields and custom metadata.
185
+ * @param startDate - Optional start date for the trace, defaults to current date
186
+ * @param metadata - Optional additional metadata to merge into the trace metadata
187
+ * @returns TraceMetadata object with source, startTime, and merged custom metadata
188
+ */
189
+ export function getTraceMetadata(startDate, metadata) {
190
+ return {
191
+ source: 'DevTools',
192
+ startTime: startDate?.toISOString() ?? new Date().toISOString(),
193
+ hardwareConcurrency: 1,
194
+ dataOrigin: 'TraceEvents',
195
+ ...metadata,
196
+ };
197
+ }
165
198
  /**
166
199
  * Creates a complete trace file container with metadata.
167
200
  * @param opt - Trace file configuration
@@ -170,10 +203,88 @@ export const measureToSpanEvents = (entry, opt) => getSpan({
170
203
  export const getTraceFile = (opt) => ({
171
204
  traceEvents: opt.traceEvents,
172
205
  displayTimeUnit: 'ms',
173
- metadata: {
174
- source: 'Node.js UserTiming',
175
- startTime: opt.startTime ?? new Date().toISOString(),
176
- hardwareConcurrency: os.cpus().length,
177
- },
206
+ metadata: getTraceMetadata(opt.startTime ? new Date(opt.startTime) : new Date(), opt.metadata),
178
207
  });
208
+ /**
209
+ * Processes the detail property of an object using a custom processor function.
210
+ * @template T - Object type that may contain a detail property
211
+ * @param target - Object containing the detail property to process
212
+ * @param processor - Function to transform the detail value
213
+ * @returns New object with processed detail property, or original object if no detail
214
+ */
215
+ function processDetail(target, processor) {
216
+ if (target.detail != null &&
217
+ (typeof target.detail === 'string' || typeof target.detail === 'object')) {
218
+ return { ...target, detail: processor(target.detail) };
219
+ }
220
+ return target;
221
+ }
222
+ /**
223
+ * Decodes a JSON string detail property back to its original object form.
224
+ * @param target - Object containing a detail property as a JSON string
225
+ * @returns UserTimingDetail with the detail property parsed from JSON
226
+ */
227
+ export function decodeDetail(target) {
228
+ return processDetail(target, detail => typeof detail === 'string'
229
+ ? JSON.parse(detail)
230
+ : detail);
231
+ }
232
+ /**
233
+ * Encodes object detail properties to JSON strings for storage/transmission.
234
+ * @param target - UserTimingDetail object with detail property to encode
235
+ * @returns UserTimingDetail with object details converted to JSON strings
236
+ */
237
+ export function encodeDetail(target) {
238
+ return processDetail(target, (detail) => typeof detail === 'object'
239
+ ? JSON.stringify(detail)
240
+ : detail);
241
+ }
242
+ /**
243
+ * Decodes a raw trace event with JSON string details back to typed UserTimingTraceEvent.
244
+ * Parses detail properties from JSON strings to objects.
245
+ * @param event - Raw trace event with string-encoded details
246
+ * @returns UserTimingTraceEvent with parsed detail objects
247
+ */
248
+ export function decodeTraceEvent({ args, ...rest }) {
249
+ if (!args) {
250
+ return rest;
251
+ }
252
+ const processedArgs = decodeDetail(args);
253
+ if ('data' in args && args.data && typeof args.data === 'object') {
254
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
255
+ return {
256
+ ...rest,
257
+ args: {
258
+ ...processedArgs,
259
+ data: decodeDetail(args.data),
260
+ },
261
+ };
262
+ }
263
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
264
+ return { ...rest, args: processedArgs };
265
+ }
266
+ /**
267
+ * Encodes a UserTimingTraceEvent to raw format with JSON string details.
268
+ * Converts object details to JSON strings for storage/transmission.
269
+ * @param event - UserTimingTraceEvent with object details
270
+ * @returns TraceEventRaw with string-encoded details
271
+ */
272
+ export function encodeTraceEvent({ args, ...rest }) {
273
+ if (!args) {
274
+ return rest;
275
+ }
276
+ const processedArgs = encodeDetail(args);
277
+ if ('data' in args && args.data && typeof args.data === 'object') {
278
+ const result = {
279
+ ...rest,
280
+ args: {
281
+ ...processedArgs,
282
+ data: encodeDetail(args.data),
283
+ },
284
+ };
285
+ return result;
286
+ }
287
+ const result = { ...rest, args: processedArgs };
288
+ return result;
289
+ }
179
290
  //# sourceMappingURL=trace-file-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace-file-utils.js","sourceRoot":"","sources":["../../../../src/lib/profiler/trace-file-utils.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAkBjD,mEAAmE;AACnE,6CAA6C;AAC7C,IAAI,QAAQ,GAAG,CAAC,CAAC;AAEjB;;;GAGG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;AAE5D;;;;;;;GAOG;AACH,MAAM,QAAQ,GAAG,CAAC,GAAiD,EAAE,EAAE,CAAC,CAAC;IACvE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,OAAO,CAAC,GAAG;IAC5B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,QAAQ;IACzB,EAAE,EAAE,GAAG,EAAE,EAAE,IAAI,YAAY,CAAC,UAAU,EAAE;CACzC,CAAC,CAAC;AAEH;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAW,EA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G,aAAa;gBAChB,IAAI,EAAE,YAAY,CAAC,IAAI,CAAC,IAAwB,CAAC;aAClD;SACF,CAAC;QACF,OAAO,MAAM,CAAC;IAChB,CAAC;IACD,MAAM,MAAM,GAAkB,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC;IAC/D,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -1,4 +1,4 @@
1
- import type { UserTimingDetail } from './user-timing-extensibility-api.type.js';
1
+ import type { UserTimingDetail } from '../user-timing-extensibility-api.type.js';
2
2
  /**
3
3
  * Arguments for instant trace events.
4
4
  * @property {UserTimingDetail} [detail] - Optional user timing detail with DevTools payload
@@ -139,7 +139,11 @@ export type SpanEvent = BeginEvent | EndEvent;
139
139
  /**
140
140
  * Union type of all trace event types.
141
141
  */
142
- export type TraceEvent = InstantEvent | CompleteEvent | SpanEvent | InstantEventTracingStartedInBrowser;
142
+ export type UserTimingTraceEvent = InstantEvent | SpanEvent;
143
+ /**
144
+ * All trace events including system events added during finalization.
145
+ */
146
+ export type TraceEvent = UserTimingTraceEvent | CompleteEvent | InstantEventTracingStartedInBrowser;
143
147
  /**
144
148
  * Raw arguments format for trace events before processing.
145
149
  * Either contains a detail string directly or nested in a data object.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trace-file.type.js","sourceRoot":"","sources":["../../../../src/lib/profiler/trace-file.type.ts"],"names":[],"mappings":""}
@@ -0,0 +1,25 @@
1
+ import type { InvalidEntry } from '../wal.js';
2
+ import type { UserTimingTraceEvent } from './trace-file.type.js';
3
+ /**
4
+ * Generates a complete Chrome DevTools trace file content as JSON string.
5
+ * Adds margin events around the trace events and includes metadata.
6
+ * @param events - Array of user timing trace events to include
7
+ * @param metadata - Optional custom metadata to include in the trace file
8
+ * @returns JSON string representation of the complete trace file
9
+ */
10
+ export declare function generateTraceContent(events: UserTimingTraceEvent[], metadata?: Record<string, unknown>): string;
11
+ /**
12
+ * Creates a WAL (Write-Ahead Logging) format configuration for Chrome DevTools trace files.
13
+ * Automatically finalizes shards into complete trace files with proper metadata and margin events.
14
+ * @returns WalFormat configuration object with baseName, codec, extensions, and finalizer
15
+ */
16
+ export declare function traceEventWalFormat(): {
17
+ baseName: string;
18
+ walExtension: string;
19
+ finalExtension: string;
20
+ codec: {
21
+ encode: (event: UserTimingTraceEvent) => string;
22
+ decode: (json: string) => UserTimingTraceEvent;
23
+ };
24
+ finalizer: (records: (UserTimingTraceEvent | InvalidEntry<string>)[], metadata?: Record<string, unknown>) => string;
25
+ };