// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import { StringBuilder, Text } from '@rushstack/node-core-library'; import { type ITerminalProvider, TerminalProviderSeverity } from './ITerminalProvider'; import { AnsiEscape } from './AnsiEscape'; /** * @beta */ export interface IStringBufferOutputOptions { /** * If set to true, special characters like \\n, \\r, and the \\u001b character * in color control tokens will get normalized to [-n-], [-r-], and [-x-] respectively * * This option defaults to `true` */ normalizeSpecialCharacters?: boolean; } /** * @beta */ export interface IStringBufferOutputChunksOptions extends IStringBufferOutputOptions { /** * If true, the output will be returned as an array of lines prefixed with severity tokens. */ asLines?: boolean; } /** * @beta */ export interface IAllStringBufferOutput { log: string; warning: string; error: string; verbose: string; debug: string; } /** * @beta */ export type TerminalProviderSeverityName = keyof typeof TerminalProviderSeverity; /** * @beta */ export interface IOutputChunk { text: string; severity: TerminalProviderSeverityName; } function _normalizeOptions( options: TOptions ): TOptions & Required { return { normalizeSpecialCharacters: true, ...options }; } function _normalizeOutput(s: string, options: IStringBufferOutputOptions | undefined): string { const { normalizeSpecialCharacters } = _normalizeOptions(options ?? {}); return _normalizeOutputInner(s, normalizeSpecialCharacters); } function _normalizeOutputInner(s: string, normalizeSpecialCharacters: boolean): string { s = Text.convertToLf(s); if (normalizeSpecialCharacters) { return AnsiEscape.formatForTests(s, { encodeNewlines: true }); } else { return s; } } const LONGEST_SEVERITY_NAME_LENGTH: number = Object.keys(TerminalProviderSeverity).reduce( (max: number, k: string) => Math.max(max, k.length), 0 ); /** * Terminal provider that stores written data in buffers separated by severity. * This terminal provider is designed to be used when code that prints to a terminal * is being unit tested. * * @beta */ export class StringBufferTerminalProvider implements ITerminalProvider { #standardBuffer: StringBuilder = new StringBuilder(); #verboseBuffer: StringBuilder = new StringBuilder(); #debugBuffer: StringBuilder = new StringBuilder(); #warningBuffer: StringBuilder = new StringBuilder(); #errorBuffer: StringBuilder = new StringBuilder(); #allOutputChunks: IOutputChunk[] = []; /** * {@inheritDoc ITerminalProvider.supportsColor} */ public readonly supportsColor: boolean; public constructor(supportsColor: boolean = false) { this.supportsColor = supportsColor; } /** * {@inheritDoc ITerminalProvider.write} */ public write(text: string, severity: TerminalProviderSeverity): void { const severityName: TerminalProviderSeverityName = TerminalProviderSeverity[ severity ] as TerminalProviderSeverityName; const lastChunk: IOutputChunk | undefined = this.#allOutputChunks[this.#allOutputChunks.length - 1]; if (lastChunk && lastChunk.severity === severityName) { lastChunk.text += text; } else { this.#allOutputChunks.push({ text, severity: severityName }); } switch (severity) { case TerminalProviderSeverity.warning: { this.#warningBuffer.append(text); break; } case TerminalProviderSeverity.error: { this.#errorBuffer.append(text); break; } case TerminalProviderSeverity.verbose: { this.#verboseBuffer.append(text); break; } case TerminalProviderSeverity.debug: { this.#debugBuffer.append(text); break; } case TerminalProviderSeverity.log: default: { this.#standardBuffer.append(text); break; } } } /** * {@inheritDoc ITerminalProvider.eolCharacter} */ public get eolCharacter(): string { return '\n'; } /** * Get everything that has been written at log-level severity. */ public getOutput(options?: IStringBufferOutputOptions): string { return _normalizeOutput(this.#standardBuffer.toString(), options); } /** * @deprecated - use {@link StringBufferTerminalProvider.getVerboseOutput} */ public getVerbose(options?: IStringBufferOutputOptions): string { return this.getVerboseOutput(options); } /** * Get everything that has been written at verbose-level severity. */ public getVerboseOutput(options?: IStringBufferOutputOptions): string { return _normalizeOutput(this.#verboseBuffer.toString(), options); } /** * Get everything that has been written at debug-level severity. */ public getDebugOutput(options?: IStringBufferOutputOptions): string { return _normalizeOutput(this.#debugBuffer.toString(), options); } /** * Get everything that has been written at error-level severity. */ public getErrorOutput(options?: IStringBufferOutputOptions): string { return _normalizeOutput(this.#errorBuffer.toString(), options); } /** * Get everything that has been written at warning-level severity. */ public getWarningOutput(options?: IStringBufferOutputOptions): string { return _normalizeOutput(this.#warningBuffer.toString(), options); } /** * Get everything that has been written at all severity levels. */ public getAllOutput(sparse?: false, options?: IStringBufferOutputOptions): IAllStringBufferOutput; public getAllOutput(sparse: true, options?: IStringBufferOutputOptions): Partial; public getAllOutput( sparse: boolean | undefined, options?: IStringBufferOutputOptions ): Partial { const result: Partial = {}; const log: string = this.getOutput(options); if (!sparse || log) { result.log = log; } const warning: string = this.getWarningOutput(options); if (!sparse || warning) { result.warning = warning; } const error: string = this.getErrorOutput(options); if (!sparse || error) { result.error = error; } const verbose: string = this.getVerboseOutput(options); if (!sparse || verbose) { result.verbose = verbose; } const debug: string = this.getDebugOutput(options); if (!sparse || debug) { result.debug = debug; } return result; } /** * Get everything that has been written as an array of output chunks, preserving order. */ public getAllOutputAsChunks( options?: IStringBufferOutputChunksOptions & { asLines?: false } ): IOutputChunk[]; public getAllOutputAsChunks( options: IStringBufferOutputChunksOptions & { asLines: true } ): `[${string}] ${string}`[]; public getAllOutputAsChunks(options: IStringBufferOutputChunksOptions = {}): IOutputChunk[] | string[] { const { asLines, normalizeSpecialCharacters } = _normalizeOptions(options); if (asLines) { const lines: `[${string}] ${string}`[] = []; for (const { text: rawText, severity: rawSeverity } of this.#allOutputChunks) { const severity: string = (rawSeverity as TerminalProviderSeverityName).padStart( LONGEST_SEVERITY_NAME_LENGTH, ' ' ); const lfText: string = Text.convertToLf(rawText); const rawLines: string[] = lfText.split('\n'); // Emit one entry per logical line. for (let i: number = 0; i < rawLines.length; i++) { const isLast: boolean = i === rawLines.length - 1; const isFinalTrailingEmpty: boolean = isLast && rawLines[i] === ''; if (isFinalTrailingEmpty) { continue; } const hasNewlineAfter: boolean = i < rawLines.length - 1; // If the original output had a newline after this line, preserve it as the special token // (e.g. "[n]") when normalization is enabled. const shouldIncludeNewlineToken: boolean = normalizeSpecialCharacters && hasNewlineAfter; const lineText: string = shouldIncludeNewlineToken ? `${rawLines[i]}\n` : rawLines[i]; const text: string = _normalizeOutputInner(lineText, normalizeSpecialCharacters); lines.push(`[${severity}] ${text}`); } } return lines; } else { return this.#allOutputChunks.map(({ text: rawText, severity }) => { const text: string = _normalizeOutputInner(rawText, normalizeSpecialCharacters); return { text, severity }; }); } } }