@sincpro/client-framework 1.7.0 → 1.9.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.
package/AGENTS.md CHANGED
@@ -217,8 +217,10 @@ options)`: no route, no verb, no RPC method. The contract's bindings (`rest`, `r
217
217
  - **The application layer imports no logger.** A bounded context has `projectBoundedContext.logger`; a run
218
218
  hands `this.logger`, bound to its execution. Only `logger` (infrastructure, the global one) and
219
219
  `loggerAdapter` are predefined; injected as a dependency they bind to the run (`BIND`), imported
220
- at module level they do not. No logger is predefined for an application layer. Console is the
221
- default engine; `configureProcess({ logger })` and `configureLogger(...)` take the same
220
+ at module level they do not. No logger is predefined for an application layer. Which INFO and
221
+ DEBUG lines speak is a `LogFilter` (level, layer, bounded context — `speaks`), the same rule
222
+ for the console and any sink (`filteredLogger`); WARN and ERROR always speak, and spans are
223
+ never filtered. Console is the default engine; `configureProcess({ logger })` and `configureLogger(...)` take the same
222
224
  `LoggerConfiguration`. The host chooses production explicitly. Never log DTOs, results or the
223
225
  full session context automatically.
224
226
  - **A failure is described once, as sincpro_framework's failure line** (`PRD_03 §6`,
package/README.md CHANGED
@@ -568,15 +568,45 @@ configureLogger({ mode: "development", level: "info", layers: { adapter: false }
568
568
  configureLogger({ mode: "production" }); // the console, silent
569
569
  configureLogger({ engine: combineLoggers(consoleLogger({ mode }), lokiLogger) }); // other sinks
570
570
  configureLogger({ engine: false }); // no logs
571
+
572
+ // Which INFO and DEBUG lines speak — by level, layer and bounded context; WARN and ERROR always.
573
+ // Spans are never filtered: a quiet line still has its span.
574
+ const production = {
575
+ level: "info",
576
+ layers: { adapter: false },
577
+ boundedContexts: { common: false },
578
+ };
579
+ configureLogger({
580
+ engine: filteredLogger(combineLoggers(consoleSink, lokiSink), () =>
581
+ debugging ? {} : production,
582
+ ),
583
+ });
571
584
  ```
572
585
 
573
586
  The console is the default engine. In production it is silent; in development it prints
574
587
  everything, and `level` and `layers` hide only INFO/DEBUG. A supplied `engine` owns its own
575
588
  policy, and each sink of `combineLoggers` keeps its own — the console's silence never silences
576
589
  another. Every execution writes `execution.started` (DEBUG) and `execution.finished` with its
577
- outcome and duration (INFO, WARN when refused, ERROR when failed). No line carries a DTO, a
578
- result, an error body or the session's context unless the author writes it. Delivery, buffering
579
- and credentials (Loki, a phone's queue) are the platform's.
590
+ outcome and duration (INFO, also when refused or aborted; ERROR when failed). No line carries a
591
+ DTO, a result, an error body or the session's context unless the author writes it. Delivery,
592
+ buffering and credentials (Loki, a phone's queue) are the platform's.
593
+
594
+ In development each record is one line for a person — time, level, layer, use case, message, its
595
+ attributes as `key=value`, and the run's short id — never the record object after it:
596
+
597
+ ```text
598
+ 10:20:30.045 DEBUG [feature] ▶ shop.Pay #0193a1
599
+ 10:20:30.051 INFO [feature] shop.Pay Paying order=A-1 note="two words" #0193a1
600
+ 10:20:30.057 INFO [feature] ✔ shop.Pay 12ms #0193a1
601
+ 10:20:31.002 INFO [feature] ✖ shop.Pay refused: domain 3ms #0193b7
602
+ 10:20:32.118 ERROR [feature] ✖ shop.Pay TypeError: card is undefined 4ms #0193c2 + the Error, with its stack
603
+ ```
604
+
605
+ An unexpected failure also prints its `Error`, so LogBox, Expo's terminal and a browser show its
606
+ code frame. `consoleLogger({ mode, colors })` colors the lines of the levels named (`true`: every
607
+ one) with ANSI codes: the platform knows where its console renders them — a terminal does, React
608
+ Native's LogBox (WARN and ERROR in the app) does not. `prettyLine(record)` is the same line, for a
609
+ sink of one's own.
580
610
 
581
611
  ## Context
582
612
 
@@ -1,8 +1,27 @@
1
- import type { Logger, LogLayer, LogLevel } from "../domain/logging.js";
2
- export type ConsoleLoggerOptions = {
3
- mode: "development" | "production";
4
- /** Development INFO/DEBUG threshold. WARN/ERROR are never hidden by layer/level masks. */
5
- level?: LogLevel;
6
- layers?: Partial<Record<LogLayer, boolean>>;
1
+ import { type LogFilter, type Logger, type LogLevel, type LogRecord } from "../domain/logging.js";
2
+ /**
3
+ * Context: a development console is read by a person, a line at a glance. Each record is ONE
4
+ * line — its time, its level, its layer and use case, its message and the keys worth reading —,
5
+ * never the record object dumped after it, and a run's start and end read as `▶` / `✔` / `✖`.
6
+ * An unexpected failure still goes as an `Error` with its stack, because that is what React
7
+ * Native's LogBox, Expo's terminal and a browser print with a code frame. Production is silent.
8
+ *
9
+ * Colors are ANSI escape codes, and only the platform knows where its console renders them: a
10
+ * terminal and a browser's devtools do; React Native's LogBox, which shows WARN and ERROR in the
11
+ * app, prints them as text. So the platform names the levels to color (`colors`), and the line
12
+ * reads the same without them.
13
+ */
14
+ /** The console's mode, which INFO and DEBUG lines it prints (`LogFilter`), and their colors. */
15
+ export type ConsoleLoggerOptions = LogFilter & {
16
+ readonly mode: "development" | "production";
17
+ /** The levels whose lines get ANSI colors: `true` every one, none unless said. */
18
+ readonly colors?: boolean | readonly LogLevel[];
7
19
  };
20
+ /** One line for a person: time, level, layer, what happened, its keys, the run. */
21
+ export declare function prettyLine(record: LogRecord, colored?: boolean): string;
22
+ /**
23
+ * Built-in console engine: one readable line per record in development, silent in production;
24
+ * which INFO and DEBUG lines it prints is its own filter, WARN and ERROR always. Other sinks are
25
+ * filtered independently.
26
+ */
8
27
  export declare function consoleLogger(options: ConsoleLoggerOptions): Logger;
@@ -1,8 +1,83 @@
1
- const RANK = { debug: 0, info: 1, warn: 2, error: 3 };
1
+ import { isLogLevel, speaks, } from "../domain/logging.js";
2
+ const LABELS = {
3
+ debug: "DEBUG",
4
+ info: "INFO ",
5
+ warn: "WARN ",
6
+ error: "ERROR",
7
+ };
8
+ const LEVEL_COLORS = {
9
+ debug: "90",
10
+ info: "36",
11
+ warn: "33",
12
+ error: "31",
13
+ };
14
+ /** Past this, a value is cut: a line is read, not scrolled. */
15
+ const MAX_VALUE = 160;
16
+ /** How much of a run's id a line shows: enough to tell two runs apart. */
17
+ const SHORT_ID = 6;
18
+ const painted = (code, text) => `\u001b[${code}m${text}\u001b[0m`;
19
+ const plain = (_code, text) => text;
20
+ function pad(value, width = 2) {
21
+ return String(value).padStart(width, "0");
22
+ }
23
+ /** `HH:mm:ss.SSS` on the device's clock; the record's own text when it is not an instant. */
24
+ function timeOf(timestamp) {
25
+ const at = new Date(timestamp);
26
+ if (Number.isNaN(at.getTime()))
27
+ return timestamp;
28
+ return `${pad(at.getHours())}:${pad(at.getMinutes())}:${pad(at.getSeconds())}.${pad(at.getMilliseconds(), 3)}`;
29
+ }
30
+ /** `key=value`, the value quoted when it would not read as one word, and cut when long. */
31
+ function keyValue(key, value) {
32
+ const text = String(value);
33
+ const cut = text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}…` : text;
34
+ return `${key}=${/^[^\s"=]+$/.test(cut) ? cut : JSON.stringify(cut)}`;
35
+ }
2
36
  /**
3
- * Built-in console engine: silent in production, configurable
4
- * development layers, and WARN/ERROR preserved. Other sinks are filtered independently.
37
+ * What the line says after its level and layer:
38
+ *
39
+ * ▶ common.PrintImage a run starts
40
+ * ✔ common.PrintImage 12ms it answered
41
+ * ✖ common.PrintImage TypeError: printer is undefined 8ms it failed
42
+ * ✖ common.ConnectPrinter refused: unavailable 8ms it was refused, or the caller left
43
+ * common.PrintImage Printing page=2 a line its use case wrote
5
44
  */
45
+ function saying(record, paint) {
46
+ const where = record.useCase ? paint("1", record.useCase) : "";
47
+ const took = record.durationMs === undefined ? "" : ` ${Math.round(record.durationMs)}ms`;
48
+ if (record.event === "execution.started")
49
+ return `${paint("34", "▶")} ${where}`;
50
+ if (record.event === "execution.finished") {
51
+ if (record.outcome === "ok")
52
+ return `${paint("32", "✔")} ${where}${took}`;
53
+ const failure = record.failure;
54
+ const why = record.outcome === "failed"
55
+ ? failure?.message
56
+ ? `${failure.type}: ${failure.message}`
57
+ : (failure?.type ?? "failed")
58
+ : `${record.outcome}${failure?.kind ? `: ${failure.kind}` : ""}`;
59
+ return `${paint("31", "✖")} ${where} ${why}${took}`;
60
+ }
61
+ return where ? `${where} ${record.message}` : record.message;
62
+ }
63
+ /** One line for a person: time, level, layer, what happened, its keys, the run. */
64
+ export function prettyLine(record, colored = false) {
65
+ const paint = colored ? painted : plain;
66
+ const keys = Object.entries(record.attributes ?? {}).map(([key, value]) => keyValue(key, value));
67
+ const run = record.executionId
68
+ ? ` ${paint("2", `#${record.executionId.slice(0, SHORT_ID)}`)}`
69
+ : "";
70
+ return [
71
+ paint("2", timeOf(record.timestamp)),
72
+ paint(LEVEL_COLORS[record.level], LABELS[record.level]),
73
+ paint("2", `[${record.layer}]`),
74
+ saying(record, paint),
75
+ ...keys,
76
+ ]
77
+ .filter((part) => part !== "")
78
+ .join(" ")
79
+ .concat(run);
80
+ }
6
81
  /** The failure as an Error to print: its type as its name, its message, its stack. */
7
82
  function errorOf(stack, failure) {
8
83
  const shown = new Error(failure.message ?? failure.type ?? "");
@@ -10,42 +85,57 @@ function errorOf(stack, failure) {
10
85
  shown.stack = stack;
11
86
  return shown;
12
87
  }
88
+ function methodOf(level) {
89
+ if (level === "debug")
90
+ return console.debug;
91
+ if (level === "warn")
92
+ return console.warn;
93
+ if (level === "error")
94
+ return console.error;
95
+ return console.log;
96
+ }
97
+ /**
98
+ * Built-in console engine: one readable line per record in development, silent in production;
99
+ * which INFO and DEBUG lines it prints is its own filter, WARN and ERROR always. Other sinks are
100
+ * filtered independently.
101
+ */
13
102
  export function consoleLogger(options) {
14
103
  const mode = options.mode;
15
104
  if (mode !== "development" && mode !== "production") {
16
105
  throw new TypeError("Console logger mode must be development or production");
17
106
  }
18
- const level = options.level ?? "debug";
19
- if (!Object.hasOwn(RANK, level)) {
107
+ if (options.level !== undefined && !isLogLevel(options.level)) {
20
108
  throw new TypeError("Console logger level must be debug, info, warn or error");
21
109
  }
22
- const layers = { ...options.layers };
110
+ const colors = options.colors ?? false;
111
+ if (Array.isArray(colors) && !colors.every(isLogLevel)) {
112
+ throw new TypeError("Console logger colors must be true, false or log levels");
113
+ }
114
+ const colored = (level) => colors === true || (Array.isArray(colors) && colors.includes(level));
115
+ const filter = {
116
+ level: options.level ?? "debug",
117
+ layers: { ...options.layers },
118
+ boundedContexts: { ...options.boundedContexts },
119
+ };
23
120
  return {
24
121
  log(record) {
25
- if (mode === "production")
122
+ if (mode === "production" || !speaks(record, filter))
26
123
  return;
27
- if (record.level !== "warn" && record.level !== "error") {
28
- if (layers[record.layer] === false || RANK[record.level] < RANK[level])
29
- return;
124
+ const method = methodOf(record.level);
125
+ let line;
126
+ try {
127
+ line = prettyLine(record, colored(record.level));
30
128
  }
31
- const prefix = `${record.timestamp} [${record.layer}] ${record.level.toUpperCase()}`;
32
- const method = record.level === "debug"
33
- ? console.debug
34
- : record.level === "warn"
35
- ? console.warn
36
- : record.level === "error"
37
- ? console.error
38
- : console.log;
39
- const stack = record.failure?.stack;
40
- if (!stack) {
41
- method.call(console, prefix, record.message, record);
42
- return;
129
+ catch {
130
+ line = `${LABELS[record.level]} [${record.layer}] ${record.message}`;
43
131
  }
132
+ const stack = record.failure?.stack;
44
133
  // An unexpected failure goes as an Error — its name, its message, its stack —: what React
45
134
  // Native's LogBox, Expo's terminal and a browser print as a failure, with its code frame.
46
- // A bare stack string read as one printed `ERROR null null`.
47
- const { stack: _shownBelow, ...failure } = record.failure ?? {};
48
- method.call(console, `${prefix} ${record.message}`, { ...record, failure }, errorOf(stack, failure));
135
+ if (stack)
136
+ method.call(console, line, errorOf(stack, record.failure ?? {}));
137
+ else
138
+ method.call(console, line);
49
139
  },
50
140
  };
51
141
  }
@@ -71,3 +71,30 @@ export interface LayerLogger {
71
71
  warn(message: string, attributes?: Attributes): void;
72
72
  error(message: string, attributes?: Attributes): void;
73
73
  }
74
+ /**
75
+ * Which INFO and DEBUG lines speak — by level, by layer and by bounded context. WARN and ERROR
76
+ * always do: a failure is never silenced. What a filter does not name speaks.
77
+ *
78
+ * { level: "info", layers: { adapter: false }, boundedContexts: { common: false } }
79
+ *
80
+ * Context: only lines are filtered, never spans — a quiet line still has its span, so a trace
81
+ * shows every run. A line outside a run (the infrastructure's `logger`) has no bounded context
82
+ * and is filtered by its layer alone.
83
+ */
84
+ export type LogFilter = {
85
+ /** The lowest level of INFO and DEBUG that speaks (`debug`: every one). */
86
+ readonly level?: LogLevel;
87
+ /** By layer: `false` keeps a layer's INFO and DEBUG quiet. */
88
+ readonly layers?: Readonly<Partial<Record<LogLayer, boolean>>>;
89
+ /** By bounded context's name: `false` keeps its INFO and DEBUG quiet. */
90
+ readonly boundedContexts?: Readonly<Record<string, boolean>>;
91
+ };
92
+ /** Whether `level` is one a line can have. */
93
+ export declare function isLogLevel(level: unknown): level is LogLevel;
94
+ /**
95
+ * Whether `record` speaks under `filter`:
96
+ * 1. WARN and ERROR, always.
97
+ * 2. INFO and DEBUG at the filter's level or above, from a layer and a bounded context it does
98
+ * not keep quiet.
99
+ */
100
+ export declare function speaks(record: LogRecord, filter: LogFilter): boolean;
@@ -1 +1,21 @@
1
- export {};
1
+ const RANK = { debug: 0, info: 1, warn: 2, error: 3 };
2
+ /** Whether `level` is one a line can have. */
3
+ export function isLogLevel(level) {
4
+ return typeof level === "string" && Object.hasOwn(RANK, level);
5
+ }
6
+ /**
7
+ * Whether `record` speaks under `filter`:
8
+ * 1. WARN and ERROR, always.
9
+ * 2. INFO and DEBUG at the filter's level or above, from a layer and a bounded context it does
10
+ * not keep quiet.
11
+ */
12
+ export function speaks(record, filter) {
13
+ if (record.level === "warn" || record.level === "error")
14
+ return true;
15
+ if (RANK[record.level] < RANK[filter.level ?? "debug"])
16
+ return false;
17
+ if (filter.layers?.[record.layer] === false)
18
+ return false;
19
+ const boundedContext = record.boundedContext;
20
+ return !(boundedContext !== undefined && filter.boundedContexts?.[boundedContext] === false);
21
+ }
@@ -10,9 +10,9 @@
10
10
  */
11
11
  export type { ErrorAbout, ErrorReporter, } from "./domain/errors.js";
12
12
  export { type IdentityKeys, identityOf, type ProcessIdentity, RELEASE, TENANT, tenantOf, USER_ID, userOf, } from "./domain/identity.js";
13
- export type { FailureDescription, LayerLogger, Logger, LogLayer, LogLevel, LogRecord, } from "./domain/logging.js";
13
+ export { type FailureDescription, isLogLevel, type LayerLogger, type LogFilter, type Logger, type LogLayer, type LogLevel, type LogRecord, speaks, } from "./domain/logging.js";
14
14
  export { type Attributes, NO_TRACER, type Outcome, type Span, type Tracer, } from "./domain/tracing.js";
15
15
  export { describeFailure } from "./services/failure.js";
16
- export { combineLoggers, logger, loggerAdapter, } from "./services/logging.js";
16
+ export { combineLoggers, filteredLogger, logger, loggerAdapter, } from "./services/logging.js";
17
17
  export { outcomeOf } from "./services/outcome.js";
18
18
  export { reportError } from "./services/reporting.js";
@@ -1,6 +1,7 @@
1
1
  export { identityOf, RELEASE, TENANT, tenantOf, USER_ID, userOf, } from "./domain/identity.js";
2
+ export { isLogLevel, speaks, } from "./domain/logging.js";
2
3
  export { NO_TRACER, } from "./domain/tracing.js";
3
4
  export { describeFailure } from "./services/failure.js";
4
- export { combineLoggers, logger, loggerAdapter, } from "./services/logging.js";
5
+ export { combineLoggers, filteredLogger, logger, loggerAdapter, } from "./services/logging.js";
5
6
  export { outcomeOf } from "./services/outcome.js";
6
7
  export { reportError } from "./services/reporting.js";
@@ -1,5 +1,5 @@
1
1
  import { type Execution } from "../../context/domain/execution.js";
2
- import type { FailureDescription, LayerLogger, Logger, LogLayer } from "../domain/logging.js";
2
+ import { type FailureDescription, type LayerLogger, type LogFilter, type Logger, type LogLayer } from "../domain/logging.js";
3
3
  import type { Outcome } from "../domain/tracing.js";
4
4
  /** The infrastructure's logger — the global one: the code that starts and holds the application. */
5
5
  export declare const logger: LayerLogger;
@@ -11,6 +11,13 @@ export declare function boundedContextLogger(name: string): LayerLogger;
11
11
  type RunLogLayer = Extract<LogLayer, "feature" | "application_service" | "event_handler">;
12
12
  /** @internal — what a Feature or ApplicationService finds as `this.logger` while it runs. */
13
13
  export declare function executionLogger(layer: RunLogLayer, execution: Execution): LayerLogger;
14
+ /**
15
+ * `engine`, hearing only the lines `filter` lets speak — WARN and ERROR always (`speaks`). A
16
+ * function is read on every line, so a debug switch changes what speaks without rebuilding:
17
+ *
18
+ * filteredLogger(combineLoggers(console, loki), () => (debugging ? everything : production))
19
+ */
20
+ export declare function filteredLogger(engine: Logger, filter: LogFilter | (() => LogFilter)): Logger;
14
21
  /** Each destination keeps its own policy; one failing sink does not hold back the others. */
15
22
  export declare function combineLoggers(...loggers: readonly Logger[]): Logger;
16
23
  /** @internal — lifecycle records contain correlation and outcome, never business payloads. */
@@ -1,5 +1,6 @@
1
1
  import { BIND } from "../../context/domain/execution.js";
2
2
  import { tenantOf, userOf } from "../domain/identity.js";
3
+ import { speaks, } from "../domain/logging.js";
3
4
  import { observabilityNow } from "../infrastructure/registry.js";
4
5
  const processSink = () => observabilityNow().logger;
5
6
  /** Sink failures cannot replace a business outcome or cause unhandled async rejections. */
@@ -77,6 +78,21 @@ export function boundedContextLogger(name) {
77
78
  export function executionLogger(layer, execution) {
78
79
  return layerLogger(layer, processSink, correlationOf(execution));
79
80
  }
81
+ /**
82
+ * `engine`, hearing only the lines `filter` lets speak — WARN and ERROR always (`speaks`). A
83
+ * function is read on every line, so a debug switch changes what speaks without rebuilding:
84
+ *
85
+ * filteredLogger(combineLoggers(console, loki), () => (debugging ? everything : production))
86
+ */
87
+ export function filteredLogger(engine, filter) {
88
+ const current = typeof filter === "function" ? filter : () => filter;
89
+ return {
90
+ log: (record) => {
91
+ if (speaks(record, current()))
92
+ deliver(engine, record);
93
+ },
94
+ };
95
+ }
80
96
  /** Each destination keeps its own policy; one failing sink does not hold back the others. */
81
97
  export function combineLoggers(...loggers) {
82
98
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sincpro/client-framework",
3
- "version": "1.7.0",
3
+ "version": "1.9.0",
4
4
  "description": "The client side of sincpro_framework, for every platform: Feature and ApplicationService traced and reported by default, applications made of domains, and the typed client generated from a service's contract. No React, no DOM.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",