@holz/json-backend 0.9.2-rc.59.sha-3abcf4b → 0.9.2-rc.60.sha-9c2a088

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 CHANGED
@@ -20,30 +20,28 @@ Logs are output in [NDJSON](https://github.com/ndjson/ndjson-spec) format. The o
20
20
 
21
21
  The `stream` option specifies where the logs will be written to. You can use any writable stream, such as a file or `process.stdout`.
22
22
 
23
- ## Log Rotation
23
+ ## Changes to `Log`
24
24
 
25
- Long-lived processes or noisy services can fill up the disk, given enough time.
26
-
27
- Lean on your environment's tools (`journalctl`) or use a package like [rotating-file-stream](https://github.com/iccicci/rotating-file-stream) to prevent files from growing unbounded.
25
+ This plugin converts a few fields to make the JSON representation useful and readable:
28
26
 
29
- ## Custom Destinations
27
+ - `log.level`: Replaced with a string mirroring its key in [level](https://github.com/PsychoLlama/holz/tree/main/packages/holz-core#log-levels).
28
+ - `log.timestamp`: Converted to an ISO 8601 date string.
29
+ - `log.context.error`: Serialized as plain values, with recursive handling for nested [cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) and [errors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError/errors).
30
30
 
31
- The default backend assumes a NodeJS environment. For other envs, use the JSON serializer exported from `/serialize`.
31
+ Conversion tools are exported separately and can be used in other environments outside NodeJS.
32
32
 
33
33
  ```ts
34
- import serialize from '@holz/json-backend/serialize';
34
+ import { toJSON, errorToJSON } from '@holz/json-backend/marshal';
35
35
 
36
- // Stream logs as NDJSON.
37
- const jsonStream = new ReadableStream<Uint8Array>({
38
- async start(controller) {
39
- const encoder = new TextEncoder();
36
+ // Convert a log to a JSON-suitable object.
37
+ JSON.stringify(toJSON(log));
40
38
 
41
- for await (const log of readLogStream()) {
42
- const encoded = encoder.encode(`${serialize(log)}\n`);
43
- controller.enqueue(encoded);
44
- }
45
-
46
- controller.close();
47
- },
48
- });
39
+ // Convert an error on its own, for errors outside `context.error`.
40
+ errorToJSON(new Error('Boom', { cause: new Error('Root cause') }));
49
41
  ```
42
+
43
+ ## Rotation and Compression
44
+
45
+ Long-lived processes or noisy services can fill up the disk, given enough time.
46
+
47
+ Lean on your environment's tools (`journalctl`) or use a package like [rotating-file-stream](https://github.com/iccicci/rotating-file-stream) to prevent files from growing unbounded.
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./serialize-68-JE9vM.cjs");var t=({stream:t})=>n=>{t.write(`${e.t(n)}\n`)};exports.createJsonBackend=t;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./marshal-Dq-F5gZZ.cjs");var t=({stream:t})=>n=>{t.write(`${JSON.stringify(e.n(n))}\n`)};exports.createJsonBackend=t;
@@ -1,6 +1,6 @@
1
- import { t as e } from "./serialize-Bc_zRhA0.js";
1
+ import { n as e } from "./marshal-nT1onzi1.js";
2
2
  // src/json-backend.ts
3
3
  var t = ({ stream: t }) => (n) => {
4
- t.write(`${e(n)}\n`);
4
+ t.write(`${JSON.stringify(e(n))}\n`);
5
5
  };
6
6
  export { t as createJsonBackend };
@@ -0,0 +1 @@
1
+ let e=require("@holz/core");var t=e=>({level:a[e.level],timestamp:new Date(e.timestamp).toISOString(),message:e.message,origin:e.origin,context:i(e.context)}),n=e=>({...e,name:e.name,message:e.message,cause:r(e.cause),errors:r(e.errors),stack:e.stack}),r=e=>e instanceof Error?n(e):Array.isArray(e)?e.map(r):e,i=e=>({...e,error:r(e.error)}),a=Object.fromEntries(Object.entries(e.level).map(([e,t])=>[t,e]));Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return n}});
@@ -0,0 +1,20 @@
1
+ import { level as e } from "@holz/core";
2
+ // src/marshal/marshal.ts
3
+ var t = (e) => ({
4
+ level: a[e.level],
5
+ timestamp: new Date(e.timestamp).toISOString(),
6
+ message: e.message,
7
+ origin: e.origin,
8
+ context: i(e.context)
9
+ }), n = (e) => ({
10
+ ...e,
11
+ name: e.name,
12
+ message: e.message,
13
+ cause: r(e.cause),
14
+ errors: r(e.errors),
15
+ stack: e.stack
16
+ }), r = (e) => e instanceof Error ? n(e) : Array.isArray(e) ? e.map(r) : e, i = (e) => ({
17
+ ...e,
18
+ error: r(e.error)
19
+ }), a = Object.fromEntries(Object.entries(e).map(([e, t]) => [t, e]));
20
+ export { t as n, n as t };
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./marshal-Dq-F5gZZ.cjs");exports.errorToJSON=e.t,exports.toJSON=e.n;
@@ -0,0 +1,20 @@
1
+ import { Log } from '@holz/core';
2
+
3
+ /**
4
+ * Best-effort attempt at converting `Error` instances to serializable JSON.
5
+ *
6
+ * These are among the most important logs, but the default behavior produces
7
+ * an empty object.
8
+ *
9
+ * This is NOT a lossless conversion. Values are too dynamic, especially
10
+ * considering custom errors. But it should handle the vast majority.
11
+ */
12
+ export declare const errorToJSON: (error: Error) => Record<string, unknown>;
13
+
14
+ /**
15
+ * Converts a log to a JSON-serializable object.
16
+ * Keys ordered to make visually skimming a log file easier.
17
+ */
18
+ export declare const toJSON: (log: Log) => Record<string, unknown>;
19
+
20
+ export { }
@@ -0,0 +1 @@
1
+ export { t as errorToJSON, n as toJSON } from "./marshal-nT1onzi1.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holz/json-backend",
3
- "version": "0.9.2-rc.59.sha-3abcf4b",
3
+ "version": "0.9.2-rc.60.sha-9c2a088",
4
4
  "description": "Print logs as newline-delimited JSON.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -15,11 +15,11 @@
15
15
  "require": "./dist/holz-json-backend.cjs",
16
16
  "import": "./dist/holz-json-backend.js"
17
17
  },
18
- "./serialize": {
19
- "source": "./src/serialize/index.ts",
20
- "types": "./dist/serialize.d.ts",
21
- "require": "./dist/serialize.cjs",
22
- "import": "./dist/serialize.js"
18
+ "./marshal": {
19
+ "source": "./src/marshal/index.ts",
20
+ "types": "./dist/marshal.d.ts",
21
+ "require": "./dist/marshal.cjs",
22
+ "import": "./dist/marshal.js"
23
23
  }
24
24
  },
25
25
  "publishConfig": {
@@ -49,7 +49,7 @@
49
49
  "@holz/core": "^0.9.0"
50
50
  },
51
51
  "devDependencies": {
52
- "@holz/core": "^0.9.2-rc.59.sha-3abcf4b",
52
+ "@holz/core": "^0.9.2-rc.60.sha-9c2a088",
53
53
  "@microsoft/api-extractor": "^7.58.8",
54
54
  "@types/node": "^26.0.0",
55
55
  "@vitest/coverage-v8": "^5.0.0",
@@ -59,5 +59,5 @@
59
59
  "vite-tsconfig-paths": "^6.0.0",
60
60
  "vitest": "^5.0.0"
61
61
  },
62
- "gitHead": "3abcf4bdde93448d03c4d0d8d9d937710db7de54"
62
+ "gitHead": "9c2a0885dda76cf5734dd4861809caa6754ef100"
63
63
  }
@@ -1,6 +1,6 @@
1
1
  import type { Writable } from 'node:stream';
2
2
  import type { Log, LogProcessor } from '@holz/core';
3
- import serialize from './serialize';
3
+ import { toJSON } from './marshal';
4
4
 
5
5
  /**
6
6
  * Prints structured logs to a writable stream in NDJSON form. Optimized for
@@ -21,7 +21,7 @@ export const createJsonBackend = ({ stream }: Config): LogProcessor => {
21
21
  // crashing the process.
22
22
  //
23
23
  // It is unlikely that a file or tty will apply backpressure in practice.
24
- stream.write(`${serialize(log)}\n`);
24
+ stream.write(`${JSON.stringify(toJSON(log))}\n`);
25
25
  };
26
26
  };
27
27
 
@@ -0,0 +1 @@
1
+ export { toJSON, errorToJSON } from './marshal';
@@ -0,0 +1,84 @@
1
+ import { level, type LogLevel, type Log, type LogContext } from '@holz/core';
2
+
3
+ /**
4
+ * Converts a log to a JSON-serializable object.
5
+ * Keys ordered to make visually skimming a log file easier.
6
+ */
7
+ export const toJSON = (log: Log): Record<string, unknown> => {
8
+ return {
9
+ // Convert the numeric level to a label. Lossless, as keys map back to
10
+ // `level`. Improves readability and use with tools like `jq`.
11
+ level: labelForLevel[log.level],
12
+
13
+ // Converted purely for human readability. `jq` doesn't have millis-level
14
+ // date precision, so optimizing for tools is somewhat moot.
15
+ timestamp: new Date(log.timestamp).toISOString(),
16
+
17
+ // No changes needed here.
18
+ message: log.message,
19
+ origin: log.origin,
20
+
21
+ // Everything in context is meant to be JSON-serializable with the
22
+ // exception (heh) of errors. Attempt a naive conversion.
23
+ context: contextToJSON(log.context),
24
+ };
25
+ };
26
+
27
+ /**
28
+ * Best-effort attempt at converting `Error` instances to serializable JSON.
29
+ *
30
+ * These are among the most important logs, but the default behavior produces
31
+ * an empty object.
32
+ *
33
+ * This is NOT a lossless conversion. Values are too dynamic, especially
34
+ * considering custom errors. But it should handle the vast majority.
35
+ */
36
+ export const errorToJSON = (error: Error): Record<string, unknown> => ({
37
+ ...error, // Some custom errors have important custom properties.
38
+
39
+ name: error.name,
40
+ message: error.message,
41
+ cause: errorFieldToJSON(error.cause),
42
+
43
+ // Special case for `AggregateError` which carries a list of errors. Well,
44
+ // we hope they're errors. It's not like JS enforces it.
45
+ errors: errorFieldToJSON((error as AggregateError).errors),
46
+
47
+ // Invaluable when needed, but costly in terms of noise.
48
+ stack: error.stack,
49
+ });
50
+
51
+ const errorFieldToJSON = (value: unknown): unknown => {
52
+ // Example: `Error(...).cause`
53
+ if (value instanceof Error) {
54
+ return errorToJSON(value);
55
+ }
56
+
57
+ // Example: `AggregateError(...).errors`
58
+ if (Array.isArray(value)) {
59
+ return value.map(errorFieldToJSON);
60
+ }
61
+
62
+ // Pass through unremarked.
63
+ return value;
64
+ };
65
+
66
+ /**
67
+ * Types require `context.error` to be an `Error` instance. Everything else is
68
+ * restricted to JSON values.
69
+ *
70
+ * `errorToJSON` is exported as an escape hatch. Internally, we only handle
71
+ * `context.error`. Consumers with more advanced cases have to eject.
72
+ */
73
+ const contextToJSON = (context: LogContext) => ({
74
+ ...context,
75
+ error: errorFieldToJSON(context.error),
76
+ });
77
+
78
+ /**
79
+ * Slightly heavier than logging the number, but easier to process
80
+ * programmatically which is somewhat implied by a JSON backend.
81
+ */
82
+ const labelForLevel = Object.fromEntries(
83
+ Object.entries(level).map(([key, value]) => [value, key]),
84
+ ) as Record<LogLevel, string>;
@@ -1 +0,0 @@
1
- let e=require("@holz/core");var t=e=>JSON.stringify({level:a[e.level],time:new Date(e.timestamp).toISOString(),msg:e.message,origin:e.origin,ctx:Object.keys(e.context).length>0?n(e.context):void 0}),n=e=>e.error instanceof Error?{...e,error:r(e.error)}:e,r=e=>({...e,name:e.name,message:e.message,cause:i(e.cause),...e instanceof AggregateError&&{errors:e.errors.map(i)}}),i=e=>e instanceof Error?r(e):e,a=Object.fromEntries(Object.entries(e.level).map(([e,t])=>[t,e]));Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return t}});
@@ -1,19 +0,0 @@
1
- import { level as e } from "@holz/core";
2
- // src/serialize/serialize.ts
3
- var t = (e) => JSON.stringify({
4
- level: a[e.level],
5
- time: new Date(e.timestamp).toISOString(),
6
- msg: e.message,
7
- origin: e.origin,
8
- ctx: Object.keys(e.context).length > 0 ? n(e.context) : void 0
9
- }), n = (e) => e.error instanceof Error ? {
10
- ...e,
11
- error: r(e.error)
12
- } : e, r = (e) => ({
13
- ...e,
14
- name: e.name,
15
- message: e.message,
16
- cause: i(e.cause),
17
- ...e instanceof AggregateError && { errors: e.errors.map(i) }
18
- }), i = (e) => e instanceof Error ? r(e) : e, a = Object.fromEntries(Object.entries(e).map(([e, t]) => [t, e]));
19
- export { t };
@@ -1 +0,0 @@
1
- Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=require("./serialize-68-JE9vM.cjs");exports.default=e.t;
@@ -1,9 +0,0 @@
1
- import { Log } from '@holz/core';
2
-
3
- /**
4
- * Serializes a log as a single line of JSON (without the trailing newline).
5
- */
6
- declare const serialize: (log: Log) => string;
7
- export default serialize;
8
-
9
- export { }
package/dist/serialize.js DELETED
@@ -1 +0,0 @@
1
- export { t as default } from "./serialize-Bc_zRhA0.js";
@@ -1 +0,0 @@
1
- export { serialize as default } from './serialize';
@@ -1,56 +0,0 @@
1
- import { level, type LogLevel, type Log, type LogContext } from '@holz/core';
2
-
3
- /**
4
- * Serializes a log as a single line of JSON (without the trailing newline).
5
- */
6
- export const serialize = (log: Log): string => {
7
- // Follow the order of typical log statements. Be kind to the human
8
- // reader.
9
- return JSON.stringify({
10
- level: labelForLevel[log.level],
11
- time: new Date(log.timestamp).toISOString(),
12
- msg: log.message,
13
- origin: log.origin,
14
- ctx:
15
- Object.keys(log.context).length > 0
16
- ? serializeContext(log.context)
17
- : undefined,
18
- });
19
- };
20
-
21
- /**
22
- * Errors are not JSON serializable, but errors are naturally a crucial aspect
23
- * of any logging system. Only `context.error` is treated as one (per
24
- * `CustomContext`); errors anywhere else are left to `JSON.stringify`.
25
- */
26
- const serializeContext = (context: LogContext) => {
27
- if (context.error instanceof Error) {
28
- return { ...context, error: serializeError(context.error) };
29
- }
30
-
31
- return context;
32
- };
33
-
34
- /** Unwraps an error, its cause chain, and any aggregated errors. */
35
- const serializeError = (error: Error): Record<string, unknown> => ({
36
- ...error, // Some custom errors have important custom properties.
37
- name: error.name,
38
- message: error.message,
39
- cause: unwrap(error.cause),
40
-
41
- // `AggregateError` collects its constituent failures in a non-enumerable
42
- // `errors` array that the spread above misses. Pull it explicitly so those
43
- // underlying errors survive serialization.
44
- ...(error instanceof AggregateError && { errors: error.errors.map(unwrap) }),
45
- });
46
-
47
- const unwrap = (value: unknown) =>
48
- value instanceof Error ? serializeError(value) : value;
49
-
50
- /**
51
- * Slightly heavier than logging the number, but easier to process
52
- * programmatically which is somewhat implied by a JSON backend.
53
- */
54
- const labelForLevel = Object.fromEntries(
55
- Object.entries(level).map(([key, value]) => [value, key]),
56
- ) as Record<LogLevel, string>;