Open History to see the last commit
1import { DifferenceStreamWriter, UnaryOperator } from '../graph.js'
2import { StreamBuilder } from '../d2.js'
3import type { IStreamBuilder, PipedOperator } from '../types.js'
4import type { DifferenceStreamReader } from '../graph.js'
5
6/**
7 * Operator that logs debug information about the stream
8 */
9export class DebugOperator<T> extends UnaryOperator<T> {
10 #name: string
11 #indent: boolean
12
13 constructor(
14 id: number,
15 inputA: DifferenceStreamReader<T>,
16 output: DifferenceStreamWriter<T>,
17 name: string,
18 indent: boolean = false,
19 ) {
20 super(id, inputA, output)
21 this.#name = name
22 this.#indent = indent
23 }
24
25 run(): void {
26 for (const message of this.inputMessages()) {
27 console.log(`debug ${this.#name} data: ${message.toString(this.#indent)}`)
28 this.output.sendData(message)
29 }
30 }
31}
32
33/**
34 * Logs debug information about the stream using console.log
35 * @param name - The name to prefix debug messages with
36 * @param indent - Whether to indent the debug output
37 */
38export function debug<T>(
39 name: string,
40 indent: boolean = false,
41): PipedOperator<T, T> {
42 return (stream: IStreamBuilder<T>): IStreamBuilder<T> => {
43 const output = new StreamBuilder<T>(
44 stream.graph,
45 new DifferenceStreamWriter<T>(),
46 )
47 const operator = new DebugOperator<T>(
48 stream.graph.getNextOperatorId(),
49 stream.connectReader(),
50 output.writer,
51 name,
52 indent,
53 )
54 stream.graph.addOperator(operator)
55 return output
56 }
57}