@vielzeug/rune 2.1.1 → 3.0.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/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/* ─── Log levels ─── */\n\nexport type LogType = 'debug' | 'error' | 'fatal' | 'info' | 'warn';\nexport type LogLevel = LogType | 'off';\n\n/** Numeric priority for each level. Lower = more verbose. Exported for transport authors. */\nexport const PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n error: 3,\n fatal: 4,\n info: 1,\n off: 5,\n warn: 2,\n};\n\n/** Returns true if `level` passes the `threshold`. Returns false when `level` is 'off'. Exported for transport/middleware authors. */\nexport function isLevelEnabled(threshold: LogLevel, level: LogLevel): boolean {\n if (level === 'off') return false;\n\n return PRIORITY[threshold] <= PRIORITY[level];\n}\n\n/* ─── Bindings ─── */\n\nexport type Bindings = Record<string, unknown>;\n\n/* ─── Log entry ─── */\n\n/**\n * The structured record produced by every log call and dispatched to all transports.\n * `data` is the merged result of pinned bindings and per-call context — transports\n * receive a single flat object and do not need to merge anything themselves.\n * Any `Error` instances — whether from a pinned binding (`bindings`/`withBindings()`) or\n * per-call context — are automatically serialized to `{ message, name, stack }`.\n * **Shallow only** — an `Error` nested inside a plain object (e.g. `{ meta: { err } }`) is left as-is;\n * only top-level fields of `data` are checked.\n */\nexport type LogEntry = {\n /**\n * Merged structured data: pinned bindings overlaid with per-call context.\n * Already shallow-copied and immutable — do not mutate.\n */\n data: Readonly<Bindings>;\n level: LogType;\n message?: string;\n namespace: string;\n /** Exact moment of the log call — shared across all transports for the same entry. */\n timestamp: Date;\n};\n\n/* ─── Transport ─── */\n\n/**\n * A transport receives a log entry and is responsible for its own delivery and formatting.\n * If a transport throws, the logger catches it, reports it via a dev-only warning, and continues\n * dispatching the entry to remaining transports — a single misbehaving transport can never crash\n * the caller of `log.info()`/etc. or block its siblings.\n */\nexport type Transport = (entry: LogEntry) => void;\n\n/**\n * Middleware function that transforms or filters log entries before dispatch. Return null to drop the entry.\n * If middleware throws, the logger catches it, reports it via a dev-only warning, and drops the entry\n * (no transports run for it) rather than crashing the caller.\n */\nexport type LogMiddleware = (entry: LogEntry) => LogEntry | null;\n\n/* ─── Transport option types ─── */\n\nexport type RemoteLogData = {\n data?: Bindings;\n env: 'development' | 'production';\n level: LogType;\n message?: string;\n namespace?: string;\n timestamp: string;\n};\n\nexport type RemoteTransportOptions = {\n /** Override the detected runtime environment. Default: auto-detected. */\n env?: 'development' | 'production';\n /** Remote delivery handler — receives the log type and structured payload. */\n handler: (type: LogType, data: RemoteLogData) => void;\n /** Minimum level to forward. Default: 'debug'. */\n level?: LogLevel;\n /**\n * Called when the handler throws or rejects.\n * The async error path is separate from any synchronous errors in the emit call stack.\n * Default: a dev-only `console.warn` (gated by `__RUNE_PROD__`). In production builds,\n * unhandled remote transport errors are silently swallowed — pass an explicit `onError`\n * if you need delivery-failure observability in production.\n */\n onError?: (error: unknown, data: RemoteLogData) => void;\n};\n\nexport type JsonTransportOptions = {\n /**\n * Custom output field names. Useful for adapting to aggregator conventions\n * (Datadog, ELK, Loki, etc.).\n *\n * @example\n * jsonTransport({ fields: { level: 'severity', time: '@timestamp', msg: 'message' } })\n */\n fields?: {\n level?: string;\n msg?: string;\n ns?: string;\n time?: string;\n };\n /** Minimum level to output. Default: 'debug'. */\n level?: LogLevel;\n /** Custom output function. Default: process.stdout.write. */\n output?: (line: string) => void;\n /**\n * Replace circular references with `'[Circular]'` instead of throwing a TypeError.\n * Useful in environments where log payloads may contain complex object graphs.\n * Default: false.\n */\n safe?: boolean;\n};\n\n/** Handle returned by `batchTransport()`. Pass `handle.transport` to `createLogger({ transports })`. */\nexport type BatchHandle = {\n /** Delegates to `dispose()`. Enables `await using` declarations. */\n [Symbol.asyncDispose]: () => Promise<void>;\n /** Stop the interval timer, flush remaining entries, and wait for all accepted batches. Idempotent. */\n dispose: () => Promise<void>;\n /** `true` after `dispose()` has been called. */\n readonly disposed: boolean;\n /** Immediately flush buffered entries and wait for their downstream delivery without stopping the timer. */\n flush: () => Promise<void>;\n /** The transport function to pass to `createLogger({ transports: [handle.transport] })`. */\n transport: Transport;\n};\n\nexport type BatchTransportOptions = {\n /** Flush interval in milliseconds. Must be finite and greater than zero. Default: 5000. */\n interval?: number;\n /** Minimum level to buffer. Default: 'debug'. */\n level?: LogLevel;\n /**\n * Hard limit on the in-memory buffer size. Must be a finite non-negative integer.\n * When the buffer exceeds this value, the oldest entries are dropped to prevent\n * unbounded memory growth. Unlike `maxSize`, this does NOT trigger a flush.\n * Default: unbounded.\n */\n maxBuffer?: number;\n /** Maximum buffer size before an early flush. Must be a finite positive integer. Default: 50. */\n maxSize?: number;\n /** Callback to receive flushed batches. May return a Promise. */\n onFlush: (entries: LogEntry[]) => void | Promise<void>;\n /**\n * Called when onFlush throws synchronously or rejects asynchronously. Observes the\n * failure; the corresponding `flush()` or `dispose()` promise still rejects.\n */\n onFlushError?: (entries: LogEntry[], error: unknown) => void;\n};\n\nexport type PipeOptions = {\n /**\n * Called when one of the piped transports throws.\n * Receives the thrown error and the log entry that triggered it.\n * Default: silent (errors are swallowed to protect remaining transports).\n */\n onError?: (error: unknown, entry: LogEntry) => void;\n};\n\nexport type SampleTransportOptions = {\n /** Minimum level to sample. Default: 'debug'. */\n level?: LogLevel;\n /** Finite fraction of entries to forward (0–1). */\n rate: number;\n /** Downstream transport to receive sampled entries. */\n transport: Transport;\n};\n\nexport type RedactTransportOptions = {\n /**\n * Field names to replace at any depth in `data`.\n * Matched by exact field name — dot-path notation (e.g. `'user.password'`) is NOT supported.\n * A key like `'password'` will redact every field named `'password'` at any nesting level.\n */\n keys: string[];\n /**\n * Finite non-negative integer maximum object nesting depth to traverse during redaction.\n * Objects deeper than this limit are returned as-is (not redacted).\n * A dev-only warning is emitted when the cap is hit.\n * Default: 20.\n * @security In production builds, the depth warning is suppressed — deeply-nested sensitive\n * fields beyond `maxDepth` will pass through unredacted without any indication. Ensure that\n * sensitive payloads are not nested beyond this limit, or lower `maxDepth` as needed.\n */\n maxDepth?: number;\n /** Replacement value for redacted fields. Default: '[REDACTED]'. */\n replacement?: string;\n /** Downstream transport to receive the redacted entry. */\n transport: Transport;\n};\n\n/* ─── Logger options ─── */\n\nexport type RuneOptions = {\n /** Initial pinned bindings for this logger instance. `Error` values are auto-serialized, same as per-call context. */\n bindings?: Bindings;\n /** Minimum log level for this logger instance. Default: 'debug'. */\n logLevel?: LogLevel;\n /** Middleware pipeline applied to every entry before dispatch to transports. */\n middleware?: LogMiddleware[];\n /**\n * Namespace for this logger. When passed to `child()`, it is automatically\n * dot-joined to the parent namespace (e.g. parent `'api'` + child `'auth'` → `'api.auth'`).\n */\n namespace?: string;\n /**\n * Transport pipeline. Each transport receives every entry that passes the level threshold.\n * Default: [consoleTransport()].\n */\n transports?: Transport[];\n};\n\n/* ─── Log method ─── */\n\n/**\n * Signature shared by all five log-level methods.\n *\n * - `log.info('message')` — string-only, most common.\n * - `log.info({ ...fields }, 'message')` — structured context + optional message.\n * `Error` values in `fields` are automatically serialized to `{ message, name, stack }`.\n * Serialization is shallow only — an `Error` nested inside a nested object is left as-is.\n * - `log.error(err, { ...fields }, 'message')` — Error first, then optional context + message.\n * Shorthand for the pattern where an Error is the primary subject of the log call.\n * The context object may be omitted entirely: `log.error(err, 'message')`.\n *\n * @example\n * log.error({ err: new Error('timeout'), requestId }, 'request failed')\n * log.error(new Error('timeout'), { requestId }, 'request failed')\n */\nexport type LogMethod = {\n (message: string): void;\n (error: Error, message?: string): void;\n (error: Error, context: Bindings, message?: string): void;\n (context: Bindings, message?: string): void;\n};\n\n/* ─── Logger interface ─── */\n\nexport type Logger = {\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose]: () => void;\n /** Snapshot of currently pinned bindings. */\n readonly bindings: Readonly<Bindings>;\n /** Create a child logger with config overrides. Inherits all config and bindings by default. */\n child: (overrides?: RuneOptions) => Logger;\n debug: LogMethod;\n /** `AbortSignal` aborted when `dispose()` is called. Use to tie external lifetimes to this logger. */\n readonly disposalSignal: AbortSignal;\n /**\n * Marks the logger as disposed — all subsequent log calls become no-ops.\n * Aborts `disposalSignal`. Does NOT auto-discover or dispose batch transports;\n * hold a direct reference to `batchTransport` and call its `dispose()` on shutdown.\n * Idempotent — safe to call multiple times.\n */\n dispose: () => void;\n /** `true` after `dispose()` has been called. */\n readonly disposed: boolean;\n /** Returns true if entries at this level will pass the configured threshold. */\n enabled: (type: LogLevel) => boolean;\n error: LogMethod;\n fatal: LogMethod;\n /**\n * Wrap a callback in a console group, closing it even on throw/reject.\n * Pass a `level` to gate the group header on the configured log threshold\n * (e.g. `level: 'debug'` suppresses the group when `logLevel` is above `'debug'`).\n * Default: always renders (unless `logLevel` is `'off'`).\n */\n group: <T>(label: string, fn: () => T, level?: LogType) => T;\n /**\n * Same as `group`, using `console.groupCollapsed`.\n * Pass a `level` to gate the group on the configured log threshold.\n */\n groupCollapsed: <T>(label: string, fn: () => T, level?: LogType) => T;\n info: LogMethod;\n /** Active log level for this logger instance. */\n readonly logLevel: LogLevel;\n /** Middleware pipeline applied before dispatch. */\n readonly middleware: readonly LogMiddleware[];\n /** Namespace string for this logger instance. */\n readonly namespace: string;\n /**\n * Measure execution time of `fn` and emit a structured log entry.\n * The entry message is `label`; `data` contains `{ duration_ms }` (rounded to 2 dp).\n * When `fn` throws or rejects, `data` also includes `{ err }` with the serialized error.\n * @param label - Human-readable description of the operation.\n * @param fn - Synchronous or async function to time.\n * @param level - Log level for the timing entry. Default: `'debug'`.\n */\n time: <T>(label: string, fn: () => T, level?: LogType) => T;\n /** Transport pipeline for this logger instance. */\n readonly transports: readonly Transport[];\n /**\n * Add a middleware function to the pipeline. Returns a **new** logger — the original is unchanged.\n * Discarding the return value is a common mistake: always assign the result.\n * @example\n * const log = baseLog.use(tracingMiddleware); // ✓ keep the result\n */\n use: (middleware: LogMiddleware) => Logger;\n warn: LogMethod;\n /**\n * Derive a child logger with additional pinned bindings.\n * The returned logger is fully independent — disposing it does not affect the parent,\n * and disposing the parent does not affect child loggers.\n */\n withBindings: (bindings: Bindings) => Logger;\n};\n"],"mappings":";AAMA,IAAa,IAAqC;CAChD,OAAO;CACP,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,MAAM;AACR;AAGA,SAAgB,EAAe,GAAqB,GAA0B;CAG5E,OAFI,MAAU,SAEP,EAAS,MAAc,EAAS;AACzC"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../src/types.ts"],"sourcesContent":["/* ─── Log levels ─── */\n\nexport type LogType = 'debug' | 'error' | 'fatal' | 'info' | 'warn';\nexport type LogLevel = LogType | 'off';\n\n/** Numeric priority for each level. Lower = more verbose. Exported for transport authors. */\nexport const PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n error: 3,\n fatal: 4,\n info: 1,\n off: 5,\n warn: 2,\n};\n\n/** Returns true if `level` passes the `threshold`. Returns false when `level` is 'off'. Exported for transport authors. */\nexport function isLevelEnabled(threshold: LogLevel, level: LogLevel): boolean {\n if (level === 'off') return false;\n\n return PRIORITY[threshold] <= PRIORITY[level];\n}\n\n/* ─── Bindings ─── */\n\nexport type Bindings = Record<string, unknown>;\n\n/* ─── Log entry ─── */\n\n/**\n * The structured record produced by every log call and dispatched to all transports.\n * `data` is the merged result of pinned bindings and per-call context — transports\n * receive a single flat object and do not need to merge anything themselves.\n * Any `Error` instances — whether from a pinned binding (`bindings`/`withBindings()`) or\n * per-call context — are automatically serialized to `{ message, name, stack }`.\n * **Shallow only** — an `Error` nested inside a plain object (e.g. `{ meta: { err } }`) is left as-is;\n * only top-level fields of `data` are checked.\n */\nexport type LogEntry = {\n /**\n * Merged structured data: pinned bindings overlaid with per-call context.\n * Already shallow-copied and immutable — do not mutate.\n */\n data: Readonly<Bindings>;\n level: LogType;\n message?: string;\n namespace: string;\n /** Exact moment of the log call — shared across all transports for the same entry. */\n timestamp: Date;\n};\n\n/* ─── Transport ─── */\n\n/**\n * A transport receives a log entry and is responsible for its own delivery and formatting.\n * If a transport throws, the logger catches it, reports it via a dev-only warning, and continues\n * dispatching the entry to remaining transports — a single misbehaving transport can never crash\n * the caller of `log.info()`/etc. or block its siblings.\n */\nexport type Transport = (entry: LogEntry) => void;\n\n/** Transform or filter entries before dispatch. Return `null` to drop an entry. */\nexport type LogMiddleware = (entry: LogEntry) => LogEntry | null;\n\n/* ─── Transport option types ─── */\n\nexport type RemoteLogData = {\n data?: Readonly<Bindings>;\n env: 'development' | 'production';\n level: LogType;\n message?: string;\n namespace?: string;\n timestamp: string;\n};\n\nexport type RemoteTransportOptions = {\n /** Override the detected runtime environment. Default: auto-detected. */\n env?: 'development' | 'production';\n /** Remote delivery handler. */\n handler: (type: LogType, data: RemoteLogData) => void | Promise<unknown>;\n /** Minimum level to forward. Default: 'debug'. */\n level?: LogLevel;\n /** Observe synchronous throws and asynchronous rejections from `handler`. */\n onError?: (error: unknown, data: RemoteLogData) => void;\n};\n\nexport type JsonTransportOptions = {\n /**\n * Custom output field names. Useful for adapting to aggregator conventions\n * (Datadog, ELK, Loki, etc.).\n *\n * @example\n * jsonTransport({ fields: { level: 'severity', time: '@timestamp', msg: 'message' } })\n */\n fields?: {\n level?: string;\n msg?: string;\n ns?: string;\n time?: string;\n };\n /** Minimum level to output. Default: 'debug'. */\n level?: LogLevel;\n /** Custom output function. Default: process.stdout.write. */\n output?: (line: string) => void;\n /**\n * Replace circular references with `'[Circular]'` instead of throwing a TypeError.\n * Useful in environments where log payloads may contain complex object graphs.\n * Default: false.\n */\n safe?: boolean;\n};\n\n/** Handle returned by `batchTransport()`. */\nexport type BatchHandle = {\n [Symbol.asyncDispose]: () => Promise<void>;\n dispose: () => Promise<void>;\n readonly disposed: boolean;\n flush: () => Promise<void>;\n transport: Transport;\n};\n\nexport type BatchTransportOptions = {\n /** Flush interval in milliseconds. Default: 5000. */\n interval?: number;\n /** Minimum level to buffer. Default: 'debug'. */\n level?: LogLevel;\n /** Hard limit on buffered entries. Oldest entries are dropped first. Default: unbounded. */\n maxBuffer?: number;\n /** Flush once this many entries are buffered. Default: 50. */\n maxSize?: number;\n /** Deliver one accepted batch. Batches are delivered serially. */\n onFlush: (entries: LogEntry[]) => void | Promise<void>;\n /** Observe delivery failures. Manual failures reject `flush()`; automatic failures reject `dispose()`. */\n onFlushError?: (entries: LogEntry[], error: unknown) => void;\n};\n\nexport type SampleTransportOptions = {\n /** Minimum level to sample. Default: 'debug'. */\n level?: LogLevel;\n /** Finite fraction of entries to forward, from 0 to 1. */\n rate: number;\n transport: Transport;\n};\n\nexport type RedactTransportOptions = {\n /** Exact field names to replace at any depth. */\n keys: readonly string[];\n /** Maximum nested object depth to inspect. Deeper subtrees are replaced entirely. Default: 20. */\n maxDepth?: number;\n /** Replacement used for matching fields and depth-limited subtrees. Default: '[REDACTED]'. */\n replacement?: string;\n transport: Transport;\n};\n\n/* ─── Logger options ─── */\n\nexport type RuneOptions = {\n /** Initial pinned bindings for this logger instance. `Error` values are auto-serialized, same as per-call context. */\n bindings?: Bindings;\n /** Minimum log level for this logger instance. Default: 'debug'. */\n logLevel?: LogLevel;\n /** Middleware applied once, in order, before dispatch to every transport. */\n middleware?: LogMiddleware[];\n /**\n * Namespace for this logger. When passed to `child()`, it is automatically\n * dot-joined to the parent namespace (e.g. parent `'api'` + child `'auth'` → `'api.auth'`).\n */\n namespace?: string;\n /**\n * Transport pipeline. Each transport receives every entry that passes the level threshold.\n * Default: [consoleTransport()].\n */\n transports?: Transport[];\n};\n\n/* ─── Log method ─── */\n\n/**\n * Signature shared by all five log-level methods.\n *\n * Message-first calls are preferred for ordinary application logging. Context-first and error-first\n * calls support structured events, adapters, and error forwarding without synthetic messages.\n * `Error` values in context are serialized shallowly to `{ message, name, stack }`.\n *\n * @example\n * log.info('request started', { requestId: 'abc' })\n * log.debug(event, `bus:${event.type}`)\n * log.error(new Error('timeout'), { requestId: 'abc' }, 'request failed')\n */\nexport type LogMethod = {\n (message: string, context?: Bindings): void;\n (error: Error, message?: string): void;\n (error: Error, context: Bindings, message?: string): void;\n (context: Bindings, message?: string): void;\n};\n\n/* ─── Logger interface ─── */\n\nexport type Logger = {\n /** Delegates to `dispose()`. Enables `using` declarations. */\n [Symbol.dispose]: () => void;\n /** Snapshot of currently pinned bindings. */\n readonly bindings: Readonly<Bindings>;\n /** Create a child logger with config overrides. Inherits all config and bindings by default. */\n child: (overrides?: RuneOptions) => Logger;\n debug: LogMethod;\n /** `AbortSignal` aborted when `dispose()` is called. Use to tie external lifetimes to this logger. */\n readonly disposalSignal: AbortSignal;\n /**\n * Marks the logger as disposed — all subsequent log calls become no-ops.\n * Aborts `disposalSignal`. Idempotent — safe to call multiple times.\n */\n dispose: () => void;\n /** `true` after `dispose()` has been called. */\n readonly disposed: boolean;\n /** Returns true if entries at this level will pass the configured threshold. */\n enabled: (type: LogLevel) => boolean;\n error: LogMethod;\n fatal: LogMethod;\n /**\n * Wrap a callback in a console group, closing it even on throw/reject.\n * Pass a `level` to gate the group header on the configured log threshold\n * (e.g. `level: 'debug'` suppresses the group when `logLevel` is above `'debug'`).\n * Default: always renders (unless `logLevel` is `'off'`).\n */\n group: <T>(label: string, fn: () => T, level?: LogType) => T;\n /**\n * Same as `group`, using `console.groupCollapsed`.\n * Pass a `level` to gate the group on the configured log threshold.\n */\n groupCollapsed: <T>(label: string, fn: () => T, level?: LogType) => T;\n info: LogMethod;\n /** Active log level for this logger instance. */\n readonly logLevel: LogLevel;\n /** Middleware pipeline snapshot. */\n readonly middleware: readonly LogMiddleware[];\n /** Namespace string for this logger instance. */\n readonly namespace: string;\n /**\n * Measure execution time of `fn` and emit a structured log entry.\n * The entry message is `label`; `data` contains `{ duration_ms }` (rounded to 2 dp).\n * When `fn` throws or rejects, `data` also includes `{ err }` with the serialized error.\n * @param label - Human-readable description of the operation.\n * @param fn - Synchronous or async function to time.\n * @param level - Log level for the timing entry. Default: `'debug'`.\n */\n time: <T>(label: string, fn: () => T, level?: LogType) => T;\n /** Transport pipeline for this logger instance. */\n readonly transports: readonly Transport[];\n /** Return a new logger with one additional middleware function. */\n use: (middleware: LogMiddleware) => Logger;\n warn: LogMethod;\n /**\n * Derive a child logger with additional pinned bindings.\n * The returned logger is fully independent — disposing it does not affect the parent,\n * and disposing the parent does not affect child loggers.\n */\n withBindings: (bindings: Bindings) => Logger;\n};\n"],"mappings":";AAMA,IAAa,IAAqC;CAChD,OAAO;CACP,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,MAAM;AACR;AAGA,SAAgB,EAAe,GAAqB,GAA0B;CAG5E,OAFI,MAAU,SAEP,EAAS,MAAc,EAAS;AACzC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vielzeug/rune",
3
- "version": "2.1.1",
3
+ "version": "3.0.0",
4
4
  "description": "Structured logging — scoped loggers, pluggable transports, log levels, and remote log draining",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,19 +30,19 @@
30
30
  "registry": "https://registry.npmjs.org/"
31
31
  },
32
32
  "scripts": {
33
- "build": "vite build && pnpm run build:bundle && pnpm run build:types",
33
+ "build": "vite build && pnpm --silent run build:bundle && pnpm --silent run build:types",
34
34
  "build:bundle": "vite build --config vite.bundle.config.ts",
35
35
  "build:types": "tsc -p tsconfig.declarations.json",
36
36
  "fix": "biome check --write src",
37
37
  "lint": "biome ci src",
38
- "prepublishOnly": "pnpm run build",
38
+ "prepublishOnly": "pnpm --silent run build",
39
39
  "preview": "vite preview",
40
40
  "test": "vitest"
41
41
  },
42
42
  "devDependencies": {
43
- "@types/node": "^26.2.0",
43
+ "@types/node": "^26.4.1",
44
44
  "typescript": "^6.0.3",
45
- "vite": "^8.2.1",
46
- "vitest": "^4.1.10"
45
+ "vite": "^8.2.2",
46
+ "vitest": "^5.0.0"
47
47
  }
48
48
  }