@orkestrel/console 0.0.12 → 0.0.14
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.
- package/README.md +8 -8
- package/dist/src/browser/index.d.ts +47 -38
- package/dist/src/browser/index.js +27 -18
- package/dist/src/browser/index.js.map +1 -1
- package/dist/src/core/index.cjs +121 -82
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +263 -174
- package/dist/src/core/index.d.ts +263 -174
- package/dist/src/core/index.js +121 -82
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +64 -45
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +115 -80
- package/dist/src/server/index.d.ts +115 -80
- package/dist/src/server/index.js +64 -45
- package/dist/src/server/index.js.map +1 -1
- package/package.json +15 -16
|
@@ -1,34 +1,40 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _orkestrel_contract = require("@orkestrel/contract");
|
|
2
3
|
let node_string_decoder = require("node:string_decoder");
|
|
3
4
|
let _orkestrel_emitter = require("@orkestrel/emitter");
|
|
4
5
|
let _src_core = require("../core/index.cjs");
|
|
5
6
|
//#region src/server/constants.ts
|
|
6
7
|
/**
|
|
7
|
-
* Lists the
|
|
8
|
-
* `stdout`-then-`stderr` order — the {@link StreamLevel} universe and the default configured
|
|
8
|
+
* Lists the process streams a {@link import('./types.js').ProcessCaptureInterface} can intercept,
|
|
9
|
+
* in `stdout`-then-`stderr` order — the {@link StreamLevel} universe and the default configured
|
|
10
|
+
* set.
|
|
9
11
|
*/
|
|
10
12
|
var STREAM_LEVELS = Object.freeze(["stdout", "stderr"]);
|
|
11
13
|
/**
|
|
12
|
-
* Sets the default bounded-buffer cap for a {@link import('./types.js').ProcessCaptureInterface} —
|
|
13
|
-
* most
|
|
14
|
-
* total buffer and each per-stream bucket; oldest dropped first)
|
|
15
|
-
*
|
|
14
|
+
* Sets the default bounded-buffer cap for a {@link import('./types.js').ProcessCaptureInterface} —
|
|
15
|
+
* `1000`, so at most that many recent {@link import('./types.js').CapturedChunk}s are retained per
|
|
16
|
+
* buffer (the total buffer and each per-stream bucket; oldest dropped first) and retention is
|
|
17
|
+
* always bounded.
|
|
18
|
+
*
|
|
19
|
+
* @remarks
|
|
20
|
+
* It mirrors the core `Capture`'s `DEFAULT_CAPTURE_LIMIT`; a consumer overrides the cap through
|
|
21
|
+
* `options.limit`.
|
|
16
22
|
*/
|
|
17
23
|
var DEFAULT_STREAM_LIMIT = 1e3;
|
|
18
24
|
/**
|
|
19
25
|
* Sets the terminal width {@link import('./factories.js').createServerSink} reports through
|
|
20
|
-
* {@link import('./types.js').ServerSinkInterface.columns} when the `stdout` stream is not a TTY
|
|
21
|
-
* `.columns` is `undefined`) and no explicit `options.columns` was supplied — the conventional
|
|
26
|
+
* {@link import('./types.js').ServerSinkInterface.columns} when the `stdout` stream is not a TTY
|
|
27
|
+
* (so `.columns` is `undefined`) and no explicit `options.columns` was supplied — the conventional
|
|
22
28
|
* 80-column default a non-interactive context (a pipe, a CI log) assumes.
|
|
23
29
|
*/
|
|
24
30
|
var DEFAULT_COLUMNS = 80;
|
|
25
31
|
/**
|
|
26
|
-
* Maps each {@link StreamLevel} to its {@link LogLevel} for the optional sink forward — the
|
|
27
|
-
* process capture routes through when writing an intercepted chunk to a
|
|
28
|
-
* {@link import('@src/core').SinkInterface}
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
+
* Maps each {@link StreamLevel} to its {@link LogLevel} for the optional sink forward — the
|
|
33
|
+
* projection a process capture routes through when writing an intercepted chunk to a
|
|
34
|
+
* {@link import('@src/core').SinkInterface}. `sink.write(text, STREAM_LEVEL_MAP[level])` is the
|
|
35
|
+
* call this map backs. `stderr` is conventionally the error/diagnostic stream → `error`; `stdout`
|
|
36
|
+
* is the normal output stream → `info`. The source of truth for the stream-to-log projection (the
|
|
37
|
+
* server analogue of the core `CAPTURE_LEVEL_MAP`).
|
|
32
38
|
*/
|
|
33
39
|
var STREAM_LEVEL_MAP = Object.freeze({
|
|
34
40
|
stdout: "info",
|
|
@@ -58,25 +64,26 @@ var STREAM_LEVEL_MAP = Object.freeze({
|
|
|
58
64
|
* ```
|
|
59
65
|
*/
|
|
60
66
|
function isStreamTarget(value) {
|
|
61
|
-
return
|
|
67
|
+
return (0, _orkestrel_contract.isObject)(value) && "write" in value && (0, _orkestrel_contract.isFunction)(value.write);
|
|
62
68
|
}
|
|
63
69
|
/**
|
|
64
|
-
* Checks whether `encoding` is a {@link BufferEncoding} accepted by `Buffer.prototype.toString` — a
|
|
65
|
-
* guard used by {@link import('./helpers.js').decodeChunk} to honor a process-write
|
|
66
|
-
* argument only when it is a real Node encoding (otherwise utf-8 is assumed).
|
|
70
|
+
* Checks whether `encoding` is a {@link BufferEncoding} accepted by `Buffer.prototype.toString` — a
|
|
71
|
+
* total guard used by {@link import('./helpers.js').decodeChunk} to honor a process-write
|
|
72
|
+
* `encoding` argument only when it is a real Node encoding (otherwise utf-8 is assumed).
|
|
67
73
|
*
|
|
68
74
|
* @param encoding - The candidate encoding (the second `write` argument, possibly a callback)
|
|
69
75
|
* @returns True if `encoding` names a supported buffer encoding; false otherwise
|
|
70
76
|
*/
|
|
71
77
|
function isBufferEncoding(encoding) {
|
|
72
|
-
return
|
|
78
|
+
return (0, _orkestrel_contract.isString)(encoding) && Buffer.isEncoding(encoding);
|
|
73
79
|
}
|
|
74
80
|
//#endregion
|
|
75
81
|
//#region src/server/helpers.ts
|
|
76
82
|
/**
|
|
77
|
-
* Infers the width in character cells of a stream target — its live `columns` when it is a TTY,
|
|
78
|
-
* the non-interactive {@link DEFAULT_COLUMNS} fallback. The basis a
|
|
79
|
-
* reports through `columns` so a `Reporter` /
|
|
83
|
+
* Infers the width in character cells of a stream target — its live `columns` when it is a TTY,
|
|
84
|
+
* else the non-interactive {@link DEFAULT_COLUMNS} fallback. The basis a
|
|
85
|
+
* {@link import('./types.js').ServerSinkInterface} reports through `columns` so a `Reporter` /
|
|
86
|
+
* `Progress` can size its layout to the terminal.
|
|
80
87
|
*
|
|
81
88
|
* @remarks
|
|
82
89
|
* Reads `target.columns` on each call (so a getter-backed real stream reflects a live resize) and
|
|
@@ -88,18 +95,18 @@ function isBufferEncoding(encoding) {
|
|
|
88
95
|
*/
|
|
89
96
|
function inferColumns(target) {
|
|
90
97
|
const columns = target.columns;
|
|
91
|
-
if (
|
|
98
|
+
if ((0, _orkestrel_contract.isFiniteNumber)(columns) && columns > 0) return columns;
|
|
92
99
|
return 80;
|
|
93
100
|
}
|
|
94
101
|
/**
|
|
95
|
-
* Infers whether one stream target receives styled output
|
|
96
|
-
*
|
|
97
|
-
* reads process globals itself.
|
|
102
|
+
* Infers whether one stream target receives styled output — a present `FORCE_COLOR` first, then a
|
|
103
|
+
* non-empty `NO_COLOR`, then `target.isTTY === true`.
|
|
98
104
|
*
|
|
99
105
|
* @remarks
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
106
|
+
* The result is a construction-time target fact for
|
|
107
|
+
* {@link import('./factories.js').createServerSink}; this helper is pure and
|
|
108
|
+
* never reads process globals itself. Under `FORCE_COLOR` only the exact value `'0'` disables
|
|
109
|
+
* styling.
|
|
103
110
|
*
|
|
104
111
|
* @param target - The stream target whose terminal capability is the fallback
|
|
105
112
|
* @param environment - The environment record supplying `FORCE_COLOR` and `NO_COLOR`
|
|
@@ -148,10 +155,10 @@ function inferStyled(target, environment) {
|
|
|
148
155
|
* ```
|
|
149
156
|
*/
|
|
150
157
|
function decodeChunk(chunk, encoding) {
|
|
151
|
-
if (
|
|
158
|
+
if ((0, _orkestrel_contract.isString)(chunk)) return chunk;
|
|
152
159
|
try {
|
|
153
160
|
if (Buffer.isBuffer(chunk)) return chunk.toString(isBufferEncoding(encoding) ? encoding : "utf8");
|
|
154
|
-
if (
|
|
161
|
+
if ((0, _orkestrel_contract.isUint8Array)(chunk)) return new TextDecoder().decode(chunk);
|
|
155
162
|
return String(chunk);
|
|
156
163
|
} catch {
|
|
157
164
|
return "[unprintable]";
|
|
@@ -282,7 +289,7 @@ var ProcessCapture = class {
|
|
|
282
289
|
return mirror(chunk, encoding, callback);
|
|
283
290
|
}
|
|
284
291
|
#decode(level, chunk, encoding) {
|
|
285
|
-
if (
|
|
292
|
+
if ((0, _orkestrel_contract.isString)(chunk)) return chunk;
|
|
286
293
|
const decoder = this.#decoders.get(level);
|
|
287
294
|
if (decoder !== void 0 && this.#streams(encoding)) return decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
288
295
|
return decodeChunk(chunk, encoding);
|
|
@@ -315,11 +322,10 @@ var ProcessCapture = class {
|
|
|
315
322
|
//#endregion
|
|
316
323
|
//#region src/server/factories.ts
|
|
317
324
|
/**
|
|
318
|
-
* Creates the server TTY {@link ServerSinkInterface} — the server output backend,
|
|
319
|
-
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
* {@link import('@src/core').strip}s ANSI to clean text for a plain target.
|
|
325
|
+
* Creates the server TTY {@link ServerSinkInterface} — the server output backend, whose
|
|
326
|
+
* `write(text, level?)` routes by level to the process streams and uses construction-time styled
|
|
327
|
+
* facts: it sends ANSI straight to a styled target (with a leading `\r` overwriting a terminal
|
|
328
|
+
* line natively) but {@link import('@src/core').strip}s ANSI to clean text for a plain target.
|
|
323
329
|
*
|
|
324
330
|
* @param options - See {@link ServerSinkOptions}
|
|
325
331
|
* @returns A {@link ServerSinkInterface} — a {@link import('@src/core').SinkInterface} that also
|
|
@@ -345,16 +351,29 @@ var ProcessCapture = class {
|
|
|
345
351
|
* the sink (and the isTTY-strip path) with a fake stream that never touches the real process
|
|
346
352
|
* streams.
|
|
347
353
|
*
|
|
348
|
-
* @example
|
|
354
|
+
* @example The server — a TTY sink and a process capture
|
|
349
355
|
* ```ts
|
|
350
356
|
* import { createStyler, Logger, Reporter } from '@orkestrel/console'
|
|
351
|
-
* import { createServerSink } from '@orkestrel/console/server'
|
|
357
|
+
* import { createServerSink, ProcessCapture } from '@orkestrel/console/server'
|
|
358
|
+
*
|
|
359
|
+
* const sink = createServerSink() // FORCE_COLOR, then NO_COLOR, then isTTY — per target, at construction
|
|
360
|
+
* const styler = createStyler({ enabled: sink.styled }) // keep generated ANSI paired with the sink's stdout stripping
|
|
361
|
+
* const logger = new Logger({ name: 'server', sink, styler })
|
|
362
|
+
* logger.error('boom') // → process.stderr (the error stream)
|
|
363
|
+
* const reporter = new Reporter({ sink, width: sink.columns }) // size the layout to the live terminal
|
|
352
364
|
*
|
|
353
|
-
*
|
|
354
|
-
* const
|
|
355
|
-
*
|
|
356
|
-
*
|
|
357
|
-
*
|
|
365
|
+
* // `styled` overrides the inference outright — for a CI log that renders ANSI off a TTY, say.
|
|
366
|
+
* const forced = createServerSink({ styled: true })
|
|
367
|
+
* forced.styled // true, whatever the environment and the streams say
|
|
368
|
+
*
|
|
369
|
+
* // Own every output path — a direct process.stdout.write, library output, child-process pipes:
|
|
370
|
+
* const capture = new ProcessCapture({ levels: ['stderr'], mirror: true })
|
|
371
|
+
* capture.start()
|
|
372
|
+
* process.stderr.write('a library diagnostic\n') // captured and still shown (mirror: true)
|
|
373
|
+
* capture.messages('stderr') // [{ level: 'stderr', text: 'a library diagnostic\n', time: … }]
|
|
374
|
+
* capture.clear() // drop buffered chunks; interception is unaffected
|
|
375
|
+
* capture.stop()
|
|
376
|
+
* capture.destroy() // stop() then tear down the emitter
|
|
358
377
|
* ```
|
|
359
378
|
*/
|
|
360
379
|
function createServerSink(options) {
|
|
@@ -382,7 +401,7 @@ function createServerSink(options) {
|
|
|
382
401
|
target.write(keep ? line : (0, _src_core.stripControls)((0, _src_core.strip)(line)));
|
|
383
402
|
},
|
|
384
403
|
get columns() {
|
|
385
|
-
return
|
|
404
|
+
return (0, _orkestrel_contract.isNumber)(fixed) ? fixed : inferColumns(out);
|
|
386
405
|
}
|
|
387
406
|
});
|
|
388
407
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/server/constants.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/ProcessCapture.ts","../../../src/server/factories.ts"],"sourcesContent":["// Server-console constants (the server branch) — UPPER_SNAKE, `Object.freeze`d data. The kind-pure home\n// for every module-scope constant the sink + process capture use: the default stream\n// set, the buffer cap, the no-TTY column fallback, and the stream→log-level projection.\n\nimport type { LogLevel } from '@src/core'\nimport type { StreamLevel } from './types.js'\n\n/**\n * Lists the two process streams a {@link import('./types.js').ProcessCaptureInterface} can intercept, in\n * `stdout`-then-`stderr` order — the {@link StreamLevel} universe and the default configured set.\n */\nexport const STREAM_LEVELS: readonly StreamLevel[] = Object.freeze(['stdout', 'stderr'])\n\n/**\n * Sets the default bounded-buffer cap for a {@link import('./types.js').ProcessCaptureInterface} — at\n * most this many recent {@link import('./types.js').CapturedChunk}s are retained per buffer (the\n * total buffer and each per-stream bucket; oldest dropped first). Mirrors the core `Capture`'s\n * `DEFAULT_CAPTURE_LIMIT`; a consumer overrides it through `options.limit`.\n */\nexport const DEFAULT_STREAM_LIMIT = 1000\n\n/**\n * Sets the terminal width {@link import('./factories.js').createServerSink} reports through\n * {@link import('./types.js').ServerSinkInterface.columns} when the `stdout` stream is not a TTY (so\n * `.columns` is `undefined`) and no explicit `options.columns` was supplied — the conventional\n * 80-column default a non-interactive context (a pipe, a CI log) assumes.\n */\nexport const DEFAULT_COLUMNS = 80\n\n/**\n * Maps each {@link StreamLevel} to its {@link LogLevel} for the optional sink forward — the projection a\n * process capture routes through when writing an intercepted chunk to a\n * {@link import('@src/core').SinkInterface}\n * (`sink.write(text, STREAM_LEVEL_MAP[level])`). `stderr` is conventionally the error/diagnostic\n * stream → `error`; `stdout` is the normal output stream → `info`. The source of truth for the\n * stream-to-log projection (the server analogue of the core `CAPTURE_LEVEL_MAP`).\n */\nexport const STREAM_LEVEL_MAP: Readonly<Record<StreamLevel, LogLevel>> = Object.freeze({\n\tstdout: 'info',\n\tstderr: 'error',\n})\n","// Total boundary guards for the server-console branch; every guard here is exported and unit-tested.\n// They narrow the two unavoidable boundaries the sink and the process capture cross — an injected or\n// real stream target, and the encoding argument a `process.*.write` carries — so neither surface\n// needs a type assertion and neither can throw on adversarial input.\n\nimport type { StreamTargetInterface } from './types.js'\n\n/**\n * Checks whether `value` is a usable {@link StreamTargetInterface} — a record with a callable `write`. A\n * total type guard: it never throws and returns `false` for anything off-shape, so it\n * narrows the one unavoidable boundary (the real `process.stdout` / `process.stderr`, or a fake\n * stream a test injects) to the exact slice the sink + capture touch — no `as`.\n *\n * @remarks\n * Only `write` is required (the irreducible output method); `isTTY` and `columns` are optional on\n * {@link StreamTargetInterface}, so their absence does not disqualify a target — a piped stream\n * (no `isTTY`) is still a valid write target, only a non-terminal one.\n *\n * @param value - Any value crossing the boundary (a process stream, an injected fake, `unknown`)\n * @returns True if `value` has a callable `write`; false otherwise\n *\n * @example\n * ```ts\n * isStreamTarget(process.stdout) // true\n * isStreamTarget({ write: () => true }) // true\n * isStreamTarget({}) // false (no write)\n * ```\n */\nexport function isStreamTarget(value: unknown): value is StreamTargetInterface {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t'write' in value &&\n\t\ttypeof value.write === 'function'\n\t)\n}\n\n/**\n * Checks whether `encoding` is a {@link BufferEncoding} accepted by `Buffer.prototype.toString` — a total\n * guard used by {@link import('./helpers.js').decodeChunk} to honor a process-write `encoding`\n * argument only when it is a real Node encoding (otherwise utf-8 is assumed).\n *\n * @param encoding - The candidate encoding (the second `write` argument, possibly a callback)\n * @returns True if `encoding` names a supported buffer encoding; false otherwise\n */\nexport function isBufferEncoding(encoding: unknown): encoding is BufferEncoding {\n\treturn typeof encoding === 'string' && Buffer.isEncoding(encoding)\n}\n","// Pure helpers for the server-console branch; every function here is exported and unit-tested.\n// Total utilities: the TTY column probe, the total chunk→text decoder the process-capture wrapper\n// reuses so intercepting `process.*.write` can never throw, and pure color-environment inference\n// for the server sink. The boundary guards live in `validators.ts`.\n\nimport type { StreamTargetInterface } from './types.js'\nimport { DEFAULT_COLUMNS } from './constants.js'\nimport { isBufferEncoding } from './validators.js'\n\n/**\n * Infers the width in character cells of a stream target — its live `columns` when it is a TTY, else\n * the non-interactive {@link DEFAULT_COLUMNS} fallback. The basis a {@link import('./types.js').ServerSinkInterface}\n * reports through `columns` so a `Reporter` / `Progress` can size its layout to the terminal.\n *\n * @remarks\n * Reads `target.columns` on each call (so a getter-backed real stream reflects a live resize) and\n * accepts it only when it is a positive finite number; a missing / `0` / non-finite `columns` (a\n * piped, non-TTY stream) falls back to {@link DEFAULT_COLUMNS}. Total — never throws.\n *\n * @param target - The stream whose width to probe\n * @returns The terminal column count, or {@link DEFAULT_COLUMNS} when not a TTY\n */\nexport function inferColumns(target: StreamTargetInterface): number {\n\tconst columns = target.columns\n\tif (typeof columns === 'number' && Number.isFinite(columns) && columns > 0) return columns\n\treturn DEFAULT_COLUMNS\n}\n\n/**\n * Infers whether one stream target receives styled output. The result is a construction-time\n * target fact for {@link import('./factories.js').createServerSink}; this helper is pure and never\n * reads process globals itself.\n *\n * @remarks\n * A present `FORCE_COLOR` key has first precedence: only the exact value `'0'` disables styling.\n * Next, a non-empty `NO_COLOR` disables styling. Otherwise styling follows\n * `target.isTTY === true`.\n *\n * @param target - The stream target whose terminal capability is the fallback\n * @param environment - The environment record supplying `FORCE_COLOR` and `NO_COLOR`\n * @returns True if output for the target retains styling and control sequences; false otherwise\n *\n * @example\n * ```ts\n * inferStyled({ write: () => true, isTTY: false }, { FORCE_COLOR: '1' }) // true\n * inferStyled({ write: () => true, isTTY: true }, { NO_COLOR: '1' }) // false\n * ```\n */\nexport function inferStyled(\n\ttarget: StreamTargetInterface,\n\tenvironment: Readonly<Record<string, string | undefined>>,\n): boolean {\n\tif (Object.hasOwn(environment, 'FORCE_COLOR')) return environment.FORCE_COLOR !== '0'\n\tconst disabled = environment.NO_COLOR\n\tif (disabled !== undefined && disabled !== '') return false\n\treturn target.isTTY === true\n}\n\n/**\n * Decodes one `process.stdout.write` / `process.stderr.write` chunk to a string — total, never\n * throws. The process write signature accepts `string | Uint8Array` plus an optional\n * encoding; the capture wrapper reuses this so intercepting a raw stream write can never crash the\n * host (a throw inside `process.stdout.write` would take the program down).\n *\n * @remarks\n * - A `string` chunk is returned verbatim — the common case (`console.log`, most library output,\n * and `process.stdout.write('text')` all pass a string).\n * - A `Buffer` chunk is decoded with the supplied `encoding` when it is a recognized\n * {@link BufferEncoding} (`process` write supports `'utf8'` / `'hex'` / `'base64'` / …), defaulting\n * to `'utf8'`; a bare `Uint8Array` is decoded through `TextDecoder` (always utf-8 — the `encoding`\n * argument applies only to a `Buffer`, never a plain `Uint8Array`).\n * - Anything else is coerced with `String(chunk)` (a number / object / bigint / symbol a misbehaving\n * writer hands the stream). The coercion is itself guarded: a value whose `toString` /\n * `Symbol.toPrimitive` throws yields the stable `'[unprintable]'` placeholder. So the helper is\n * total on every input — it always yields some string, never an exception (a throw here would\n * escape into `process.*.write` and crash the host).\n *\n * @param chunk - The chunk passed to the stream's `write`\n * @param encoding - The optional encoding argument passed alongside the chunk\n * @returns The chunk as text\n *\n * @example\n * ```ts\n * decodeChunk('hi') // 'hi'\n * decodeChunk(Buffer.from('hi')) // 'hi'\n * decodeChunk(new Uint8Array([104, 105])) // 'hi'\n * ```\n */\nexport function decodeChunk(chunk: unknown, encoding?: unknown): string {\n\tif (typeof chunk === 'string') return chunk\n\ttry {\n\t\tif (Buffer.isBuffer(chunk)) {\n\t\t\treturn chunk.toString(isBufferEncoding(encoding) ? encoding : 'utf8')\n\t\t}\n\t\tif (chunk instanceof Uint8Array) return new TextDecoder().decode(chunk)\n\t\t// The String() coercion is inside the try too: a value with a hostile `toString` /\n\t\t// `Symbol.toPrimitive` would otherwise throw here and escape into `process.*.write`, crashing\n\t\t// the host — the exact failure this total decoder exists to prevent. Guard it.\n\t\treturn String(chunk)\n\t} catch {\n\t\t// Any decode / coercion failure yields a stable placeholder — the helper is total on every\n\t\t// input (the kind a misbehaving writer could hand the patched stream), never an exception.\n\t\treturn '[unprintable]'\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tCapturedChunk,\n\tProcessCaptureEventMap,\n\tProcessCaptureInterface,\n\tProcessCaptureOptions,\n\tStreamLevel,\n\tStreamWriteCallback,\n\tStreamWriteFunction,\n} from './types.js'\nimport type { RetentionInterface, SinkInterface } from '@src/core'\nimport { StringDecoder } from 'node:string_decoder'\nimport { Emitter } from '@orkestrel/emitter'\nimport { Retention } from '@src/core'\nimport { DEFAULT_STREAM_LIMIT, STREAM_LEVEL_MAP, STREAM_LEVELS } from './constants.js'\nimport { decodeChunk } from './helpers.js'\nimport { isBufferEncoding } from './validators.js'\n\n/**\n * Implements an observable interceptor of the raw process output streams — it takes control of\n * `process.stdout.write` / `process.stderr.write` on the write side. While `active`, every write to\n * a configured {@link StreamLevel} is captured as a frozen {@link CapturedChunk}, buffered (total +\n * per-stream, bounded), emitted on `capture`, and — per options — mirrored to the real stream,\n * forwarded to a {@link SinkInterface}, or both.\n *\n * @remarks\n * Where the core `Capture` patches `console.*` (the high-level read side), this patches the\n * low-level stream `write`, so it owns all server output: a direct `process.stdout.write`, a\n * third-party library's writes, a child-process pipe — not only `console.*`.\n *\n * - **Snapshot-at-start (the no-capture-loop principle).** `start()` snapshots the current\n * `process[stream].write` for each configured level, then installs the wrappers. The mirror\n * replays through that snapshot (bound to its stream) — so a server sink created from the same\n * streams before the capture is never re-captured: this catches other writers, not the mirror's\n * own replay. Create your sinks before installing a capture.\n * - **Idempotent + process-global + non-reentrant.** `start()` while `active` is a no-op (never\n * double-patches — that would snapshot the wrapper as the \"original\" and break restore); `stop()`\n * while inactive is a no-op. It patches the one global `process`, so at most one process capture\n * may be active at a time — two concurrently would interleave buffers and clobber each other's\n * restore.\n * - **The wrapper never throws and passes backpressure through.** A throw inside\n * `process.stdout.write` would crash the host, so the wrapper decodes each chunk totally (a byte\n * chunk through the per-level streaming decoder below, everything else through the total\n * {@link decodeChunk}), and returns the snapshot-original's `boolean` when mirroring (so a caller's\n * `write` backpressure handling still works) or `true` when capture-only (the buffer never fills).\n * - **Streaming UTF-8 decode (no split-codepoint corruption).** `start()` gives each configured\n * {@link StreamLevel} a fresh persistent `StringDecoder`. A byte chunk with utf-8 or an omitted\n * encoding decodes through it, so a multibyte codepoint split across two `write` byte chunks — a\n * child-process pipe, a library, or OS buffering all produce this — carries its partial bytes to\n * the next write instead of decoding each half to `U+FFFD`. `stop()` flushes each decoder once, so\n * a codepoint left half-written at stop is still surfaced. A `string` chunk is already text and\n * passes through; an explicit non-utf-8 buffer encoding (`latin1` / `hex` / `base64` / …) names a\n * self-contained per-write decode and is honored one-shot through {@link decodeChunk}.\n * - **Bounded buffers.** The total buffer and each per-stream bucket are each capped at `limit`\n * (oldest dropped first), never unbounded — the same retention precedent as the core `Capture`.\n * - **Lifecycle.** `start` / `stop` toggle interception (emitting `start` / `stop`);\n * `destroy()` stops (restoring the pristine `write`) then destroys the emitter.\n *\n * @example\n * ```ts\n * const capture = new ProcessCapture({ levels: ['stderr'], mirror: true })\n * capture.start()\n * process.stderr.write('a library diagnostic\\n') // captured and still written to the terminal\n * capture.messages('stderr') // [{ level: 'stderr', text: 'a library diagnostic\\n', time: … }]\n * capture.stop() // process.stderr.write restored\n * ```\n */\nexport class ProcessCapture implements ProcessCaptureInterface {\n\t// The push observation surface — owned, never inherited. The emitter isolates a listener\n\t// throw (routing it to the `error` handler), so a buggy `capture` listener can never escape into\n\t// the host program's `process.*.write` call.\n\treadonly #emitter: Emitter<ProcessCaptureEventMap>\n\treadonly #levels: readonly StreamLevel[]\n\treadonly #mirror: boolean\n\treadonly #sink: SinkInterface | undefined\n\t// The bounded buffers — the total one and one per configured StreamLevel — owned by the shared\n\t// core retention engine the console `Capture` composes too.\n\treadonly #retention: RetentionInterface<CapturedChunk>\n\t// The snapshot-original `write` references, captured at start() and restored at stop(); empty\n\t// while inactive.\n\treadonly #originals = new Map<StreamLevel, StreamWriteFunction>()\n\t// One persistent streaming utf-8 decoder per configured level, created fresh in start() and\n\t// flushed + cleared in stop(). It carries a multibyte codepoint split across successive byte\n\t// writes so each half is not decoded to U+FFFD; empty while inactive.\n\treadonly #decoders = new Map<StreamLevel, StringDecoder>()\n\t// Stored rather than derived from #originals: an empty `levels` list patches no stream, so a\n\t// started capture configured with no level leaves #originals empty while still being active.\n\t#active = false\n\n\tconstructor(options?: ProcessCaptureOptions) {\n\t\tthis.#emitter = new Emitter<ProcessCaptureEventMap>({\n\t\t\t...(options?.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options?.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t\tthis.#levels = options?.levels ?? STREAM_LEVELS\n\t\tthis.#mirror = options?.mirror ?? false\n\t\tthis.#sink = options?.sink\n\t\tthis.#retention = new Retention<CapturedChunk>(\n\t\t\tthis.#levels,\n\t\t\toptions?.limit ?? DEFAULT_STREAM_LIMIT,\n\t\t)\n\t}\n\n\tget emitter(): EmitterInterface<ProcessCaptureEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget active(): boolean {\n\t\treturn this.#active\n\t}\n\n\tstart(): void {\n\t\t// Idempotent — never double-patch an already-active capture (that would snapshot the wrappers\n\t\t// as the \"originals\" and break restore).\n\t\tif (this.#active) return\n\t\tthis.#active = true\n\t\tfor (const level of this.#levels) {\n\t\t\tconst stream = this.#stream(level)\n\t\t\t// Snapshot the current write reference before replacing it — stop() restores exactly this\n\t\t\t// reference, leaving the stream pristine (the wrapper is never snapshotted as the original).\n\t\t\tconst original = stream.write\n\t\t\tthis.#originals.set(level, original)\n\t\t\t// The mirror target is the snapshot original bound to its stream, computed once here — so a\n\t\t\t// mirrored write reaches the real method with its proper receiver, through the snapshot and\n\t\t\t// never the live (patched) `write` (no capture loop). The restore reference stays the pristine\n\t\t\t// unbound `original` above; only the mirror uses the bound form.\n\t\t\tconst mirror = original.bind(stream)\n\t\t\t// The replacement matches the Node `write` overload shape exactly — `(chunk, encoding?, cb?)`\n\t\t\t// where the 2nd arg is either a `BufferEncoding` or the completion callback — so it assigns to\n\t\t\t// the stream's `write` slot and its args forward cleanly to `mirror` (no `as`, no untyped\n\t\t\t// spread).\n\t\t\tstream.write = this.#captureWrite.bind(this, level, mirror)\n\t\t\t// A fresh streaming decoder per cycle — a stop → start pair starts clean, never carrying a\n\t\t\t// stale partial byte from a prior capture into the new one.\n\t\t\tthis.#decoders.set(level, new StringDecoder('utf8'))\n\t\t}\n\t\tthis.#emitter.emit('start')\n\t}\n\n\tstop(): void {\n\t\t// Safe when not active — nothing to restore.\n\t\tif (!this.#active) return\n\t\tthis.#active = false\n\t\tfor (const [level, original] of this.#originals) this.#stream(level).write = original\n\t\tthis.#originals.clear()\n\t\t// Drain any trailing partial codepoint from each streaming decoder before the `stop` signal, so\n\t\t// a codepoint left half-written at stop is captured once rather than dropped.\n\t\tthis.#flush()\n\t\tthis.#emitter.emit('stop')\n\t}\n\n\tmessages(): readonly CapturedChunk[]\n\tmessages(level: StreamLevel): readonly CapturedChunk[]\n\tmessages(level?: StreamLevel): readonly CapturedChunk[] {\n\t\tif (level === undefined) return this.#retention.records()\n\t\treturn this.#retention.records(level)\n\t}\n\n\tclear(): void {\n\t\tthis.#retention.clear()\n\t}\n\n\tdestroy(): void {\n\t\tthis.stop()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// The global WriteStream for a StreamLevel — `process[level]` indexes it directly, since a\n\t// StreamLevel is the `process` property key (`'stdout'` / `'stderr'`); no `as`, no lookup map.\n\t#stream(level: StreamLevel): NodeJS.WriteStream {\n\t\treturn process[level]\n\t}\n\n\t// Adapt the patched stream's write signature to #intercept. Binding level and the pristine\n\t// mirror in start() leaves the canonical chunk / encoding / callback parameters.\n\t#captureWrite(\n\t\tlevel: StreamLevel,\n\t\tmirror: StreamWriteFunction,\n\t\tchunk: string | Uint8Array,\n\t\tencoding?: BufferEncoding | StreamWriteCallback,\n\t\tcallback?: StreamWriteCallback,\n\t): boolean {\n\t\treturn this.#intercept(level, chunk, encoding, callback, mirror)\n\t}\n\n\t// The wrapper body behind every patched stream write: decode the chunk to text (#decode — total,\n\t// streaming for byte chunks), record it (buffer bounded, emit `capture`, forward to the sink),\n\t// then — per options — mirror to the real stream. Never throws (#decode is total; the emitter\n\t// isolates listeners); the program's own write is replayed through `mirror` (the bound snapshot\n\t// original) only when the `mirror` option is set, and the original's backpressure boolean is\n\t// returned. Capture-only returns `true` (output is swallowed into the buffer, so the kernel buffer\n\t// never fills). The raw chunk (not the decoded text) is what mirrors, so the terminal still\n\t// receives the exact bytes; the `encoding` / `callback` tail is forwarded to the mirror branched\n\t// on whether the 2nd arg is the callback or an encoding (the two Node overloads), so a caller's\n\t// completion callback fires.\n\t#intercept(\n\t\tlevel: StreamLevel,\n\t\tchunk: string | Uint8Array,\n\t\tencoding: BufferEncoding | StreamWriteCallback | undefined,\n\t\tcallback: StreamWriteCallback | undefined,\n\t\tmirror: StreamWriteFunction,\n\t): boolean {\n\t\tthis.#record(level, this.#decode(level, chunk, encoding))\n\t\tif (!this.#mirror) {\n\t\t\t// Capture-only: the write never reaches the real stream, so fire the caller's completion\n\t\t\t// callback asynchronously (matching Node's own async completion semantics) rather than\n\t\t\t// silently dropping it — both call shapes (`write(chunk, cb)` and `write(chunk, encoding, cb)`)\n\t\t\t// are covered.\n\t\t\tconst done = typeof encoding === 'function' ? encoding : callback\n\t\t\tif (done !== undefined) queueMicrotask(() => done())\n\t\t\treturn true\n\t\t}\n\t\t// `write(chunk, cb)` when the 2nd arg is the callback; `write(chunk, encoding, cb)` otherwise —\n\t\t// matching the two Node overloads so the forward stays typed.\n\t\tif (typeof encoding === 'function') return mirror(chunk, encoding)\n\t\treturn mirror(chunk, encoding, callback)\n\t}\n\n\t// Decode one write chunk to text — total, never throws (a throw here would escape into the patched\n\t// process.*.write and crash the host). A `string` chunk is already text and passes through. A byte\n\t// chunk with utf-8 / an omitted encoding / a callback in the encoding slot streams through the\n\t// level's persistent decoder, carrying a codepoint split across writes; an explicit non-utf-8\n\t// buffer encoding is self-contained per write and decoded one-shot through decodeChunk.\n\t#decode(\n\t\tlevel: StreamLevel,\n\t\tchunk: string | Uint8Array,\n\t\tencoding: BufferEncoding | StreamWriteCallback | undefined,\n\t): string {\n\t\tif (typeof chunk === 'string') return chunk\n\t\tconst decoder = this.#decoders.get(level)\n\t\tif (decoder !== undefined && this.#streams(encoding)) {\n\t\t\treturn decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n\t\t}\n\t\treturn decodeChunk(chunk, encoding)\n\t}\n\n\t// Whether a byte chunk with this encoding routes through the persistent streaming decoder rather\n\t// than the one-shot decodeChunk. True for an omitted encoding, a callback in the slot, an\n\t// unrecognized string (all utf-8 by decodeChunk's own fallback), or an explicit utf-8; false only\n\t// for a recognized non-utf-8 buffer encoding, whose per-write bytes are self-contained.\n\t#streams(encoding: BufferEncoding | StreamWriteCallback | undefined): boolean {\n\t\tif (!isBufferEncoding(encoding)) return true\n\t\tconst normalized = encoding.toLowerCase()\n\t\treturn normalized === 'utf8' || normalized === 'utf-8'\n\t}\n\n\t// Build the immutable, serializable captured chunk from already-decoded text, stamp it with the\n\t// capture instant, buffer it (total + per-stream, bounded), emit `capture`, then forward it to the\n\t// sink. Frozen so a consumer (or the `capture` listener) can never mutate it. Never throws into the\n\t// patched stream — the sink is a best-effort tee and the emitter isolates a listener throw.\n\t#record(level: StreamLevel, text: string): void {\n\t\tconst message: CapturedChunk = Object.freeze({ level, text, time: Date.now() })\n\t\tthis.#retention.add(message)\n\t\tthis.#emitter.emit('capture', message)\n\t\tif (this.#sink !== undefined) {\n\t\t\ttry {\n\t\t\t\tthis.#sink.write(message.text, STREAM_LEVEL_MAP[level])\n\t\t\t} catch {\n\t\t\t\t// The sink is a best-effort tee; the wrapper never throws into the patched global stream —\n\t\t\t\t// a broken/throwing sink must not crash the host's process.stdout / process.stderr write.\n\t\t\t}\n\t\t}\n\t}\n\n\t// Drain each streaming decoder's trailing partial codepoint once — `decoder.end()` emits the\n\t// pending bytes' final text (U+FFFD for a genuinely truncated sequence) — so a codepoint left\n\t// half-written at stop is recorded, not silently dropped. An empty flush adds no record. Clears\n\t// the decoders so the next start() begins clean.\n\t#flush(): void {\n\t\tfor (const [level, decoder] of this.#decoders) {\n\t\t\tconst text = decoder.end()\n\t\t\tif (text !== '') this.#record(level, text)\n\t\t}\n\t\tthis.#decoders.clear()\n\t}\n}\n","import type { LogLevel } from '@src/core'\nimport type { ServerSinkInterface, ServerSinkOptions } from './types.js'\nimport { selectWriter, strip, stripControls } from '@src/core'\nimport { inferColumns, inferStyled } from './helpers.js'\nimport { isStreamTarget } from './validators.js'\n\n/**\n * Creates the server TTY {@link ServerSinkInterface} — the server output backend, the\n * env-symmetric sibling of `createBrowserSink` / core's `createConsoleSink`. `write(text, level?)`\n * routes by level to the process streams and uses construction-time styled facts: it sends ANSI\n * straight to a styled target (with a leading `\\r` overwriting a terminal line natively) but\n * {@link import('@src/core').strip}s ANSI to clean text for a plain target.\n *\n * @param options - See {@link ServerSinkOptions}\n * @returns A {@link ServerSinkInterface} — a {@link import('@src/core').SinkInterface} that also\n * exposes the terminal `columns` width\n *\n * @remarks\n * - **Routes by level.** `error` / `warn` → the error stream (`process.stderr` by default), every\n * other level (and an omitted level) → the `stdout` stream (`process.stdout`) — the same routing\n * as core's `createConsoleSink`, so a logger's `error` reaches `stderr`. Both call the one\n * {@link import('@src/core').selectWriter} leaf, which is what keeps them identical.\n * - **Per-target styled facts.** At construction, each target uses `options.styled` when supplied;\n * otherwise {@link inferStyled} applies the injected `environment` (default `process.env`) and\n * then that target's `isTTY`.\n * Writes use those stored facts, so `styled` and the `stdout` target's strip decision never\n * disagree; the `stderr` target keeps its own fact internally.\n * - **Width.** `columns` reflects the live `stdout.columns` (so it tracks a terminal resize),\n * falling back to {@link import('./constants.js').DEFAULT_COLUMNS} when the `stdout` stream is not\n * a TTY — or a fixed value when `options.columns` is supplied. Feed it to a `Reporter` /\n * `Progress` `width`.\n * - **Injectable + guard-narrowed.** `options.stdout` / `options.stderr` default to `process.stdout`\n * / `process.stderr` but accept any {@link import('./types.js').StreamTargetInterface}, resolved\n * through {@link isStreamTarget} (narrow the boundary, never `as`), so a test drives\n * the sink (and the isTTY-strip path) with a fake stream that never touches the real process\n * streams.\n *\n * @example\n * ```ts\n * import { createStyler, Logger, Reporter } from '@orkestrel/console'\n * import { createServerSink } from '@orkestrel/console/server'\n *\n * const sink = createServerSink()\n * const styler = createStyler({ enabled: sink.styled })\n * const logger = new Logger({ name: 'app', sink, styler })\n * logger.error('boom') // → process.stderr, ANSI rendered on a TTY / stripped to a pipe\n * const reporter = new Reporter({ sink, width: sink.columns })\n * ```\n */\nexport function createServerSink(options?: ServerSinkOptions): ServerSinkInterface {\n\t// Resolve each target through the guard: a present, well-shaped injected stream is used as\n\t// is; otherwise the real process stream — no `as`, and an `undefined` option falls through to the\n\t// default. `stdout` carries info/debug, `stderr` carries error/warn.\n\tconst out = isStreamTarget(options?.stdout) ? options.stdout : process.stdout\n\tconst err = isStreamTarget(options?.stderr) ? options.stderr : process.stderr\n\tconst styled = options?.styled\n\tconst environment = options?.environment ?? process.env\n\tconst outStyled = styled ?? inferStyled(out, environment)\n\tconst errStyled = styled ?? inferStyled(err, environment)\n\tconst fixed = options?.columns\n\treturn Object.freeze({\n\t\tstyled: outStyled,\n\t\twrite(text: string, level?: LogLevel): void {\n\t\t\t// The one shared routing leaf picks the target and its styled fact together; `warn` shares\n\t\t\t// the error stream here, matching `console.warn` writing to stderr in core.\n\t\t\tconst target = selectWriter(level, { log: out, warn: err, error: err })\n\t\t\tconst keep = selectWriter(level, { log: outStyled, warn: errStyled, error: errStyled })\n\t\t\t// A leading `\\r` marks an in-place redraw frame (Spinner/Progress), which carries its own\n\t\t\t// line endings and is written verbatim; every other (line-oriented) write gets exactly one\n\t\t\t// trailing `\\n` appended here, matching `console.log`'s newline-terminated behavior.\n\t\t\tconst framed = text.startsWith('\\r')\n\t\t\tconst line = framed ? text : `${text}\\n`\n\t\t\t// A styled target receives the line verbatim; a plain target receives visible text only.\n\t\t\ttarget.write(keep ? line : stripControls(strip(line)))\n\t\t},\n\t\tget columns(): number {\n\t\t\t// A fixed override wins; otherwise the live stdout-stream width (tracks a resize), with the\n\t\t\t// non-TTY fallback inside inferColumns.\n\t\t\treturn typeof fixed === 'number' ? fixed : inferColumns(out)\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,gBAAwC,OAAO,OAAO,CAAC,UAAU,QAAQ,CAAC;;;;;;;AAQvF,IAAa,uBAAuB;;;;;;;AAQpC,IAAa,kBAAkB;;;;;;;;;AAU/B,IAAa,mBAA4D,OAAO,OAAO;CACtF,QAAQ;CACR,QAAQ;AACT,CAAC;;;;;;;;;;;;;;;;;;;;;;;;ACZD,SAAgB,eAAe,OAAgD;CAC9E,OACC,OAAO,UAAU,YACjB,UAAU,QACV,WAAW,SACX,OAAO,MAAM,UAAU;AAEzB;;;;;;;;;AAUA,SAAgB,iBAAiB,UAA+C;CAC/E,OAAO,OAAO,aAAa,YAAY,OAAO,WAAW,QAAQ;AAClE;;;;;;;;;;;;;;;;ACzBA,SAAgB,aAAa,QAAuC;CACnE,MAAM,UAAU,OAAO;CACvB,IAAI,OAAO,YAAY,YAAY,OAAO,SAAS,OAAO,KAAK,UAAU,GAAG,OAAO;CACnF,OAAA;AACD;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,YACf,QACA,aACU;CACV,IAAI,OAAO,OAAO,aAAa,aAAa,GAAG,OAAO,YAAY,gBAAgB;CAClF,MAAM,WAAW,YAAY;CAC7B,IAAI,aAAa,KAAA,KAAa,aAAa,IAAI,OAAO;CACtD,OAAO,OAAO,UAAU;AACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,YAAY,OAAgB,UAA4B;CACvE,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI;EACH,IAAI,OAA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W,IAClB,IAAS,OAAO,GAAG,KAAK;GAErC,OAAO,MAAM,OAAO,QAAA,GAAO,UAAA,cAAA,EAAA,GAAc,UAAA,MAAA,CAAM,IAAI,CAAC,CAAC;EACtD;EACA,IAAI,UAAkB;GAGrB,OAAO,OAAO,UAAU,WAAW,QAAQ,aAAa,GAAG;EAC5D;CACD,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../../../src/server/constants.ts","../../../src/server/validators.ts","../../../src/server/helpers.ts","../../../src/server/ProcessCapture.ts","../../../src/server/factories.ts"],"sourcesContent":["// Server-console constants (the server branch) — UPPER_SNAKE, `Object.freeze`d data. The kind-pure home\n// for every module-scope constant the sink + process capture use: the default stream\n// set, the buffer cap, the no-TTY column fallback, and the stream→log-level projection.\n\nimport type { LogLevel } from '@src/core'\nimport type { StreamLevel } from './types.js'\n\n/**\n * Lists the process streams a {@link import('./types.js').ProcessCaptureInterface} can intercept,\n * in `stdout`-then-`stderr` order — the {@link StreamLevel} universe and the default configured\n * set.\n */\nexport const STREAM_LEVELS: readonly StreamLevel[] = Object.freeze(['stdout', 'stderr'])\n\n/**\n * Sets the default bounded-buffer cap for a {@link import('./types.js').ProcessCaptureInterface} —\n * `1000`, so at most that many recent {@link import('./types.js').CapturedChunk}s are retained per\n * buffer (the total buffer and each per-stream bucket; oldest dropped first) and retention is\n * always bounded.\n *\n * @remarks\n * It mirrors the core `Capture`'s `DEFAULT_CAPTURE_LIMIT`; a consumer overrides the cap through\n * `options.limit`.\n */\nexport const DEFAULT_STREAM_LIMIT = 1000\n\n/**\n * Sets the terminal width {@link import('./factories.js').createServerSink} reports through\n * {@link import('./types.js').ServerSinkInterface.columns} when the `stdout` stream is not a TTY\n * (so `.columns` is `undefined`) and no explicit `options.columns` was supplied — the conventional\n * 80-column default a non-interactive context (a pipe, a CI log) assumes.\n */\nexport const DEFAULT_COLUMNS = 80\n\n/**\n * Maps each {@link StreamLevel} to its {@link LogLevel} for the optional sink forward — the\n * projection a process capture routes through when writing an intercepted chunk to a\n * {@link import('@src/core').SinkInterface}. `sink.write(text, STREAM_LEVEL_MAP[level])` is the\n * call this map backs. `stderr` is conventionally the error/diagnostic stream → `error`; `stdout`\n * is the normal output stream → `info`. The source of truth for the stream-to-log projection (the\n * server analogue of the core `CAPTURE_LEVEL_MAP`).\n */\nexport const STREAM_LEVEL_MAP: Readonly<Record<StreamLevel, LogLevel>> = Object.freeze({\n\tstdout: 'info',\n\tstderr: 'error',\n})\n","// Total boundary guards for the server-console branch; every guard here is exported and unit-tested.\n// They narrow the two unavoidable boundaries the sink and the process capture cross — an injected or\n// real stream target, and the encoding argument a `process.*.write` carries — so neither surface\n// needs a type assertion and neither can throw on adversarial input.\n\nimport type { StreamTargetInterface } from './types.js'\nimport { isFunction, isObject, isString } from '@orkestrel/contract'\n\n/**\n * Checks whether `value` is a usable {@link StreamTargetInterface} — a record with a callable `write`. A\n * total type guard: it never throws and returns `false` for anything off-shape, so it\n * narrows the one unavoidable boundary (the real `process.stdout` / `process.stderr`, or a fake\n * stream a test injects) to the exact slice the sink + capture touch — no `as`.\n *\n * @remarks\n * Only `write` is required (the irreducible output method); `isTTY` and `columns` are optional on\n * {@link StreamTargetInterface}, so their absence does not disqualify a target — a piped stream\n * (no `isTTY`) is still a valid write target, only a non-terminal one.\n *\n * @param value - Any value crossing the boundary (a process stream, an injected fake, `unknown`)\n * @returns True if `value` has a callable `write`; false otherwise\n *\n * @example\n * ```ts\n * isStreamTarget(process.stdout) // true\n * isStreamTarget({ write: () => true }) // true\n * isStreamTarget({}) // false (no write)\n * ```\n */\nexport function isStreamTarget(value: unknown): value is StreamTargetInterface {\n\treturn isObject(value) && 'write' in value && isFunction(value.write)\n}\n\n/**\n * Checks whether `encoding` is a {@link BufferEncoding} accepted by `Buffer.prototype.toString` — a\n * total guard used by {@link import('./helpers.js').decodeChunk} to honor a process-write\n * `encoding` argument only when it is a real Node encoding (otherwise utf-8 is assumed).\n *\n * @param encoding - The candidate encoding (the second `write` argument, possibly a callback)\n * @returns True if `encoding` names a supported buffer encoding; false otherwise\n */\nexport function isBufferEncoding(encoding: unknown): encoding is BufferEncoding {\n\treturn isString(encoding) && Buffer.isEncoding(encoding)\n}\n","// Pure helpers for the server-console branch; every function here is exported and unit-tested.\n// Total utilities: the TTY column probe, the total chunk→text decoder the process-capture wrapper\n// reuses so intercepting `process.*.write` can never throw, and pure color-environment inference\n// for the server sink. The boundary guards live in `validators.ts`.\n\nimport type { StreamTargetInterface } from './types.js'\nimport { isFiniteNumber, isString, isUint8Array } from '@orkestrel/contract'\nimport { DEFAULT_COLUMNS } from './constants.js'\nimport { isBufferEncoding } from './validators.js'\n\n/**\n * Infers the width in character cells of a stream target — its live `columns` when it is a TTY,\n * else the non-interactive {@link DEFAULT_COLUMNS} fallback. The basis a\n * {@link import('./types.js').ServerSinkInterface} reports through `columns` so a `Reporter` /\n * `Progress` can size its layout to the terminal.\n *\n * @remarks\n * Reads `target.columns` on each call (so a getter-backed real stream reflects a live resize) and\n * accepts it only when it is a positive finite number; a missing / `0` / non-finite `columns` (a\n * piped, non-TTY stream) falls back to {@link DEFAULT_COLUMNS}. Total — never throws.\n *\n * @param target - The stream whose width to probe\n * @returns The terminal column count, or {@link DEFAULT_COLUMNS} when not a TTY\n */\nexport function inferColumns(target: StreamTargetInterface): number {\n\tconst columns = target.columns\n\tif (isFiniteNumber(columns) && columns > 0) return columns\n\treturn DEFAULT_COLUMNS\n}\n\n/**\n * Infers whether one stream target receives styled output — a present `FORCE_COLOR` first, then a\n * non-empty `NO_COLOR`, then `target.isTTY === true`.\n *\n * @remarks\n * The result is a construction-time target fact for\n * {@link import('./factories.js').createServerSink}; this helper is pure and\n * never reads process globals itself. Under `FORCE_COLOR` only the exact value `'0'` disables\n * styling.\n *\n * @param target - The stream target whose terminal capability is the fallback\n * @param environment - The environment record supplying `FORCE_COLOR` and `NO_COLOR`\n * @returns True if output for the target retains styling and control sequences; false otherwise\n *\n * @example\n * ```ts\n * inferStyled({ write: () => true, isTTY: false }, { FORCE_COLOR: '1' }) // true\n * inferStyled({ write: () => true, isTTY: true }, { NO_COLOR: '1' }) // false\n * ```\n */\nexport function inferStyled(\n\ttarget: StreamTargetInterface,\n\tenvironment: Readonly<Record<string, string | undefined>>,\n): boolean {\n\tif (Object.hasOwn(environment, 'FORCE_COLOR')) return environment.FORCE_COLOR !== '0'\n\tconst disabled = environment.NO_COLOR\n\tif (disabled !== undefined && disabled !== '') return false\n\treturn target.isTTY === true\n}\n\n/**\n * Decodes one `process.stdout.write` / `process.stderr.write` chunk to a string — total, never\n * throws. The process write signature accepts `string | Uint8Array` plus an optional\n * encoding; the capture wrapper reuses this so intercepting a raw stream write can never crash the\n * host (a throw inside `process.stdout.write` would take the program down).\n *\n * @remarks\n * - A `string` chunk is returned verbatim — the common case (`console.log`, most library output,\n * and `process.stdout.write('text')` all pass a string).\n * - A `Buffer` chunk is decoded with the supplied `encoding` when it is a recognized\n * {@link BufferEncoding} (`process` write supports `'utf8'` / `'hex'` / `'base64'` / …), defaulting\n * to `'utf8'`; a bare `Uint8Array` is decoded through `TextDecoder` (always utf-8 — the `encoding`\n * argument applies only to a `Buffer`, never a plain `Uint8Array`).\n * - Anything else is coerced with `String(chunk)` (a number / object / bigint / symbol a misbehaving\n * writer hands the stream). The coercion is itself guarded: a value whose `toString` /\n * `Symbol.toPrimitive` throws yields the stable `'[unprintable]'` placeholder. So the helper is\n * total on every input — it always yields some string, never an exception (a throw here would\n * escape into `process.*.write` and crash the host).\n *\n * @param chunk - The chunk passed to the stream's `write`\n * @param encoding - The optional encoding argument passed alongside the chunk\n * @returns The chunk as text\n *\n * @example\n * ```ts\n * decodeChunk('hi') // 'hi'\n * decodeChunk(Buffer.from('hi')) // 'hi'\n * decodeChunk(new Uint8Array([104, 105])) // 'hi'\n * ```\n */\nexport function decodeChunk(chunk: unknown, encoding?: unknown): string {\n\tif (isString(chunk)) return chunk\n\ttry {\n\t\tif (Buffer.isBuffer(chunk)) {\n\t\t\treturn chunk.toString(isBufferEncoding(encoding) ? encoding : 'utf8')\n\t\t}\n\t\tif (isUint8Array(chunk)) return new TextDecoder().decode(chunk)\n\t\t// The String() coercion is inside the try too: a value with a hostile `toString` /\n\t\t// `Symbol.toPrimitive` would otherwise throw here and escape into `process.*.write`, crashing\n\t\t// the host — the exact failure this total decoder exists to prevent. Guard it.\n\t\treturn String(chunk)\n\t} catch {\n\t\t// Any decode / coercion failure yields a stable placeholder — the helper is total on every\n\t\t// input (the kind a misbehaving writer could hand the patched stream), never an exception.\n\t\treturn '[unprintable]'\n\t}\n}\n","import type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tCapturedChunk,\n\tProcessCaptureEventMap,\n\tProcessCaptureInterface,\n\tProcessCaptureOptions,\n\tStreamLevel,\n\tStreamWriteCallback,\n\tStreamWriteFunction,\n} from './types.js'\nimport type { RetentionInterface, SinkInterface } from '@src/core'\nimport { StringDecoder } from 'node:string_decoder'\nimport { isString } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport { Retention } from '@src/core'\nimport { DEFAULT_STREAM_LIMIT, STREAM_LEVEL_MAP, STREAM_LEVELS } from './constants.js'\nimport { decodeChunk } from './helpers.js'\nimport { isBufferEncoding } from './validators.js'\n\n/**\n * Implements an observable interceptor of the raw process output streams — it takes control of\n * `process.stdout.write` / `process.stderr.write` on the write side. While `active`, every write to\n * a configured {@link StreamLevel} is captured as a frozen {@link CapturedChunk}, buffered (total +\n * per-stream, bounded), emitted on `capture`, and — per options — mirrored to the real stream,\n * forwarded to a {@link SinkInterface}, or both.\n *\n * @remarks\n * Where the core `Capture` patches `console.*` (the high-level read side), this patches the\n * low-level stream `write`, so it owns all server output: a direct `process.stdout.write`, a\n * third-party library's writes, a child-process pipe — not only `console.*`.\n *\n * - **Snapshot-at-start (the no-capture-loop principle).** `start()` snapshots the current\n * `process[stream].write` for each configured level, then installs the wrappers. The mirror\n * replays through that snapshot (bound to its stream) — so a server sink created from the same\n * streams before the capture is never re-captured: this catches other writers, not the mirror's\n * own replay. Create your sinks before installing a capture.\n * - **Idempotent + process-global + non-reentrant.** `start()` while `active` is a no-op (never\n * double-patches — that would snapshot the wrapper as the \"original\" and break restore); `stop()`\n * while inactive is a no-op. It patches the one global `process`, so at most one process capture\n * may be active at a time — two concurrently would interleave buffers and clobber each other's\n * restore.\n * - **The wrapper never throws and passes backpressure through.** A throw inside\n * `process.stdout.write` would crash the host, so the wrapper decodes each chunk totally (a byte\n * chunk through the per-level streaming decoder below, everything else through the total\n * {@link decodeChunk}), and returns the snapshot-original's `boolean` when mirroring (so a caller's\n * `write` backpressure handling still works) or `true` when capture-only (the buffer never fills).\n * - **Streaming UTF-8 decode (no split-codepoint corruption).** `start()` gives each configured\n * {@link StreamLevel} a fresh persistent `StringDecoder`. A byte chunk with utf-8 or an omitted\n * encoding decodes through it, so a multibyte codepoint split across two `write` byte chunks — a\n * child-process pipe, a library, or OS buffering all produce this — carries its partial bytes to\n * the next write instead of decoding each half to `U+FFFD`. `stop()` flushes each decoder once, so\n * a codepoint left half-written at stop is still surfaced. A `string` chunk is already text and\n * passes through; an explicit non-utf-8 buffer encoding (`latin1` / `hex` / `base64` / …) names a\n * self-contained per-write decode and is honored one-shot through {@link decodeChunk}.\n * - **Bounded buffers.** The total buffer and each per-stream bucket are each capped at `limit`\n * (oldest dropped first), never unbounded — the same retention precedent as the core `Capture`.\n * - **Lifecycle.** `start` / `stop` toggle interception (emitting `start` / `stop`);\n * `destroy()` stops (restoring the pristine `write`) then destroys the emitter.\n *\n * @example\n * ```ts\n * const capture = new ProcessCapture({ levels: ['stderr'], mirror: true })\n * capture.start()\n * process.stderr.write('a library diagnostic\\n') // captured and still written to the terminal\n * capture.messages('stderr') // [{ level: 'stderr', text: 'a library diagnostic\\n', time: … }]\n * capture.stop() // process.stderr.write restored\n * ```\n */\nexport class ProcessCapture implements ProcessCaptureInterface {\n\t// The push observation surface — owned, never inherited. The emitter isolates a listener\n\t// throw (routing it to the `error` handler), so a buggy `capture` listener can never escape into\n\t// the host program's `process.*.write` call.\n\treadonly #emitter: Emitter<ProcessCaptureEventMap>\n\treadonly #levels: readonly StreamLevel[]\n\treadonly #mirror: boolean\n\treadonly #sink: SinkInterface | undefined\n\t// The bounded buffers — the total one and one per configured StreamLevel — owned by the shared\n\t// core retention engine the console `Capture` composes too.\n\treadonly #retention: RetentionInterface<CapturedChunk>\n\t// The snapshot-original `write` references, captured at start() and restored at stop(); empty\n\t// while inactive.\n\treadonly #originals = new Map<StreamLevel, StreamWriteFunction>()\n\t// One persistent streaming utf-8 decoder per configured level, created fresh in start() and\n\t// flushed + cleared in stop(). It carries a multibyte codepoint split across successive byte\n\t// writes so each half is not decoded to U+FFFD; empty while inactive.\n\treadonly #decoders = new Map<StreamLevel, StringDecoder>()\n\t// Stored rather than derived from #originals: an empty `levels` list patches no stream, so a\n\t// started capture configured with no level leaves #originals empty while still being active.\n\t#active = false\n\n\tconstructor(options?: ProcessCaptureOptions) {\n\t\tthis.#emitter = new Emitter<ProcessCaptureEventMap>({\n\t\t\t...(options?.on !== undefined ? { on: options.on } : {}),\n\t\t\t...(options?.error !== undefined ? { error: options.error } : {}),\n\t\t})\n\t\tthis.#levels = options?.levels ?? STREAM_LEVELS\n\t\tthis.#mirror = options?.mirror ?? false\n\t\tthis.#sink = options?.sink\n\t\tthis.#retention = new Retention<CapturedChunk>(\n\t\t\tthis.#levels,\n\t\t\toptions?.limit ?? DEFAULT_STREAM_LIMIT,\n\t\t)\n\t}\n\n\tget emitter(): EmitterInterface<ProcessCaptureEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\tget active(): boolean {\n\t\treturn this.#active\n\t}\n\n\tstart(): void {\n\t\t// Idempotent — never double-patch an already-active capture (that would snapshot the wrappers\n\t\t// as the \"originals\" and break restore).\n\t\tif (this.#active) return\n\t\tthis.#active = true\n\t\tfor (const level of this.#levels) {\n\t\t\tconst stream = this.#stream(level)\n\t\t\t// Snapshot the current write reference before replacing it — stop() restores exactly this\n\t\t\t// reference, leaving the stream pristine (the wrapper is never snapshotted as the original).\n\t\t\tconst original = stream.write\n\t\t\tthis.#originals.set(level, original)\n\t\t\t// The mirror target is the snapshot original bound to its stream, computed once here — so a\n\t\t\t// mirrored write reaches the real method with its proper receiver, through the snapshot and\n\t\t\t// never the live (patched) `write` (no capture loop). The restore reference stays the pristine\n\t\t\t// unbound `original` above; only the mirror uses the bound form.\n\t\t\tconst mirror = original.bind(stream)\n\t\t\t// The replacement matches the Node `write` overload shape exactly — `(chunk, encoding?, cb?)`\n\t\t\t// where the 2nd arg is either a `BufferEncoding` or the completion callback — so it assigns to\n\t\t\t// the stream's `write` slot and its args forward cleanly to `mirror` (no `as`, no untyped\n\t\t\t// spread).\n\t\t\tstream.write = this.#captureWrite.bind(this, level, mirror)\n\t\t\t// A fresh streaming decoder per cycle — a stop → start pair starts clean, never carrying a\n\t\t\t// stale partial byte from a prior capture into the new one.\n\t\t\tthis.#decoders.set(level, new StringDecoder('utf8'))\n\t\t}\n\t\tthis.#emitter.emit('start')\n\t}\n\n\tstop(): void {\n\t\t// Safe when not active — nothing to restore.\n\t\tif (!this.#active) return\n\t\tthis.#active = false\n\t\tfor (const [level, original] of this.#originals) this.#stream(level).write = original\n\t\tthis.#originals.clear()\n\t\t// Drain any trailing partial codepoint from each streaming decoder before the `stop` signal, so\n\t\t// a codepoint left half-written at stop is captured once rather than dropped.\n\t\tthis.#flush()\n\t\tthis.#emitter.emit('stop')\n\t}\n\n\tmessages(): readonly CapturedChunk[]\n\tmessages(level: StreamLevel): readonly CapturedChunk[]\n\tmessages(level?: StreamLevel): readonly CapturedChunk[] {\n\t\tif (level === undefined) return this.#retention.records()\n\t\treturn this.#retention.records(level)\n\t}\n\n\tclear(): void {\n\t\tthis.#retention.clear()\n\t}\n\n\tdestroy(): void {\n\t\tthis.stop()\n\t\tthis.#emitter.destroy()\n\t}\n\n\t// The global WriteStream for a StreamLevel — `process[level]` indexes it directly, since a\n\t// StreamLevel is the `process` property key (`'stdout'` / `'stderr'`); no `as`, no lookup map.\n\t#stream(level: StreamLevel): NodeJS.WriteStream {\n\t\treturn process[level]\n\t}\n\n\t// Adapt the patched stream's write signature to #intercept. Binding level and the pristine\n\t// mirror in start() leaves the canonical chunk / encoding / callback parameters.\n\t#captureWrite(\n\t\tlevel: StreamLevel,\n\t\tmirror: StreamWriteFunction,\n\t\tchunk: string | Uint8Array,\n\t\tencoding?: BufferEncoding | StreamWriteCallback,\n\t\tcallback?: StreamWriteCallback,\n\t): boolean {\n\t\treturn this.#intercept(level, chunk, encoding, callback, mirror)\n\t}\n\n\t// The wrapper body behind every patched stream write: decode the chunk to text (#decode — total,\n\t// streaming for byte chunks), record it (buffer bounded, emit `capture`, forward to the sink),\n\t// then — per options — mirror to the real stream. Never throws (#decode is total; the emitter\n\t// isolates listeners); the program's own write is replayed through `mirror` (the bound snapshot\n\t// original) only when the `mirror` option is set, and the original's backpressure boolean is\n\t// returned. Capture-only returns `true` (output is swallowed into the buffer, so the kernel buffer\n\t// never fills). The raw chunk (not the decoded text) is what mirrors, so the terminal still\n\t// receives the exact bytes; the `encoding` / `callback` tail is forwarded to the mirror branched\n\t// on whether the 2nd arg is the callback or an encoding (the two Node overloads), so a caller's\n\t// completion callback fires.\n\t#intercept(\n\t\tlevel: StreamLevel,\n\t\tchunk: string | Uint8Array,\n\t\tencoding: BufferEncoding | StreamWriteCallback | undefined,\n\t\tcallback: StreamWriteCallback | undefined,\n\t\tmirror: StreamWriteFunction,\n\t): boolean {\n\t\tthis.#record(level, this.#decode(level, chunk, encoding))\n\t\tif (!this.#mirror) {\n\t\t\t// Capture-only: the write never reaches the real stream, so fire the caller's completion\n\t\t\t// callback asynchronously (matching Node's own async completion semantics) rather than\n\t\t\t// silently dropping it — both call shapes (`write(chunk, cb)` and `write(chunk, encoding, cb)`)\n\t\t\t// are covered.\n\t\t\tconst done = typeof encoding === 'function' ? encoding : callback\n\t\t\tif (done !== undefined) queueMicrotask(() => done())\n\t\t\treturn true\n\t\t}\n\t\t// `write(chunk, cb)` when the 2nd arg is the callback; `write(chunk, encoding, cb)` otherwise —\n\t\t// matching the two Node overloads so the forward stays typed.\n\t\tif (typeof encoding === 'function') return mirror(chunk, encoding)\n\t\treturn mirror(chunk, encoding, callback)\n\t}\n\n\t// Decode one write chunk to text — total, never throws (a throw here would escape into the patched\n\t// process.*.write and crash the host). A `string` chunk is already text and passes through. A byte\n\t// chunk with utf-8 / an omitted encoding / a callback in the encoding slot streams through the\n\t// level's persistent decoder, carrying a codepoint split across writes; an explicit non-utf-8\n\t// buffer encoding is self-contained per write and decoded one-shot through decodeChunk.\n\t#decode(\n\t\tlevel: StreamLevel,\n\t\tchunk: string | Uint8Array,\n\t\tencoding: BufferEncoding | StreamWriteCallback | undefined,\n\t): string {\n\t\tif (isString(chunk)) return chunk\n\t\tconst decoder = this.#decoders.get(level)\n\t\tif (decoder !== undefined && this.#streams(encoding)) {\n\t\t\treturn decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))\n\t\t}\n\t\treturn decodeChunk(chunk, encoding)\n\t}\n\n\t// Whether a byte chunk with this encoding routes through the persistent streaming decoder rather\n\t// than the one-shot decodeChunk. True for an omitted encoding, a callback in the slot, an\n\t// unrecognized string (all utf-8 by decodeChunk's own fallback), or an explicit utf-8; false only\n\t// for a recognized non-utf-8 buffer encoding, whose per-write bytes are self-contained.\n\t#streams(encoding: BufferEncoding | StreamWriteCallback | undefined): boolean {\n\t\tif (!isBufferEncoding(encoding)) return true\n\t\tconst normalized = encoding.toLowerCase()\n\t\treturn normalized === 'utf8' || normalized === 'utf-8'\n\t}\n\n\t// Build the immutable, serializable captured chunk from already-decoded text, stamp it with the\n\t// capture instant, buffer it (total + per-stream, bounded), emit `capture`, then forward it to the\n\t// sink. Frozen so a consumer (or the `capture` listener) can never mutate it. Never throws into the\n\t// patched stream — the sink is a best-effort tee and the emitter isolates a listener throw.\n\t#record(level: StreamLevel, text: string): void {\n\t\tconst message: CapturedChunk = Object.freeze({ level, text, time: Date.now() })\n\t\tthis.#retention.add(message)\n\t\tthis.#emitter.emit('capture', message)\n\t\tif (this.#sink !== undefined) {\n\t\t\ttry {\n\t\t\t\tthis.#sink.write(message.text, STREAM_LEVEL_MAP[level])\n\t\t\t} catch {\n\t\t\t\t// The sink is a best-effort tee; the wrapper never throws into the patched global stream —\n\t\t\t\t// a broken/throwing sink must not crash the host's process.stdout / process.stderr write.\n\t\t\t}\n\t\t}\n\t}\n\n\t// Drain each streaming decoder's trailing partial codepoint once — `decoder.end()` emits the\n\t// pending bytes' final text (U+FFFD for a genuinely truncated sequence) — so a codepoint left\n\t// half-written at stop is recorded, not silently dropped. An empty flush adds no record. Clears\n\t// the decoders so the next start() begins clean.\n\t#flush(): void {\n\t\tfor (const [level, decoder] of this.#decoders) {\n\t\t\tconst text = decoder.end()\n\t\t\tif (text !== '') this.#record(level, text)\n\t\t}\n\t\tthis.#decoders.clear()\n\t}\n}\n","import type { LogLevel } from '@src/core'\nimport type { ServerSinkInterface, ServerSinkOptions } from './types.js'\nimport { isNumber } from '@orkestrel/contract'\nimport { selectWriter, strip, stripControls } from '@src/core'\nimport { inferColumns, inferStyled } from './helpers.js'\nimport { isStreamTarget } from './validators.js'\n\n/**\n * Creates the server TTY {@link ServerSinkInterface} — the server output backend, whose\n * `write(text, level?)` routes by level to the process streams and uses construction-time styled\n * facts: it sends ANSI straight to a styled target (with a leading `\\r` overwriting a terminal\n * line natively) but {@link import('@src/core').strip}s ANSI to clean text for a plain target.\n *\n * @param options - See {@link ServerSinkOptions}\n * @returns A {@link ServerSinkInterface} — a {@link import('@src/core').SinkInterface} that also\n * exposes the terminal `columns` width\n *\n * @remarks\n * - **Routes by level.** `error` / `warn` → the error stream (`process.stderr` by default), every\n * other level (and an omitted level) → the `stdout` stream (`process.stdout`) — the same routing\n * as core's `createConsoleSink`, so a logger's `error` reaches `stderr`. Both call the one\n * {@link import('@src/core').selectWriter} leaf, which is what keeps them identical.\n * - **Per-target styled facts.** At construction, each target uses `options.styled` when supplied;\n * otherwise {@link inferStyled} applies the injected `environment` (default `process.env`) and\n * then that target's `isTTY`.\n * Writes use those stored facts, so `styled` and the `stdout` target's strip decision never\n * disagree; the `stderr` target keeps its own fact internally.\n * - **Width.** `columns` reflects the live `stdout.columns` (so it tracks a terminal resize),\n * falling back to {@link import('./constants.js').DEFAULT_COLUMNS} when the `stdout` stream is not\n * a TTY — or a fixed value when `options.columns` is supplied. Feed it to a `Reporter` /\n * `Progress` `width`.\n * - **Injectable + guard-narrowed.** `options.stdout` / `options.stderr` default to `process.stdout`\n * / `process.stderr` but accept any {@link import('./types.js').StreamTargetInterface}, resolved\n * through {@link isStreamTarget} (narrow the boundary, never `as`), so a test drives\n * the sink (and the isTTY-strip path) with a fake stream that never touches the real process\n * streams.\n *\n * @example The server — a TTY sink and a process capture\n * ```ts\n * import { createStyler, Logger, Reporter } from '@orkestrel/console'\n * import { createServerSink, ProcessCapture } from '@orkestrel/console/server'\n *\n * const sink = createServerSink() // FORCE_COLOR, then NO_COLOR, then isTTY — per target, at construction\n * const styler = createStyler({ enabled: sink.styled }) // keep generated ANSI paired with the sink's stdout stripping\n * const logger = new Logger({ name: 'server', sink, styler })\n * logger.error('boom') // → process.stderr (the error stream)\n * const reporter = new Reporter({ sink, width: sink.columns }) // size the layout to the live terminal\n *\n * // `styled` overrides the inference outright — for a CI log that renders ANSI off a TTY, say.\n * const forced = createServerSink({ styled: true })\n * forced.styled // true, whatever the environment and the streams say\n *\n * // Own every output path — a direct process.stdout.write, library output, child-process pipes:\n * const capture = new ProcessCapture({ levels: ['stderr'], mirror: true })\n * capture.start()\n * process.stderr.write('a library diagnostic\\n') // captured and still shown (mirror: true)\n * capture.messages('stderr') // [{ level: 'stderr', text: 'a library diagnostic\\n', time: … }]\n * capture.clear() // drop buffered chunks; interception is unaffected\n * capture.stop()\n * capture.destroy() // stop() then tear down the emitter\n * ```\n */\nexport function createServerSink(options?: ServerSinkOptions): ServerSinkInterface {\n\t// Resolve each target through the guard: a present, well-shaped injected stream is used as\n\t// is; otherwise the real process stream — no `as`, and an `undefined` option falls through to the\n\t// default. `stdout` carries info/debug, `stderr` carries error/warn.\n\tconst out = isStreamTarget(options?.stdout) ? options.stdout : process.stdout\n\tconst err = isStreamTarget(options?.stderr) ? options.stderr : process.stderr\n\tconst styled = options?.styled\n\tconst environment = options?.environment ?? process.env\n\tconst outStyled = styled ?? inferStyled(out, environment)\n\tconst errStyled = styled ?? inferStyled(err, environment)\n\tconst fixed = options?.columns\n\treturn Object.freeze({\n\t\tstyled: outStyled,\n\t\twrite(text: string, level?: LogLevel): void {\n\t\t\t// The one shared routing leaf picks the target and its styled fact together; `warn` shares\n\t\t\t// the error stream here, matching `console.warn` writing to stderr in core.\n\t\t\tconst target = selectWriter(level, { log: out, warn: err, error: err })\n\t\t\tconst keep = selectWriter(level, { log: outStyled, warn: errStyled, error: errStyled })\n\t\t\t// A leading `\\r` marks an in-place redraw frame (Spinner/Progress), which carries its own\n\t\t\t// line endings and is written verbatim; every other (line-oriented) write gets exactly one\n\t\t\t// trailing `\\n` appended here, matching `console.log`'s newline-terminated behavior.\n\t\t\tconst framed = text.startsWith('\\r')\n\t\t\tconst line = framed ? text : `${text}\\n`\n\t\t\t// A styled target receives the line verbatim; a plain target receives visible text only.\n\t\t\ttarget.write(keep ? line : stripControls(strip(line)))\n\t\t},\n\t\tget columns(): number {\n\t\t\t// A fixed override wins; otherwise the live stdout-stream width (tracks a resize), with the\n\t\t\t// non-TTY fallback inside inferColumns.\n\t\t\treturn isNumber(fixed) ? fixed : inferColumns(out)\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;;AAYA,IAAa,gBAAwC,OAAO,OAAO,CAAC,UAAU,QAAQ,CAAC;;;;;;;;;;;AAYvF,IAAa,uBAAuB;;;;;;;AAQpC,IAAa,kBAAkB;;;;;;;;;AAU/B,IAAa,mBAA4D,OAAO,OAAO;CACtF,QAAQ;CACR,QAAQ;AACT,CAAC;;;;;;;;;;;;;;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