@tupik/infra 0.0.0-stage → 1.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carlos Alberto Barbosa Stenzel / Tupik Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @tupik/infra
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Universal production building blocks for **Tupik**: pluggable key/value storage with TTL, a structured
4
+ JSON logger and duck-typed OpenTelemetry tracing. Zero dependencies and no `node:*` imports, so it runs on any runtime.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ npm install @tupik/infra
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```ts
15
+ import { createLogger, createMemoryStorage, createRuntimeTracer, namespaced } from '@tupik/infra';
16
+
17
+ const storage = createMemoryStorage();
18
+ const sessions = namespaced(storage, 'session'); // keys stored as 'session:<key>'
19
+ await sessions.set('abc', { user: 1 }, { ttlMs: 60_000 });
20
+ console.log(await sessions.get('abc')); // { user: 1 }
21
+
22
+ const log = createLogger({ level: 'info', base: { service: 'api' }, redact: ['password'] });
23
+ log.child({ requestId: 'r1' }).info('login', { password: 'secret' });
24
+ // {"level":"info","time":...,"msg":"login","service":"api","requestId":"r1","password":"[redacted]"}
25
+
26
+ // Without `tracer` every span is a no-op; pass `trace.getTracer('api')` from @opentelemetry/api to record spans.
27
+ const tracer = createRuntimeTracer();
28
+ const value = await tracer.span('compute', (span) => {
29
+ span.setAttribute('items', 3);
30
+ return 42;
31
+ });
32
+ console.log(tracer.enabled, value); // false 42
33
+ ```
34
+
35
+ ## Key API
36
+
37
+ | Export | Purpose |
38
+ | --- | --- |
39
+ | `createMemoryStorage({ now? })` | In-memory `Storage` (`get`/`set` with `ttlMs`/`delete`/`clear`/`keys`) |
40
+ | `namespaced(storage, prefix)` | View over any `Storage` that stores keys as `prefix:key` |
41
+ | `createLogger({ level?, base?, sink?, redact?, maskIp?, errorDetail?, now? })` | JSON-lines logger with `child(bindings)`; redacts `DEFAULT_REDACT_KEYS` at any depth and masks IPs by default |
42
+ | `maskIp(value)`, `DEFAULT_REDACT_KEYS`, `IP_LOG_KEYS` | IP masking (IPv4 /24, IPv6 /48), the default redaction list and the IP keys |
43
+ | `createRedactor({ redact?, maskIp?, errorDetail? })` | The logger's deep redaction as a function (single source, also inlined by `@tupik/middleware`) |
44
+ | `createRuntimeTracer({ tracer?, attributes?, errorDetail? })` | `span(name, fn, { attributes, kind, links, context }?)` over any OTel-compatible tracer; `errorDetail: 'name'` keeps only `error.type` |
45
+ | `parseTraceparent(header)`, `formatTraceparent(spanContext)` | W3C Trace Context `traceparent` in and out |
46
+ | `createAttributeRedactor({ redact?, maskIp?, sensitive? })` | Flat OTel attributes after `createRedactor`, with sensitive field paths (e.g. a route's `pii`/`health`/`secret`) as `'[redacted]'` |
47
+
48
+ ## License
49
+
50
+ MIT
@@ -0,0 +1,199 @@
1
+ /** Options for a single write. */
2
+ interface StorageEntryOptions {
3
+ /** Time to live in milliseconds (finite, >= 0). Omit for an entry that never expires. */
4
+ ttlMs?: number;
5
+ }
6
+ /**
7
+ * Pluggable asynchronous key/value store. Implement it over KV, Redis, D1, etc.;
8
+ * `keys` is optional and enables namespaced `clear()`.
9
+ */
10
+ interface Storage {
11
+ get<T = unknown>(key: string): Promise<T | undefined>;
12
+ set<T>(key: string, value: T, options?: StorageEntryOptions): Promise<void>;
13
+ delete(key: string): Promise<boolean>;
14
+ clear(): Promise<void>;
15
+ /** Live keys, optionally only those starting with `prefix`. */
16
+ keys?(prefix?: string): Promise<string[]>;
17
+ }
18
+ interface MemoryStorageOptions {
19
+ /** Clock in milliseconds; injectable so TTL is testable without timers. Default `Date.now`. */
20
+ now?: () => number;
21
+ }
22
+ /**
23
+ * In-memory `Storage` backed by a `Map`. Values are stored by reference (not cloned).
24
+ * Expired entries read as `undefined` and are dropped lazily on access.
25
+ */
26
+ declare function createMemoryStorage(options?: MemoryStorageOptions): Storage;
27
+ /**
28
+ * Scopes a storage under `prefix + ':'`. `clear()` deletes only the namespace's keys and
29
+ * therefore needs a backend that implements `keys()`; otherwise it rejects with a TypeError
30
+ * instead of silently clearing nothing (or everything).
31
+ */
32
+ declare function namespaced(storage: Storage, prefix: string): Storage;
33
+
34
+ /**
35
+ * Single source of the redaction rules shared by `createLogger`, the
36
+ * `@tupik/middleware` logger and its `errorReporter` (which inlines this
37
+ * module at build time, so it keeps depending only on `@tupik/core`).
38
+ */
39
+ /** How much of an `Error` reaches the log. */
40
+ type ErrorDetail = 'name' | 'message' | 'stack';
41
+ /** Keys always redacted (case-insensitive): credentials, session data and personal identifiers. */
42
+ declare const DEFAULT_REDACT_KEYS: readonly string[];
43
+ /** Keys whose values are IP addresses, masked when `maskIp` is on. */
44
+ declare const IP_LOG_KEYS: readonly string[];
45
+ /**
46
+ * Masks one IP (IPv4 keeps the first three octets, IPv6 the first three
47
+ * groups) or every entry of a comma-separated list such as
48
+ * `x-forwarded-for`. Anything that is not an IP becomes `'[redacted]'`.
49
+ */
50
+ declare function maskIp(value: string): string;
51
+ interface RedactOptions {
52
+ /** Extra keys (case-insensitive) replaced by `'[redacted]'`, added to `DEFAULT_REDACT_KEYS`. */
53
+ redact?: readonly string[];
54
+ /** Masks values under `IP_LOG_KEYS` (IPv4 → `/24`, IPv6 → `/48`). Default `true`. */
55
+ maskIp?: boolean;
56
+ /** How much of an `Error` is kept. Default `'message'`. */
57
+ errorDetail?: ErrorDetail;
58
+ }
59
+ /**
60
+ * Returns a function that copies a value with `DEFAULT_REDACT_KEYS` (plus
61
+ * `redact`) replaced by `'[redacted]'` at any depth, IP keys masked, errors
62
+ * reduced per `errorDetail`, cycles as `'[circular]'` and values nested deeper
63
+ * than `MAX_LOG_DEPTH` (counting the root's fields as level 0) as
64
+ * `'[truncated]'`. Inputs are never mutated.
65
+ */
66
+ declare function createRedactor(options?: RedactOptions): (value: unknown) => unknown;
67
+
68
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
69
+ interface LogRecord {
70
+ level: LogLevel;
71
+ time: number;
72
+ msg: string;
73
+ [key: string]: unknown;
74
+ }
75
+ /** Receives one serialized JSON line per log call. */
76
+ type LogSink = (line: string) => void;
77
+ interface LoggerOptions {
78
+ /** Minimum level written. Default `'info'`. */
79
+ level?: LogLevel;
80
+ /** Fields merged into every record. */
81
+ base?: Record<string, unknown>;
82
+ /** Default `console.log`. */
83
+ sink?: LogSink;
84
+ /**
85
+ * Extra keys (case-insensitive) replaced by `'[redacted]'`, added to
86
+ * `DEFAULT_REDACT_KEYS`. Applied at any depth (objects and arrays) up to
87
+ * `MAX_LOG_DEPTH`; deeper values become `'[truncated]'` and cycles
88
+ * `'[circular]'`. Objects with `toJSON` (Date, URL) are kept; inputs are
89
+ * never mutated.
90
+ */
91
+ redact?: readonly string[];
92
+ /** Masks values under `IP_LOG_KEYS` (IPv4 → `/24`, IPv6 → `/48`). Default `true`. */
93
+ maskIp?: boolean;
94
+ /**
95
+ * How much of an `Error` is written: `'name'`, `'message'` (default) or
96
+ * `'stack'`. Stacks reveal paths and code: enable `'stack'` only outside
97
+ * production. Messages may carry user data; use `'name'` when they can.
98
+ */
99
+ errorDetail?: ErrorDetail;
100
+ /** Clock in milliseconds. Default `Date.now`. */
101
+ now?: () => number;
102
+ }
103
+ interface Logger {
104
+ debug(msg: string, fields?: Record<string, unknown>): void;
105
+ info(msg: string, fields?: Record<string, unknown>): void;
106
+ warn(msg: string, fields?: Record<string, unknown>): void;
107
+ error(msg: string, fields?: Record<string, unknown>): void;
108
+ /** A logger that adds `bindings` to every record (per-call fields still win). */
109
+ child(bindings: Record<string, unknown>): Logger;
110
+ }
111
+ /**
112
+ * Structured JSON logger: one JSON object per call, written to `sink`.
113
+ * Runtime-agnostic. Redacts `DEFAULT_REDACT_KEYS` (plus `redact`) at any
114
+ * depth and masks IPs by default.
115
+ */
116
+ declare function createLogger(options?: LoggerOptions): Logger;
117
+
118
+ /** W3C trace identity of a span (OpenTelemetry `SpanContext`). */
119
+ interface SpanContextLike {
120
+ readonly traceId: string;
121
+ readonly spanId: string;
122
+ readonly traceFlags: number;
123
+ readonly isRemote?: boolean;
124
+ }
125
+ /** Structural subset of an OpenTelemetry `Span`; a real OTel span satisfies it. */
126
+ interface SpanLike {
127
+ setAttribute(key: string, value: unknown): void;
128
+ setStatus?(status: {
129
+ code: number;
130
+ message?: string;
131
+ }): void;
132
+ recordException?(error: unknown): void;
133
+ /** Present on real OTel spans; used to propagate `traceparent` downstream. */
134
+ spanContext?(): SpanContextLike;
135
+ end(): void;
136
+ }
137
+ /** Options of one span (subset of OpenTelemetry `SpanOptions`). */
138
+ interface SpanOptionsLike {
139
+ attributes?: Record<string, unknown>;
140
+ /** OpenTelemetry `SpanKind` (`1` = SERVER). */
141
+ kind?: number;
142
+ links?: readonly {
143
+ readonly context: SpanContextLike;
144
+ }[];
145
+ }
146
+ /** Structural subset of an OpenTelemetry `Tracer` (e.g. `trace.getTracer('app')`). */
147
+ interface TracerLike {
148
+ /** `context` is the parent OTel `Context`, passed through untouched. */
149
+ startSpan(name: string, options?: SpanOptionsLike, context?: unknown): SpanLike;
150
+ }
151
+ interface TracingOptions {
152
+ /** Without a tracer every span is a no-op and `enabled` is `false`. */
153
+ tracer?: TracerLike;
154
+ /** Attributes passed to every `startSpan` call. */
155
+ attributes?: Record<string, unknown>;
156
+ /**
157
+ * What a failed span records. `'message'` (default) calls `recordException`
158
+ * and puts the message in the status; `'name'` only sets `error.type`, so
159
+ * messages that may carry personal data never reach the trace backend.
160
+ */
161
+ errorDetail?: 'name' | 'message';
162
+ }
163
+ /** Per-span options of `RuntimeTracer.span`. */
164
+ interface SpanStartOptions extends SpanOptionsLike {
165
+ /** Parent OTel `Context` (e.g. from `propagation.extract`). */
166
+ context?: unknown;
167
+ }
168
+ interface RuntimeTracer {
169
+ /** Runs `fn` inside a span; the span always ends, errors propagate unchanged. */
170
+ span<T>(name: string, fn: (span: SpanLike) => T | Promise<T>, options?: SpanStartOptions): Promise<T>;
171
+ readonly enabled: boolean;
172
+ }
173
+ /** OpenTelemetry hooks without an SDK dependency: pass any tracer that matches `TracerLike`. */
174
+ declare function createRuntimeTracer(options?: TracingOptions): RuntimeTracer;
175
+ /** Parses a W3C `traceparent` header; `undefined` when absent or invalid (then a new trace starts). */
176
+ declare function parseTraceparent(header: string | null | undefined): SpanContextLike | undefined;
177
+ /** `traceparent` value for an outgoing request; `undefined` for an invalid (e.g. no-op) span context. */
178
+ declare function formatTraceparent(context: SpanContextLike): string | undefined;
179
+ /** Value an OpenTelemetry attribute may hold. */
180
+ type AttributeValue = string | number | boolean | readonly (string | number | boolean)[];
181
+ interface AttributeRedactorOptions extends Omit<RedactOptions, 'errorDetail'> {
182
+ /**
183
+ * Field paths whose values never reach a span (e.g. the `pii`/`health`/
184
+ * `secret` paths of a route). An attribute matches by full path or by its
185
+ * last segment, case-insensitive: `'profile.email'` hides `user.email` too.
186
+ */
187
+ sensitive?: readonly string[];
188
+ }
189
+ /**
190
+ * Returns a function that turns free-form attributes into flat OpenTelemetry
191
+ * attributes: `createRedactor` rules first (default keys, IP masking), then
192
+ * every `sensitive` field becomes `'[redacted]'`. Nested objects flatten to
193
+ * dotted keys; arrays of objects become JSON; `null`, `undefined` and
194
+ * functions are dropped.
195
+ */
196
+ declare function createAttributeRedactor(options?: AttributeRedactorOptions): (attributes: Record<string, unknown>) => Record<string, AttributeValue>;
197
+
198
+ export { DEFAULT_REDACT_KEYS, IP_LOG_KEYS, createAttributeRedactor, createLogger, createMemoryStorage, createRedactor, createRuntimeTracer, formatTraceparent, maskIp, namespaced, parseTraceparent };
199
+ export type { AttributeRedactorOptions, AttributeValue, ErrorDetail, LogLevel, LogRecord, LogSink, Logger, LoggerOptions, MemoryStorageOptions, RedactOptions, RuntimeTracer, SpanContextLike, SpanLike, SpanOptionsLike, SpanStartOptions, Storage, StorageEntryOptions, TracerLike, TracingOptions };
@@ -0,0 +1,199 @@
1
+ /** Options for a single write. */
2
+ interface StorageEntryOptions {
3
+ /** Time to live in milliseconds (finite, >= 0). Omit for an entry that never expires. */
4
+ ttlMs?: number;
5
+ }
6
+ /**
7
+ * Pluggable asynchronous key/value store. Implement it over KV, Redis, D1, etc.;
8
+ * `keys` is optional and enables namespaced `clear()`.
9
+ */
10
+ interface Storage {
11
+ get<T = unknown>(key: string): Promise<T | undefined>;
12
+ set<T>(key: string, value: T, options?: StorageEntryOptions): Promise<void>;
13
+ delete(key: string): Promise<boolean>;
14
+ clear(): Promise<void>;
15
+ /** Live keys, optionally only those starting with `prefix`. */
16
+ keys?(prefix?: string): Promise<string[]>;
17
+ }
18
+ interface MemoryStorageOptions {
19
+ /** Clock in milliseconds; injectable so TTL is testable without timers. Default `Date.now`. */
20
+ now?: () => number;
21
+ }
22
+ /**
23
+ * In-memory `Storage` backed by a `Map`. Values are stored by reference (not cloned).
24
+ * Expired entries read as `undefined` and are dropped lazily on access.
25
+ */
26
+ declare function createMemoryStorage(options?: MemoryStorageOptions): Storage;
27
+ /**
28
+ * Scopes a storage under `prefix + ':'`. `clear()` deletes only the namespace's keys and
29
+ * therefore needs a backend that implements `keys()`; otherwise it rejects with a TypeError
30
+ * instead of silently clearing nothing (or everything).
31
+ */
32
+ declare function namespaced(storage: Storage, prefix: string): Storage;
33
+
34
+ /**
35
+ * Single source of the redaction rules shared by `createLogger`, the
36
+ * `@tupik/middleware` logger and its `errorReporter` (which inlines this
37
+ * module at build time, so it keeps depending only on `@tupik/core`).
38
+ */
39
+ /** How much of an `Error` reaches the log. */
40
+ type ErrorDetail = 'name' | 'message' | 'stack';
41
+ /** Keys always redacted (case-insensitive): credentials, session data and personal identifiers. */
42
+ declare const DEFAULT_REDACT_KEYS: readonly string[];
43
+ /** Keys whose values are IP addresses, masked when `maskIp` is on. */
44
+ declare const IP_LOG_KEYS: readonly string[];
45
+ /**
46
+ * Masks one IP (IPv4 keeps the first three octets, IPv6 the first three
47
+ * groups) or every entry of a comma-separated list such as
48
+ * `x-forwarded-for`. Anything that is not an IP becomes `'[redacted]'`.
49
+ */
50
+ declare function maskIp(value: string): string;
51
+ interface RedactOptions {
52
+ /** Extra keys (case-insensitive) replaced by `'[redacted]'`, added to `DEFAULT_REDACT_KEYS`. */
53
+ redact?: readonly string[];
54
+ /** Masks values under `IP_LOG_KEYS` (IPv4 → `/24`, IPv6 → `/48`). Default `true`. */
55
+ maskIp?: boolean;
56
+ /** How much of an `Error` is kept. Default `'message'`. */
57
+ errorDetail?: ErrorDetail;
58
+ }
59
+ /**
60
+ * Returns a function that copies a value with `DEFAULT_REDACT_KEYS` (plus
61
+ * `redact`) replaced by `'[redacted]'` at any depth, IP keys masked, errors
62
+ * reduced per `errorDetail`, cycles as `'[circular]'` and values nested deeper
63
+ * than `MAX_LOG_DEPTH` (counting the root's fields as level 0) as
64
+ * `'[truncated]'`. Inputs are never mutated.
65
+ */
66
+ declare function createRedactor(options?: RedactOptions): (value: unknown) => unknown;
67
+
68
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
69
+ interface LogRecord {
70
+ level: LogLevel;
71
+ time: number;
72
+ msg: string;
73
+ [key: string]: unknown;
74
+ }
75
+ /** Receives one serialized JSON line per log call. */
76
+ type LogSink = (line: string) => void;
77
+ interface LoggerOptions {
78
+ /** Minimum level written. Default `'info'`. */
79
+ level?: LogLevel;
80
+ /** Fields merged into every record. */
81
+ base?: Record<string, unknown>;
82
+ /** Default `console.log`. */
83
+ sink?: LogSink;
84
+ /**
85
+ * Extra keys (case-insensitive) replaced by `'[redacted]'`, added to
86
+ * `DEFAULT_REDACT_KEYS`. Applied at any depth (objects and arrays) up to
87
+ * `MAX_LOG_DEPTH`; deeper values become `'[truncated]'` and cycles
88
+ * `'[circular]'`. Objects with `toJSON` (Date, URL) are kept; inputs are
89
+ * never mutated.
90
+ */
91
+ redact?: readonly string[];
92
+ /** Masks values under `IP_LOG_KEYS` (IPv4 → `/24`, IPv6 → `/48`). Default `true`. */
93
+ maskIp?: boolean;
94
+ /**
95
+ * How much of an `Error` is written: `'name'`, `'message'` (default) or
96
+ * `'stack'`. Stacks reveal paths and code: enable `'stack'` only outside
97
+ * production. Messages may carry user data; use `'name'` when they can.
98
+ */
99
+ errorDetail?: ErrorDetail;
100
+ /** Clock in milliseconds. Default `Date.now`. */
101
+ now?: () => number;
102
+ }
103
+ interface Logger {
104
+ debug(msg: string, fields?: Record<string, unknown>): void;
105
+ info(msg: string, fields?: Record<string, unknown>): void;
106
+ warn(msg: string, fields?: Record<string, unknown>): void;
107
+ error(msg: string, fields?: Record<string, unknown>): void;
108
+ /** A logger that adds `bindings` to every record (per-call fields still win). */
109
+ child(bindings: Record<string, unknown>): Logger;
110
+ }
111
+ /**
112
+ * Structured JSON logger: one JSON object per call, written to `sink`.
113
+ * Runtime-agnostic. Redacts `DEFAULT_REDACT_KEYS` (plus `redact`) at any
114
+ * depth and masks IPs by default.
115
+ */
116
+ declare function createLogger(options?: LoggerOptions): Logger;
117
+
118
+ /** W3C trace identity of a span (OpenTelemetry `SpanContext`). */
119
+ interface SpanContextLike {
120
+ readonly traceId: string;
121
+ readonly spanId: string;
122
+ readonly traceFlags: number;
123
+ readonly isRemote?: boolean;
124
+ }
125
+ /** Structural subset of an OpenTelemetry `Span`; a real OTel span satisfies it. */
126
+ interface SpanLike {
127
+ setAttribute(key: string, value: unknown): void;
128
+ setStatus?(status: {
129
+ code: number;
130
+ message?: string;
131
+ }): void;
132
+ recordException?(error: unknown): void;
133
+ /** Present on real OTel spans; used to propagate `traceparent` downstream. */
134
+ spanContext?(): SpanContextLike;
135
+ end(): void;
136
+ }
137
+ /** Options of one span (subset of OpenTelemetry `SpanOptions`). */
138
+ interface SpanOptionsLike {
139
+ attributes?: Record<string, unknown>;
140
+ /** OpenTelemetry `SpanKind` (`1` = SERVER). */
141
+ kind?: number;
142
+ links?: readonly {
143
+ readonly context: SpanContextLike;
144
+ }[];
145
+ }
146
+ /** Structural subset of an OpenTelemetry `Tracer` (e.g. `trace.getTracer('app')`). */
147
+ interface TracerLike {
148
+ /** `context` is the parent OTel `Context`, passed through untouched. */
149
+ startSpan(name: string, options?: SpanOptionsLike, context?: unknown): SpanLike;
150
+ }
151
+ interface TracingOptions {
152
+ /** Without a tracer every span is a no-op and `enabled` is `false`. */
153
+ tracer?: TracerLike;
154
+ /** Attributes passed to every `startSpan` call. */
155
+ attributes?: Record<string, unknown>;
156
+ /**
157
+ * What a failed span records. `'message'` (default) calls `recordException`
158
+ * and puts the message in the status; `'name'` only sets `error.type`, so
159
+ * messages that may carry personal data never reach the trace backend.
160
+ */
161
+ errorDetail?: 'name' | 'message';
162
+ }
163
+ /** Per-span options of `RuntimeTracer.span`. */
164
+ interface SpanStartOptions extends SpanOptionsLike {
165
+ /** Parent OTel `Context` (e.g. from `propagation.extract`). */
166
+ context?: unknown;
167
+ }
168
+ interface RuntimeTracer {
169
+ /** Runs `fn` inside a span; the span always ends, errors propagate unchanged. */
170
+ span<T>(name: string, fn: (span: SpanLike) => T | Promise<T>, options?: SpanStartOptions): Promise<T>;
171
+ readonly enabled: boolean;
172
+ }
173
+ /** OpenTelemetry hooks without an SDK dependency: pass any tracer that matches `TracerLike`. */
174
+ declare function createRuntimeTracer(options?: TracingOptions): RuntimeTracer;
175
+ /** Parses a W3C `traceparent` header; `undefined` when absent or invalid (then a new trace starts). */
176
+ declare function parseTraceparent(header: string | null | undefined): SpanContextLike | undefined;
177
+ /** `traceparent` value for an outgoing request; `undefined` for an invalid (e.g. no-op) span context. */
178
+ declare function formatTraceparent(context: SpanContextLike): string | undefined;
179
+ /** Value an OpenTelemetry attribute may hold. */
180
+ type AttributeValue = string | number | boolean | readonly (string | number | boolean)[];
181
+ interface AttributeRedactorOptions extends Omit<RedactOptions, 'errorDetail'> {
182
+ /**
183
+ * Field paths whose values never reach a span (e.g. the `pii`/`health`/
184
+ * `secret` paths of a route). An attribute matches by full path or by its
185
+ * last segment, case-insensitive: `'profile.email'` hides `user.email` too.
186
+ */
187
+ sensitive?: readonly string[];
188
+ }
189
+ /**
190
+ * Returns a function that turns free-form attributes into flat OpenTelemetry
191
+ * attributes: `createRedactor` rules first (default keys, IP masking), then
192
+ * every `sensitive` field becomes `'[redacted]'`. Nested objects flatten to
193
+ * dotted keys; arrays of objects become JSON; `null`, `undefined` and
194
+ * functions are dropped.
195
+ */
196
+ declare function createAttributeRedactor(options?: AttributeRedactorOptions): (attributes: Record<string, unknown>) => Record<string, AttributeValue>;
197
+
198
+ export { DEFAULT_REDACT_KEYS, IP_LOG_KEYS, createAttributeRedactor, createLogger, createMemoryStorage, createRedactor, createRuntimeTracer, formatTraceparent, maskIp, namespaced, parseTraceparent };
199
+ export type { AttributeRedactorOptions, AttributeValue, ErrorDetail, LogLevel, LogRecord, LogSink, Logger, LoggerOptions, MemoryStorageOptions, RedactOptions, RuntimeTracer, SpanContextLike, SpanLike, SpanOptionsLike, SpanStartOptions, Storage, StorageEntryOptions, TracerLike, TracingOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,314 @@
1
+ function expiryFor(options, now) {
2
+ const ttlMs = options?.ttlMs;
3
+ if (ttlMs === void 0) return void 0;
4
+ if (!Number.isFinite(ttlMs) || ttlMs < 0) {
5
+ throw new RangeError(`ttlMs must be a finite number >= 0, received ${String(ttlMs)}`);
6
+ }
7
+ return now() + ttlMs;
8
+ }
9
+ function createMemoryStorage(options = {}) {
10
+ const now = options.now ?? Date.now;
11
+ const entries = /* @__PURE__ */ new Map();
12
+ function live(key) {
13
+ const entry = entries.get(key);
14
+ if (entry === void 0) return void 0;
15
+ if (entry.expiresAt !== void 0 && now() >= entry.expiresAt) {
16
+ entries.delete(key);
17
+ return void 0;
18
+ }
19
+ return entry;
20
+ }
21
+ return {
22
+ async get(key) {
23
+ return live(key)?.value;
24
+ },
25
+ async set(key, value, entryOptions) {
26
+ entries.set(key, { value, expiresAt: expiryFor(entryOptions, now) });
27
+ },
28
+ async delete(key) {
29
+ return live(key) !== void 0 && entries.delete(key);
30
+ },
31
+ async clear() {
32
+ entries.clear();
33
+ },
34
+ async keys(prefix = "") {
35
+ const out = [];
36
+ for (const key of [...entries.keys()]) {
37
+ if (key.startsWith(prefix) && live(key) !== void 0) out.push(key);
38
+ }
39
+ return out;
40
+ }
41
+ };
42
+ }
43
+ function namespaced(storage, prefix) {
44
+ if (prefix === "") throw new TypeError("namespaced(): prefix must be a non-empty string");
45
+ const head = prefix + ":";
46
+ const scoped = {
47
+ get: (key) => storage.get(head + key),
48
+ set: (key, value, options) => storage.set(head + key, value, options),
49
+ delete: (key) => storage.delete(head + key),
50
+ async clear() {
51
+ if (storage.keys === void 0) {
52
+ throw new TypeError("namespaced(): clear() requires a storage that implements keys()");
53
+ }
54
+ const keys = await storage.keys(head);
55
+ await Promise.all(keys.map((key) => storage.delete(key)));
56
+ }
57
+ };
58
+ const listKeys = storage.keys;
59
+ if (listKeys !== void 0) {
60
+ scoped.keys = async (subPrefix = "") => {
61
+ const keys = await listKeys.call(storage, head + subPrefix);
62
+ return keys.map((key) => key.slice(head.length));
63
+ };
64
+ }
65
+ return scoped;
66
+ }
67
+
68
+ const DEFAULT_REDACT_KEYS = [
69
+ "authorization",
70
+ "proxy-authorization",
71
+ "cookie",
72
+ "set-cookie",
73
+ "x-csrf-token",
74
+ "x-api-key",
75
+ "x-auth-token",
76
+ "password",
77
+ "senha",
78
+ "token",
79
+ "secret",
80
+ "cpf"
81
+ ];
82
+ const IP_LOG_KEYS = ["cf-connecting-ip", "x-forwarded-for", "x-real-ip", "ip"];
83
+ const MAX_LOG_DEPTH = 8;
84
+ function maskIpv6(ip) {
85
+ const halves = ip.split("::");
86
+ if (halves.length > 2) return void 0;
87
+ const left = halves[0] === void 0 || halves[0] === "" ? [] : halves[0].split(":");
88
+ const right = halves[1] === void 0 || halves[1] === "" ? [] : halves[1].split(":");
89
+ const groups = halves.length === 2 ? [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right] : left;
90
+ if (groups.length !== 8 || groups.some((group) => !/^[0-9a-f]{1,4}$/i.test(group))) return void 0;
91
+ return groups.slice(0, 3).join(":") + "::";
92
+ }
93
+ function maskIp(value) {
94
+ return value.split(",").map((part) => {
95
+ const ip = part.trim();
96
+ if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(ip)) return ip.slice(0, ip.lastIndexOf(".")) + ".0";
97
+ return maskIpv6(ip) ?? "[redacted]";
98
+ }).join(", ");
99
+ }
100
+ const REDACTED$1 = "[redacted]";
101
+ const IP_KEYS = new Set(IP_LOG_KEYS);
102
+ function errorFields(error, detail) {
103
+ const out = { name: error.name };
104
+ if (detail !== "name") out["message"] = error.message;
105
+ if (detail === "stack" && error.stack !== void 0) out["stack"] = error.stack;
106
+ return out;
107
+ }
108
+ function cleanField(key, value, config, ancestors, depth) {
109
+ const lower = key.toLowerCase();
110
+ if (config.redact.has(lower)) return REDACTED$1;
111
+ if (config.maskIp && IP_KEYS.has(lower) && typeof value === "string") return maskIp(value);
112
+ return cleanValue(value, config, ancestors, depth);
113
+ }
114
+ function cleanValue(value, config, ancestors, depth) {
115
+ if (typeof value === "bigint") return value.toString();
116
+ if (value === null || typeof value !== "object") return value;
117
+ if (depth >= MAX_LOG_DEPTH) return "[truncated]";
118
+ if (ancestors.has(value)) return "[circular]";
119
+ const source = value instanceof Error ? errorFields(value, config.errorDetail) : value;
120
+ if (!Array.isArray(source) && typeof source.toJSON === "function") return source;
121
+ ancestors.add(value);
122
+ try {
123
+ if (Array.isArray(source)) return source.map((inner) => cleanValue(inner, config, ancestors, depth + 1));
124
+ const out = {};
125
+ for (const [key, inner] of Object.entries(source)) out[key] = cleanField(key, inner, config, ancestors, depth + 1);
126
+ return out;
127
+ } finally {
128
+ ancestors.delete(value);
129
+ }
130
+ }
131
+ function createRedactor(options = {}) {
132
+ const config = {
133
+ redact: new Set([...DEFAULT_REDACT_KEYS, ...options.redact ?? []].map((key) => key.toLowerCase())),
134
+ maskIp: options.maskIp !== false,
135
+ errorDetail: options.errorDetail ?? "message"
136
+ };
137
+ return (value) => cleanValue(value, config, /* @__PURE__ */ new Set(), -1);
138
+ }
139
+
140
+ const LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
141
+ const RESERVED = /* @__PURE__ */ new Set(["level", "time", "msg"]);
142
+ function write(config, bindings, level, msg, fields) {
143
+ if (LEVELS[level] < config.threshold) return;
144
+ try {
145
+ const record = { level, time: config.now(), msg };
146
+ const merged = fields === void 0 ? bindings : { ...bindings, ...fields };
147
+ const cleaned = config.clean(merged);
148
+ for (const [key, value] of Object.entries(cleaned)) {
149
+ if (!RESERVED.has(key)) record[key] = value;
150
+ }
151
+ let line;
152
+ try {
153
+ line = JSON.stringify(record);
154
+ } catch {
155
+ line = JSON.stringify({ level, time: record.time, msg, logError: "unserializable fields" });
156
+ }
157
+ config.sink(line);
158
+ } catch {
159
+ }
160
+ }
161
+ function build(config, bindings) {
162
+ return {
163
+ debug: (msg, fields) => write(config, bindings, "debug", msg, fields),
164
+ info: (msg, fields) => write(config, bindings, "info", msg, fields),
165
+ warn: (msg, fields) => write(config, bindings, "warn", msg, fields),
166
+ error: (msg, fields) => write(config, bindings, "error", msg, fields),
167
+ child: (extra) => build(config, { ...bindings, ...extra })
168
+ };
169
+ }
170
+ function createLogger(options = {}) {
171
+ const level = options.level ?? "info";
172
+ if (!Object.hasOwn(LEVELS, level)) {
173
+ throw new RangeError(`createLogger(): unknown level ${JSON.stringify(level)}`);
174
+ }
175
+ const config = {
176
+ threshold: LEVELS[level],
177
+ sink: options.sink ?? ((line) => console.log(line)),
178
+ clean: createRedactor(options),
179
+ now: options.now ?? Date.now
180
+ };
181
+ return build(config, { ...options.base });
182
+ }
183
+
184
+ const STATUS_ERROR = 2;
185
+ const NOOP_SPAN = {
186
+ setAttribute() {
187
+ },
188
+ setStatus() {
189
+ },
190
+ recordException() {
191
+ },
192
+ end() {
193
+ }
194
+ };
195
+ function safely(action) {
196
+ try {
197
+ action();
198
+ } catch {
199
+ }
200
+ }
201
+ function errorType(error) {
202
+ return error instanceof Error ? error.name : typeof error;
203
+ }
204
+ function describeError(error) {
205
+ if (error instanceof Error) return error.message;
206
+ try {
207
+ return String(error);
208
+ } catch {
209
+ return "unknown error";
210
+ }
211
+ }
212
+ function createRuntimeTracer(options = {}) {
213
+ const tracer = options.tracer;
214
+ const defaults = options.attributes;
215
+ const errorDetail = options.errorDetail ?? "message";
216
+ if (tracer === void 0) {
217
+ return {
218
+ enabled: false,
219
+ span: async (_name, fn) => fn(NOOP_SPAN)
220
+ };
221
+ }
222
+ const active = tracer;
223
+ function start(name, init) {
224
+ const { context, ...rest } = init ?? {};
225
+ const attributes = defaults === void 0 && rest.attributes === void 0 ? void 0 : { ...defaults, ...rest.attributes };
226
+ const spanOptions = attributes === void 0 ? rest : { ...rest, attributes };
227
+ try {
228
+ if (context !== void 0) return active.startSpan(name, spanOptions, context);
229
+ return Object.keys(spanOptions).length === 0 ? active.startSpan(name) : active.startSpan(name, spanOptions);
230
+ } catch {
231
+ return NOOP_SPAN;
232
+ }
233
+ }
234
+ function fail(span, error) {
235
+ if (errorDetail === "name") {
236
+ safely(() => span.setAttribute("error.type", errorType(error)));
237
+ safely(() => span.setStatus?.({ code: STATUS_ERROR }));
238
+ return;
239
+ }
240
+ safely(() => span.recordException?.(error));
241
+ safely(() => span.setStatus?.({ code: STATUS_ERROR, message: describeError(error) }));
242
+ }
243
+ return {
244
+ enabled: true,
245
+ async span(name, fn, init) {
246
+ const span = start(name, init);
247
+ try {
248
+ return await fn(span);
249
+ } catch (error) {
250
+ fail(span, error);
251
+ throw error;
252
+ } finally {
253
+ safely(() => span.end());
254
+ }
255
+ }
256
+ };
257
+ }
258
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
259
+ const ZERO_TRACE = "0".repeat(32);
260
+ const ZERO_SPAN = "0".repeat(16);
261
+ function parseTraceparent(header) {
262
+ const match = TRACEPARENT.exec((header ?? "").trim());
263
+ if (match === null) return void 0;
264
+ const [, version, traceId, spanId, flags, extra] = match;
265
+ if (version === void 0 || traceId === void 0 || spanId === void 0 || flags === void 0) return void 0;
266
+ if (version === "ff" || version === "00" && extra !== void 0) return void 0;
267
+ if (traceId === ZERO_TRACE || spanId === ZERO_SPAN) return void 0;
268
+ return { traceId, spanId, traceFlags: parseInt(flags, 16), isRemote: true };
269
+ }
270
+ function formatTraceparent(context) {
271
+ const header = `00-${context.traceId}-${context.spanId}-${(context.traceFlags & 255).toString(16).padStart(2, "0")}`;
272
+ return parseTraceparent(header) === void 0 ? void 0 : header;
273
+ }
274
+ const REDACTED = "[redacted]";
275
+ function isPrimitive(value) {
276
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
277
+ }
278
+ function lastSegment(path) {
279
+ return path.slice(path.lastIndexOf(".") + 1);
280
+ }
281
+ function createAttributeRedactor(options = {}) {
282
+ const redact = createRedactor({ ...options, errorDetail: "name" });
283
+ const paths = new Set((options.sensitive ?? []).map((path) => path.toLowerCase()));
284
+ const names = new Set([...paths].map(lastSegment).concat([...DEFAULT_REDACT_KEYS, ...options.redact ?? []].map((key) => key.toLowerCase())));
285
+ function hidden(key) {
286
+ const lower = key.toLowerCase();
287
+ if (names.has(lastSegment(lower))) return true;
288
+ for (const path of paths) if (lower === path || lower.endsWith("." + path)) return true;
289
+ return false;
290
+ }
291
+ function scrub(value) {
292
+ if (Array.isArray(value)) return value.map(scrub);
293
+ if (typeof value !== "object" || value === null) return value;
294
+ const out = {};
295
+ for (const [key, inner] of Object.entries(value)) out[key] = hidden(key) ? REDACTED : scrub(inner);
296
+ return out;
297
+ }
298
+ function flatten(prefix, value, out) {
299
+ for (const [key, inner] of Object.entries(value)) {
300
+ const name = prefix === "" ? key : prefix + "." + key;
301
+ if (hidden(name)) out[name] = REDACTED;
302
+ else if (isPrimitive(inner)) out[name] = inner;
303
+ else if (Array.isArray(inner)) out[name] = inner.every(isPrimitive) ? inner : JSON.stringify(scrub(inner));
304
+ else if (typeof inner === "object" && inner !== null) flatten(name, inner, out);
305
+ }
306
+ }
307
+ return (attributes) => {
308
+ const out = {};
309
+ flatten("", redact(attributes), out);
310
+ return out;
311
+ };
312
+ }
313
+
314
+ export { DEFAULT_REDACT_KEYS, IP_LOG_KEYS, createAttributeRedactor, createLogger, createMemoryStorage, createRedactor, createRuntimeTracer, formatTraceparent, maskIp, namespaced, parseTraceparent };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@tupik/infra",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.1.0",
4
+ "description": "Universal production building blocks for Tupik: pluggable storage, structured JSON logger and duck-typed OpenTelemetry tracing.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "tupik",
8
+ "typescript",
9
+ "web-framework",
10
+ "storage",
11
+ "logger",
12
+ "opentelemetry",
13
+ "tracing"
14
+ ],
15
+ "homepage": "https://github.com/CodeHamper/tupikjs/tree/main/packages/infra#readme",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/CodeHamper/tupikjs.git",
19
+ "directory": "packages/infra"
20
+ },
21
+ "bugs": {
22
+ "url": "https://github.com/CodeHamper/tupikjs/issues"
23
+ },
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.mjs"
36
+ }
37
+ },
38
+ "engines": {
39
+ "node": ">=22.12"
40
+ },
41
+ "dependencies": {},
42
+ "devDependencies": {
43
+ "typescript": "^5.6.0",
44
+ "unbuild": "^3.0.0",
45
+ "vitest": "^2.1.0"
46
+ },
47
+ "scripts": {
48
+ "build": "unbuild",
49
+ "typecheck": "tsc --noEmit",
50
+ "test": "vitest run"
51
+ }
6
52
  }