@vllnt/logger 0.1.3-canary.90f2d33 → 0.1.3-canary.adb2d48

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/CHANGELOG.md ADDED
@@ -0,0 +1,70 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.3] - 2026-11-27
8
+
9
+ ### Added
10
+
11
+ - The npm package ships `docs/API.md` (every public export with an example), `llms.txt`,
12
+ `CHANGELOG.md` and the TypeScript sources in `src/`, so coding agents can read docs that match
13
+ the installed version from `node_modules/@vllnt/logger/`. `llms.txt` links the shipped files
14
+ with relative paths.
15
+ - README notes the bundled docs for coding agents and lists related packages.
16
+ - `package.json` sets `homepage` and `keywords`. Docs-only changes on `main` now publish a canary.
17
+
18
+ ### Fixed
19
+
20
+ - Log calls never throw. A throwing `getLogLevel`, output, or data getter is swallowed instead of
21
+ propagating into the host application; `withTiming` and `withTimingSync` always rethrow the
22
+ original error from the wrapped function.
23
+ - An invalid or throwing `getLogLevel` falls back to `info` instead of silently dropping every entry.
24
+ - `consoleOutput` keeps the entry when data holds a `BigInt` (written as a string), an `Error`
25
+ (written as `{ name, message, stack }`, previously `{}`) or a circular reference
26
+ (written as `"[Circular]"`). Only a throwing `toJSON` or getter still degrades to the minimal line.
27
+ - `consoleOutput` no longer throws when a `console` method throws.
28
+ - `createPostHogOutput` swallows rejected promises returned by `capture` instead of leaving an
29
+ unhandled rejection. `PostHogCapture` now accepts functions returning any value.
30
+ - `withTiming` logs a placeholder when a thrown value cannot be converted to a string.
31
+ - `docs/API.md`: the posthog-node wrapper now type-checks under `exactOptionalPropertyTypes`
32
+ (`(event, properties = {}) => client.capture({ distinctId, event, properties })`), and the
33
+ placeholder note names every placeholder. Tests type-check every example against the sources
34
+ and posthog-node, and check the entry-point table against the real exports.
35
+ - The publish workflow builds before it runs the tests, so the check of the built package files
36
+ runs before every publish instead of being skipped.
37
+
38
+ ### Changed
39
+
40
+ - `package.json` `exports` lists the `types` condition first so every resolver picks the typings.
41
+ - Publishing: stable releases come only from a pushed `vX.Y.Z` tag on `main` (npm trusted
42
+ publishing with provenance); canary builds still publish on every push to `main`. Actions are
43
+ pinned to commit SHAs, the workflow token is read-only by default, and pnpm is pinned to 10.34.8
44
+ with a seven-day minimum release age.
45
+ - README documents the release flow, serialization behaviour and that there is no built-in redaction.
46
+ - Built with tsup 9 and TypeScript 6. The `.d.ts` files of the subpaths and the shared core use
47
+ `export type { … }`, and the subpath declarations import shared types from `./index.js`. The
48
+ toolchain change does not change the types consumers see.
49
+ - Development only: `@vllnt/typescript` 3 (stricter compiler flags; published output unchanged),
50
+ `vitest` 5.1.1, and `pnpm test:coverage`.
51
+
52
+ ## [0.1.2] - 2026-03-10
53
+
54
+ ### Changed
55
+
56
+ - Publish workflow and CI refinements.
57
+
58
+ ## [0.1.1] - 2026-03-10
59
+
60
+ ### Changed
61
+
62
+ - Added the publish workflow (trusted publishing, canary and release jobs) and refined CI.
63
+
64
+ ## [0.1.0] - 2026-03-09
65
+
66
+ ### Added
67
+
68
+ - Initial release: core logger (`createLogger`, `createExtendedLogger`, `composeOutputs`,
69
+ `consoleOutput`, `formatLogEntry`, `parseLogLevel`), Node.js backend preset, and the `/convex`,
70
+ `/posthog` and `/testing` entry points.
package/README.md CHANGED
@@ -10,6 +10,12 @@ Zero runtime dependencies. Tree-shakeable. Works in Node.js, Convex, browser, an
10
10
  pnpm add @vllnt/logger
11
11
  ```
12
12
 
13
+ ## For coding agents
14
+
15
+ The docs are bundled in the package: `node_modules/@vllnt/logger/docs/API.md` (every export,
16
+ its signature and an example), `llms.txt`, `CHANGELOG.md` and the TypeScript sources in
17
+ `node_modules/@vllnt/logger/src/`. They match the installed version. Read them before writing code.
18
+
13
19
  ## Quick Start
14
20
 
15
21
  ```ts
@@ -36,6 +42,8 @@ Set `LOG_LEVEL` env var to control verbosity (`debug`, `info`, `warn`, `error`).
36
42
 
37
43
  ## API
38
44
 
45
+ Full reference: [docs/API.md](docs/API.md).
46
+
39
47
  ### `createBackendLogger(scope): ExtendedLogger`
40
48
 
41
49
  Pre-configured for Node.js. Reads `LOG_LEVEL` from `process.env` lazily on each log call.
@@ -162,6 +170,14 @@ type LoggerConfig = { getLogLevel: () => LogLevel; output: LogOutput };
162
170
  - **Lazy level evaluation**: `getLogLevel()` is called per-emit, so env changes are picked up without restart
163
171
  - **Zero side effects**: Core module has zero module-level side effects (`sideEffects: false`)
164
172
 
173
+ ## Related packages
174
+
175
+ - [`@vllnt/analytics`](https://oss.vllnt.com/packages/analytics): product analytics with consent
176
+ management. Use it for user behaviour; use this logger for operational logs.
177
+ - [`@vllnt/convex-events`](https://oss.vllnt.com/packages/convex-events): an append-only activity
178
+ feed stored in Convex. Use it when entries must be stored and queried later; this logger only
179
+ writes to outputs such as the console.
180
+
165
181
  ## Releases
166
182
 
167
183
  Every publish runs in `.github/workflows/publish.yml` with npm trusted publishing and provenance;
@@ -175,3 +191,7 @@ nothing is published from a local machine. Maintainers only.
175
191
  ## License
176
192
 
177
193
  [MIT](LICENSE)
194
+
195
+ ---
196
+
197
+ Part of vllnt oss: https://oss.vllnt.com
package/docs/API.md ADDED
@@ -0,0 +1,240 @@
1
+ # @vllnt/logger API
2
+
3
+ Reference for every public export. This file ships in the npm package, so the copy at
4
+ `node_modules/@vllnt/logger/docs/API.md` matches the installed version. The TypeScript sources
5
+ ship in `node_modules/@vllnt/logger/src/`.
6
+
7
+ ## Entry points
8
+
9
+ The package is ESM only (`import`; there is no `require` condition). Every entry point ships
10
+ its own type declarations.
11
+
12
+ | Import | Exports |
13
+ | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
14
+ | `@vllnt/logger` | `createBackendLogger`, `createLogger`, `createExtendedLogger`, `consoleOutput`, `composeOutputs`, `formatLogEntry`, `parseLogLevel`; types `LogLevel`, `LogData`, `LogEntry`, `LogOutput`, `Logger`, `ExtendedLogger`, `LoggerConfig` |
15
+ | `@vllnt/logger/convex` | `createConvexLogger` |
16
+ | `@vllnt/logger/posthog` | `createPostHogOutput`; type `PostHogCapture` |
17
+ | `@vllnt/logger/testing` | `createTestOutput`; type `TestOutput` |
18
+
19
+ Shared types (`LogEntry`, `LogLevel`, …) are exported only from `@vllnt/logger`.
20
+
21
+ Examples use placeholders (`posthog` for a posthog-js instance, `apiKey`, `distinctId`,
22
+ `fetchRows`, `orderId`) and Vitest's `expect`.
23
+
24
+ ## Behaviour shared by every logger
25
+
26
+ - The emitted `event` is `<scope>.<event>`: `createLogger("auth", …).info("login")` emits
27
+ `auth.login`.
28
+ - Levels by severity: `debug` < `info` < `warn` < `error`. An entry is emitted when its level is
29
+ at or above the configured level.
30
+ - `getLogLevel` runs on every log call. Its result goes through `parseLogLevel`; an invalid value
31
+ or a throw falls back to `info`.
32
+ - Log calls never throw. A throwing `getLogLevel`, output or data getter is swallowed.
33
+ - Data is spread first, then `event`, `level` and `timestamp` (ISO 8601), so data cannot
34
+ overwrite those three fields.
35
+ - Outputs are synchronous. There is no built-in redaction.
36
+
37
+ ## `@vllnt/logger`
38
+
39
+ ### `createBackendLogger(scope: string): ExtendedLogger`
40
+
41
+ Node.js preset. Reads `LOG_LEVEL` from `process.env` on each call, parsed with
42
+ `parseLogLevel(value, "warn")`, so the default is `warn`. Without `process` it uses `warn`.
43
+ Writes with `consoleOutput`.
44
+
45
+ ```ts
46
+ import { createBackendLogger } from "@vllnt/logger";
47
+
48
+ const logger = createBackendLogger("payments");
49
+ logger.warn("charge.declined", { amount: 99 });
50
+ // console.warn: {"amount":99,"event":"payments.charge.declined","level":"warn","timestamp":"..."}
51
+ ```
52
+
53
+ ### `createLogger(scope: string, config: LoggerConfig): Logger`
54
+
55
+ Core factory with your own level source and output.
56
+
57
+ ```ts
58
+ import { consoleOutput, createLogger } from "@vllnt/logger";
59
+
60
+ const logger = createLogger("api", {
61
+ getLogLevel: () => "debug",
62
+ output: consoleOutput,
63
+ });
64
+ logger.debug("request", { path: "/health" });
65
+ ```
66
+
67
+ ### `createExtendedLogger(scope: string, config: LoggerConfig): ExtendedLogger`
68
+
69
+ `createLogger` plus `withTiming` and `withTimingSync`:
70
+
71
+ - `withTiming<T>(label: string, execute: () => Promise<T>, extraData?: LogData): Promise<T>`
72
+ - `withTimingSync<T>(label: string, execute: () => T, extraData?: LogData): T`
73
+
74
+ Both log `info` `<scope>.<label>.start` with `extraData`, then `info` `<scope>.<label>.complete`
75
+ with `extraData` and `durationMs`. If `execute` throws, they log `error` `<scope>.<label>.error`
76
+ with `extraData`, `durationMs` and `error` (the `Error` message, otherwise `String(value)`, or
77
+ `"[unprintable error]"`), then rethrow the original error. The message is logged verbatim.
78
+
79
+ ```ts
80
+ import { consoleOutput, createExtendedLogger } from "@vllnt/logger";
81
+
82
+ const logger = createExtendedLogger("db", {
83
+ getLogLevel: () => "info",
84
+ output: consoleOutput,
85
+ });
86
+ const rows = await logger.withTiming("query", () => fetchRows(), { table: "users" });
87
+ // db.query.start, then db.query.complete with durationMs
88
+ ```
89
+
90
+ ### `consoleOutput(entry: LogEntry): void`
91
+
92
+ Default output. Writes `JSON.stringify(entry)` to `console.debug`, `console.info`,
93
+ `console.warn` or `console.error` by level. `BigInt` is written as a string, `Error` as
94
+ `{ name, message, stack }`, a circular reference as `"[Circular]"`. If serialization still fails
95
+ (a throwing `toJSON` or getter) it writes `[logger:serialize-error] event=<event> level=<level>`.
96
+ A throwing `console` method is swallowed.
97
+
98
+ ```ts
99
+ import { consoleOutput, formatLogEntry } from "@vllnt/logger";
100
+
101
+ consoleOutput(formatLogEntry("error", "job.failed", { error: new Error("timeout") }));
102
+ ```
103
+
104
+ ### `composeOutputs(...outputs: LogOutput[]): LogOutput`
105
+
106
+ Returns one output that calls each output in order. A throwing output does not stop the others.
107
+
108
+ ```ts
109
+ import { composeOutputs, consoleOutput } from "@vllnt/logger";
110
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
111
+
112
+ const output = composeOutputs(consoleOutput, createPostHogOutput(posthog.capture.bind(posthog)));
113
+ ```
114
+
115
+ ### `formatLogEntry(level: LogLevel, event: string, data?: LogData): LogEntry`
116
+
117
+ Builds an entry: `{ ...data, event, level, timestamp }`. It does not add a scope prefix.
118
+
119
+ ```ts
120
+ import { formatLogEntry } from "@vllnt/logger";
121
+
122
+ formatLogEntry("info", "cache.hit", { key: "user:1" });
123
+ // { key: "user:1", event: "cache.hit", level: "info", timestamp: "2026-…Z" }
124
+ ```
125
+
126
+ ### `parseLogLevel(value: string | undefined, defaultLevel?: LogLevel): LogLevel`
127
+
128
+ Trims and lowercases `value`. Returns it when it is `debug`, `info`, `warn` or `error`, otherwise
129
+ `defaultLevel` (default `info`).
130
+
131
+ ```ts
132
+ import { parseLogLevel } from "@vllnt/logger";
133
+
134
+ parseLogLevel(" WARN "); // "warn"
135
+ parseLogLevel("verbose", "error"); // "error"
136
+ ```
137
+
138
+ ### Types
139
+
140
+ ```ts
141
+ type LogLevel = "debug" | "error" | "info" | "warn";
142
+ type LogData = Record<string, unknown>;
143
+ type LogEntry = { event: string; level: LogLevel; timestamp: string } & Record<string, unknown>;
144
+ type LogOutput = (entry: LogEntry) => void;
145
+
146
+ type Logger = {
147
+ debug: (event: string, data?: LogData) => void;
148
+ error: (event: string, data?: LogData) => void;
149
+ info: (event: string, data?: LogData) => void;
150
+ warn: (event: string, data?: LogData) => void;
151
+ };
152
+
153
+ type ExtendedLogger = Logger & {
154
+ withTiming: <T>(label: string, execute: () => Promise<T>, extraData?: LogData) => Promise<T>;
155
+ withTimingSync: <T>(label: string, execute: () => T, extraData?: LogData) => T;
156
+ };
157
+
158
+ type LoggerConfig = {
159
+ /** Called on every log call. */
160
+ getLogLevel: () => LogLevel;
161
+ output: LogOutput;
162
+ };
163
+ ```
164
+
165
+ ## `@vllnt/logger/convex`
166
+
167
+ ### `createConvexLogger(scope: string, level?: LogLevel): ExtendedLogger`
168
+
169
+ Logger for Convex queries, mutations and actions. Uses the fixed `level` (default `info`) and
170
+ `consoleOutput`. It does not read `process.env`.
171
+
172
+ ```ts
173
+ import { createConvexLogger } from "@vllnt/logger/convex";
174
+
175
+ const logger = createConvexLogger("orders", "debug");
176
+ logger.info("created", { orderId });
177
+ ```
178
+
179
+ ## `@vllnt/logger/posthog`
180
+
181
+ ### `createPostHogOutput(capture: PostHogCapture): LogOutput`
182
+
183
+ Calls `capture(entry.event, properties)`, where `properties` is the entry without `event`
184
+ (`level`, `timestamp` and your data). Errors thrown by `capture`, and rejections of a promise it
185
+ returns, are swallowed. No PostHog SDK dependency: pass your own function. posthog-js
186
+ `capture(event, properties)` fits as is:
187
+
188
+ ```ts
189
+ import { createLogger } from "@vllnt/logger";
190
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
191
+
192
+ const logger = createLogger("billing", {
193
+ getLogLevel: () => "info",
194
+ output: createPostHogOutput((event, properties) => posthog.capture(event, properties)),
195
+ });
196
+ ```
197
+
198
+ posthog-node `capture` takes one object, so wrap it. The `= {}` default keeps the wrapper valid
199
+ under `exactOptionalPropertyTypes`, where posthog-node's `properties` does not accept `undefined`:
200
+
201
+ ```ts
202
+ import { createPostHogOutput } from "@vllnt/logger/posthog";
203
+ import { PostHog } from "posthog-node";
204
+
205
+ const client = new PostHog(apiKey);
206
+ const output = createPostHogOutput((event, properties = {}) =>
207
+ client.capture({ distinctId, event, properties }),
208
+ );
209
+ ```
210
+
211
+ ### `PostHogCapture`
212
+
213
+ ```ts
214
+ type PostHogCapture = (event: string, properties?: Record<string, unknown>) => unknown;
215
+ ```
216
+
217
+ ## `@vllnt/logger/testing`
218
+
219
+ ### `createTestOutput(): TestOutput`
220
+
221
+ An output that stores every entry in `entries`, for assertions.
222
+
223
+ ```ts
224
+ import { createLogger } from "@vllnt/logger";
225
+ import { createTestOutput } from "@vllnt/logger/testing";
226
+
227
+ const { entries, output } = createTestOutput();
228
+ const logger = createLogger("test", { getLogLevel: () => "debug", output });
229
+ logger.info("hello", { a: 1 });
230
+ expect(entries[0]).toMatchObject({ event: "test.hello", level: "info", a: 1 });
231
+ ```
232
+
233
+ ### `TestOutput`
234
+
235
+ ```ts
236
+ type TestOutput = {
237
+ entries: readonly LogEntry[];
238
+ output: LogOutput;
239
+ };
240
+ ```
package/llms.txt ADDED
@@ -0,0 +1,33 @@
1
+ # @vllnt/logger
2
+
3
+ > Small structured logging package for the @vllnt ecosystem. Emits JSON log entries, has zero runtime dependencies, and never throws from a log call.
4
+
5
+ Scoped events (`auth.login`), levels `debug`, `info`, `warn`, `error`, and pluggable synchronous outputs. The Node.js backend preset reads `LOG_LEVEL` from `process.env` on each call and defaults to `warn`. There is no built-in redaction. ESM only.
6
+
7
+ ## For coding agents
8
+
9
+ The docs are bundled in the package at `node_modules/@vllnt/logger/docs/`, with the TypeScript sources in `node_modules/@vllnt/logger/src/`. They match the installed version. Read them before writing code.
10
+
11
+ ## Docs
12
+
13
+ - [API Reference](./docs/API.md): Every public export, its signature and an example, per entry point
14
+ - [README](./README.md): Install, quick start, entry points and design decisions
15
+ - [Changelog](./CHANGELOG.md): Version history and release notes
16
+
17
+ ## Entry points
18
+
19
+ - `@vllnt/logger`: core API and Node.js backend preset (`createBackendLogger`)
20
+ - `@vllnt/logger/convex`: `createConvexLogger`, no `process.env` access
21
+ - `@vllnt/logger/posthog`: `createPostHogOutput`
22
+ - `@vllnt/logger/testing`: `createTestOutput`
23
+
24
+ ## Ecosystem
25
+
26
+ - [vllnt oss](https://oss.vllnt.com/llms.txt): Index of all @vllnt open-source packages
27
+
28
+ ## Optional
29
+
30
+ - [Contributing](https://github.com/vllnt/logger/blob/main/CONTRIBUTING.md): Development setup and release flow
31
+ - [AGENTS](https://github.com/vllnt/logger/blob/main/AGENTS.md): Agent instructions for working on this repository (not shipped in the package)
32
+ - [Security Policy](https://github.com/vllnt/logger/blob/main/SECURITY.md): Vulnerability reporting
33
+ - [License](./LICENSE): MIT
package/package.json CHANGED
@@ -1,14 +1,25 @@
1
1
  {
2
2
  "name": "@vllnt/logger",
3
- "version": "0.1.3-canary.90f2d33",
3
+ "version": "0.1.3-canary.adb2d48",
4
4
  "type": "module",
5
5
  "description": "Structured logging for the @vllnt ecosystem",
6
6
  "license": "MIT",
7
7
  "author": "bntvllnt",
8
+ "homepage": "https://oss.vllnt.com/packages/logger",
8
9
  "repository": {
9
10
  "type": "git",
10
11
  "url": "https://github.com/vllnt/logger"
11
12
  },
13
+ "keywords": [
14
+ "logger",
15
+ "logging",
16
+ "structured-logging",
17
+ "json",
18
+ "convex",
19
+ "posthog",
20
+ "typescript",
21
+ "zero-dependency"
22
+ ],
12
23
  "sideEffects": false,
13
24
  "exports": {
14
25
  ".": {
@@ -29,7 +40,11 @@
29
40
  }
30
41
  },
31
42
  "files": [
32
- "dist"
43
+ "dist",
44
+ "src",
45
+ "docs/API.md",
46
+ "CHANGELOG.md",
47
+ "llms.txt"
33
48
  ],
34
49
  "scripts": {
35
50
  "build": "tsup",
@@ -37,6 +52,7 @@
37
52
  "lint": "eslint --cache --cache-location node_modules/.cache/eslint/ --max-warnings 0",
38
53
  "lint:fix": "eslint --cache --cache-location node_modules/.cache/eslint/ --fix",
39
54
  "test": "vitest run",
55
+ "test:coverage": "vitest run --coverage --coverage.include=src --coverage.reporter=text",
40
56
  "test:watch": "vitest"
41
57
  },
42
58
  "publishConfig": {
@@ -44,14 +60,16 @@
44
60
  "registry": "https://registry.npmjs.org/"
45
61
  },
46
62
  "devDependencies": {
47
- "@types/node": "^26.6.5",
48
- "@vllnt/eslint-config": "^2.0.0",
49
- "@vllnt/typescript": "^2.0.0",
63
+ "@types/node": "^26.6.6",
64
+ "@vitest/coverage-v8": "^5.1.1",
65
+ "@vllnt/eslint-config": "^2.1.0",
66
+ "@vllnt/typescript": "^3.0.0",
50
67
  "eslint": "^9.39.5",
51
- "prettier": "^3.9.10",
68
+ "posthog-node": "^6.0.5",
69
+ "prettier": "^3.10.1",
52
70
  "tsup": "^9.0.0",
53
71
  "typescript": "^6.0.3",
54
- "vitest": "^5.0.5"
72
+ "vitest": "^5.1.1"
55
73
  },
56
74
  "packageManager": "pnpm@10.34.8",
57
75
  "pnpm": {
@@ -63,6 +81,7 @@
63
81
  "esbuild"
64
82
  ],
65
83
  "overrides": {
84
+ "minimatch@>=7.0.0 <11.0.1": "11.0.5",
66
85
  "deepmerge-ts@<8.0.0": "^8.0.0",
67
86
  "handlebars@<4.7.10": "^4.7.10"
68
87
  }
package/src/backend.ts ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @vllnt/logger — Backend preset.
3
+ *
4
+ * Pre-configured logger for Node.js backends.
5
+ * Reads LOG_LEVEL from process.env on each call (no module-level side effects).
6
+ */
7
+
8
+ import {
9
+ consoleOutput,
10
+ createExtendedLogger,
11
+ type ExtendedLogger,
12
+ type LogLevel,
13
+ parseLogLevel,
14
+ } from "./core.js";
15
+
16
+ const HAS_PROCESS = typeof process !== "undefined";
17
+
18
+ function getEnvironmentVariable(key: string): string | undefined {
19
+ if (HAS_PROCESS && process.env) {
20
+ return process.env[key];
21
+ }
22
+ return undefined;
23
+ }
24
+
25
+ function getBackendLogLevel(): LogLevel {
26
+ return parseLogLevel(getEnvironmentVariable("LOG_LEVEL"), "warn");
27
+ }
28
+
29
+ /** Create a scoped backend logger. Reads LOG_LEVEL from process.env on each call. */
30
+ export function createBackendLogger(scope: string): ExtendedLogger {
31
+ return createExtendedLogger(scope, {
32
+ getLogLevel: getBackendLogLevel,
33
+ output: consoleOutput,
34
+ });
35
+ }
package/src/convex.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @vllnt/logger — Convex-safe logger.
3
+ *
4
+ * Imports from core.ts (no process.env, no crypto).
5
+ * Works in Convex queries, mutations, and actions.
6
+ */
7
+
8
+ import {
9
+ consoleOutput,
10
+ createExtendedLogger,
11
+ type ExtendedLogger,
12
+ type LogLevel,
13
+ } from "./core.js";
14
+
15
+ /**
16
+ * Create a logger for Convex functions.
17
+ * Pass level explicitly (Convex has no process.env in queries/mutations).
18
+ * Defaults to "info".
19
+ */
20
+ export function createConvexLogger(
21
+ scope: string,
22
+ level: LogLevel = "info",
23
+ ): ExtendedLogger {
24
+ return createExtendedLogger(scope, {
25
+ getLogLevel: () => level,
26
+ output: consoleOutput,
27
+ });
28
+ }
package/src/core.ts ADDED
@@ -0,0 +1,293 @@
1
+ /**
2
+ * @vllnt/logger — Core module.
3
+ *
4
+ * Pure functions, ZERO module-level side effects.
5
+ * Safe to import in any runtime (Node, Convex, browser, edge).
6
+ */
7
+
8
+ /** Log levels ordered by severity */
9
+ export type LogLevel = "debug" | "error" | "info" | "warn";
10
+
11
+ /** Structured log data payload */
12
+ export type LogData = Record<string, unknown>;
13
+
14
+ /** Formatted log entry */
15
+ export type LogEntry = {
16
+ event: string;
17
+ level: LogLevel;
18
+ timestamp: string;
19
+ } & Record<string, unknown>;
20
+
21
+ /** Logger interface — 4 level methods */
22
+ export type Logger = {
23
+ debug: (event: string, data?: LogData) => void;
24
+ error: (event: string, data?: LogData) => void;
25
+ info: (event: string, data?: LogData) => void;
26
+ warn: (event: string, data?: LogData) => void;
27
+ };
28
+
29
+ /** Extended logger with timing helpers */
30
+ export type ExtendedLogger = Logger & {
31
+ withTiming: <T>(
32
+ label: string,
33
+ execute: () => Promise<T>,
34
+ extraData?: LogData,
35
+ ) => Promise<T>;
36
+ withTimingSync: <T>(
37
+ label: string,
38
+ execute: () => T,
39
+ extraData?: LogData,
40
+ ) => T;
41
+ };
42
+
43
+ /** Output handler for log entries. Synchronous by design — async adapters must handle their own promises. */
44
+ export type LogOutput = (entry: LogEntry) => void;
45
+
46
+ /** Configuration for creating a logger */
47
+ export type LoggerConfig = {
48
+ /** Returns the current log level. Called on every log emit — keep it cheap. */
49
+ getLogLevel: () => LogLevel;
50
+ output: LogOutput;
51
+ };
52
+
53
+ const LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {
54
+ debug: 0,
55
+ error: 3,
56
+ info: 1,
57
+ warn: 2,
58
+ };
59
+
60
+ function shouldLog(level: LogLevel, configuredLevel: LogLevel): boolean {
61
+ return LOG_LEVEL_PRIORITY[level] >= LOG_LEVEL_PRIORITY[configuredLevel];
62
+ }
63
+
64
+ /** Parse a log level string, returning default if invalid. */
65
+ export function parseLogLevel(
66
+ value: string | undefined,
67
+ defaultLevel: LogLevel = "info",
68
+ ): LogLevel {
69
+ const normalized = value?.toLowerCase().trim();
70
+ if (
71
+ normalized === "debug" ||
72
+ normalized === "info" ||
73
+ normalized === "warn" ||
74
+ normalized === "error"
75
+ ) {
76
+ return normalized;
77
+ }
78
+ return defaultLevel;
79
+ }
80
+
81
+ /**
82
+ * Format a log entry. User data spread FIRST, fixed fields LAST.
83
+ * This prevents user data from overwriting event/level/timestamp.
84
+ */
85
+ export function formatLogEntry(
86
+ level: LogLevel,
87
+ event: string,
88
+ data?: LogData,
89
+ ): LogEntry {
90
+ return {
91
+ ...data,
92
+ event,
93
+ level,
94
+ timestamp: new Date().toISOString(),
95
+ };
96
+ }
97
+
98
+ /** Resolve the configured level; a throwing or invalid `getLogLevel` falls back to "info". */
99
+ function resolveLevel(config: LoggerConfig): LogLevel {
100
+ try {
101
+ return parseLogLevel(config.getLogLevel(), "info");
102
+ } catch {
103
+ return "info";
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Create a scoped logger with the given configuration.
109
+ *
110
+ * Log calls never throw: a failing `getLogLevel`, `output`, or data getter is
111
+ * swallowed so logging cannot break the host application.
112
+ */
113
+ export function createLogger(scope: string, config: LoggerConfig): Logger {
114
+ const log = (level: LogLevel, event: string, data?: LogData): void => {
115
+ try {
116
+ if (shouldLog(level, resolveLevel(config))) {
117
+ config.output(formatLogEntry(level, `${scope}.${event}`, data));
118
+ }
119
+ } catch {
120
+ // Swallowed — logging failures must not propagate
121
+ }
122
+ };
123
+
124
+ return {
125
+ debug: (event, data) => {
126
+ log("debug", event, data);
127
+ },
128
+ error: (event, data) => {
129
+ log("error", event, data);
130
+ },
131
+ info: (event, data) => {
132
+ log("info", event, data);
133
+ },
134
+ warn: (event, data) => {
135
+ log("warn", event, data);
136
+ },
137
+ };
138
+ }
139
+
140
+ function formatError(error: unknown): string {
141
+ try {
142
+ return error instanceof Error ? error.message : String(error);
143
+ } catch {
144
+ return "[unprintable error]";
145
+ }
146
+ }
147
+
148
+ function createWithTiming(base: Logger): ExtendedLogger["withTiming"] {
149
+ return async <T>(
150
+ label: string,
151
+ execute: () => Promise<T>,
152
+ extraData?: LogData,
153
+ ): Promise<T> => {
154
+ const start = Date.now();
155
+ base.info(`${label}.start`, extraData);
156
+ try {
157
+ const result = await execute();
158
+ base.info(`${label}.complete`, {
159
+ ...extraData,
160
+ durationMs: Date.now() - start,
161
+ });
162
+ return result;
163
+ } catch (error) {
164
+ base.error(`${label}.error`, {
165
+ ...extraData,
166
+ durationMs: Date.now() - start,
167
+ error: formatError(error),
168
+ });
169
+ throw error;
170
+ }
171
+ };
172
+ }
173
+
174
+ function createWithTimingSync(base: Logger): ExtendedLogger["withTimingSync"] {
175
+ return <T>(label: string, execute: () => T, extraData?: LogData): T => {
176
+ const start = Date.now();
177
+ base.info(`${label}.start`, extraData);
178
+ try {
179
+ const result = execute();
180
+ base.info(`${label}.complete`, {
181
+ ...extraData,
182
+ durationMs: Date.now() - start,
183
+ });
184
+ return result;
185
+ } catch (error) {
186
+ base.error(`${label}.error`, {
187
+ ...extraData,
188
+ durationMs: Date.now() - start,
189
+ error: formatError(error),
190
+ });
191
+ throw error;
192
+ }
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Create an extended logger with timing helpers.
198
+ *
199
+ * @remarks Caught errors use `error.message` verbatim.
200
+ * Callers handling sensitive errors should sanitize before throwing.
201
+ */
202
+ export function createExtendedLogger(
203
+ scope: string,
204
+ config: LoggerConfig,
205
+ ): ExtendedLogger {
206
+ const base = createLogger(scope, config);
207
+ return {
208
+ ...base,
209
+ withTiming: createWithTiming(base),
210
+ withTimingSync: createWithTimingSync(base),
211
+ };
212
+ }
213
+
214
+ /**
215
+ * JSON.stringify replacer that keeps entries serializable. It turns BigInt
216
+ * into a string, Error into `{ name, message, stack }`, and circular
217
+ * references into "[Circular]". Repeated non-circular references stay intact.
218
+ */
219
+ function createReplacer(): (
220
+ this: unknown,
221
+ key: string,
222
+ value: unknown,
223
+ ) => unknown {
224
+ const ancestors: unknown[] = [];
225
+ return function replacer(this: unknown, _key: string, value: unknown) {
226
+ if (typeof value === "bigint") {
227
+ return value.toString();
228
+ }
229
+ const resolved =
230
+ value instanceof Error
231
+ ? { message: value.message, name: value.name, stack: value.stack }
232
+ : value;
233
+ if (typeof resolved !== "object" || resolved === null) {
234
+ return resolved;
235
+ }
236
+ // Drop everything below the current holder: the rest is a finished sibling branch.
237
+ ancestors.splice(ancestors.indexOf(this) + 1);
238
+ if (ancestors.includes(resolved)) {
239
+ return "[Circular]";
240
+ }
241
+ ancestors.push(resolved);
242
+ return resolved;
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Default console output handler. Never throws. It handles BigInt, Error and
248
+ * circular values; anything still unserializable (throwing toJSON or getters)
249
+ * degrades to a minimal event/level line, and console failures disappear.
250
+ */
251
+ export function consoleOutput(entry: LogEntry): void {
252
+ let message: string;
253
+ try {
254
+ message = JSON.stringify(entry, createReplacer());
255
+ } catch {
256
+ message = `[logger:serialize-error] event=${entry.event} level=${entry.level}`;
257
+ }
258
+
259
+ try {
260
+ switch (entry.level) {
261
+ case "debug":
262
+ console.debug(message);
263
+ break;
264
+ case "error":
265
+ console.error(message);
266
+ break;
267
+ case "info":
268
+ console.info(message);
269
+ break;
270
+ case "warn":
271
+ console.warn(message);
272
+ break;
273
+ default:
274
+ console.info(message);
275
+ break;
276
+ }
277
+ } catch {
278
+ // Swallowed — a broken console must not break the app
279
+ }
280
+ }
281
+
282
+ /** Compose outputs into a single LogOutput. Each output runs in isolation. */
283
+ export function composeOutputs(...outputs: LogOutput[]): LogOutput {
284
+ return (entry: LogEntry): void => {
285
+ outputs.forEach((output) => {
286
+ try {
287
+ output(entry);
288
+ } catch {
289
+ // Isolated — other outputs continue
290
+ }
291
+ });
292
+ };
293
+ }
package/src/index.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @vllnt/logger — Structured logging for the @vllnt ecosystem.
3
+ *
4
+ * Core exports + backend preset.
5
+ */
6
+
7
+ export { createBackendLogger } from "./backend.js";
8
+ export {
9
+ composeOutputs,
10
+ consoleOutput,
11
+ createExtendedLogger,
12
+ createLogger,
13
+ type ExtendedLogger,
14
+ formatLogEntry,
15
+ type LogData,
16
+ type LogEntry,
17
+ type Logger,
18
+ type LoggerConfig,
19
+ type LogLevel,
20
+ type LogOutput,
21
+ parseLogLevel,
22
+ } from "./core.js";
package/src/posthog.ts ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * @vllnt/logger — PostHog output adapter.
3
+ *
4
+ * Wraps a PostHog-style capture function as a LogOutput.
5
+ * No PostHog SDK dependency — consumer passes their own capture fn.
6
+ */
7
+
8
+ import type { LogEntry, LogOutput } from "./core.js";
9
+
10
+ /** PostHog-compatible capture function signature */
11
+ export type PostHogCapture = (
12
+ event: string,
13
+ properties?: Record<string, unknown>,
14
+ ) => unknown;
15
+
16
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
17
+ return (
18
+ typeof value === "object" &&
19
+ value !== null &&
20
+ typeof (value as { then?: unknown }).then === "function"
21
+ );
22
+ }
23
+
24
+ /**
25
+ * Create a LogOutput that forwards entries to PostHog.
26
+ * Swallows errors from the capture function, including rejected promises it
27
+ * returns — logging must not break the app.
28
+ */
29
+ export function createPostHogOutput(capture: PostHogCapture): LogOutput {
30
+ return (entry: LogEntry): void => {
31
+ try {
32
+ const { event, ...properties } = entry;
33
+ const result = capture(event, properties);
34
+ if (isThenable(result)) {
35
+ Promise.resolve(result).catch(() => {
36
+ // Swallowed — async capture failures must not become unhandled rejections
37
+ });
38
+ }
39
+ } catch {
40
+ // Swallowed — logging failures must not propagate
41
+ }
42
+ };
43
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @vllnt/logger — Test utilities.
3
+ *
4
+ * Provides a test output that captures log entries for assertion.
5
+ */
6
+
7
+ import type { LogEntry, LogOutput } from "./core.js";
8
+
9
+ /** Result of createTestOutput — output function + captured entries */
10
+ export type TestOutput = {
11
+ entries: readonly LogEntry[];
12
+ output: LogOutput;
13
+ };
14
+
15
+ /** Create a test output that captures entries into an array for assertion. */
16
+ export function createTestOutput(): TestOutput {
17
+ const entries: LogEntry[] = [];
18
+ const output: LogOutput = (entry: LogEntry): void => {
19
+ entries.push(entry);
20
+ };
21
+ return { entries, output };
22
+ }