autotel 4.1.0 → 4.2.1
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/auto.cjs +5 -3
- package/dist/auto.cjs.map +1 -1
- package/dist/auto.js +3 -3
- package/dist/auto.js.map +1 -1
- package/dist/chunk-C_NdSu1c.cjs +34 -0
- package/dist/correlation-id.cjs +1 -1
- package/dist/correlation-id.d.cts.map +1 -1
- package/dist/correlation-id.d.ts.map +1 -1
- package/dist/correlation-id.js +1 -1
- package/dist/decorators.cjs +1 -1
- package/dist/decorators.js +1 -1
- package/dist/{event-ByBTV9M2.js → event-531asIM6.js} +4 -4
- package/dist/{event-ByBTV9M2.js.map → event-531asIM6.js.map} +1 -1
- package/dist/{event-BhHREDJk.cjs → event-CcZYwp50.cjs} +4 -4
- package/dist/{event-BhHREDJk.cjs.map → event-CcZYwp50.cjs.map} +1 -1
- package/dist/event.cjs +1 -1
- package/dist/event.js +1 -1
- package/dist/{functional-zpzNLhky.cjs → functional-C8B0Qa7o.cjs} +10 -7
- package/dist/functional-C8B0Qa7o.cjs.map +1 -0
- package/dist/{functional-DtI0u4vx.js → functional-r-AUIRy_.js} +9 -9
- package/dist/functional-r-AUIRy_.js.map +1 -0
- package/dist/functional.cjs +1 -1
- package/dist/functional.js +1 -1
- package/dist/http.cjs +1 -1
- package/dist/http.js +1 -1
- package/dist/index.cjs +15 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -14
- package/dist/index.js.map +1 -1
- package/dist/{init-D-jnNMix.js → init-BS2JVkrL.js} +2 -2
- package/dist/{init-D-jnNMix.js.map → init-BS2JVkrL.js.map} +1 -1
- package/dist/{init-BX7AmFRl.cjs → init-BXiuPK6j.cjs} +3 -3
- package/dist/{init-BX7AmFRl.cjs.map → init-BXiuPK6j.cjs.map} +1 -1
- package/dist/instrumentation.cjs +2 -2
- package/dist/instrumentation.js +2 -2
- package/dist/logger.cjs +236 -8
- package/dist/logger.cjs.map +1 -0
- package/dist/messaging.cjs +1 -1
- package/dist/messaging.js +1 -1
- package/dist/{node-require-DF5QBX6z.cjs → node-require-CZ_PU448.cjs} +6 -4
- package/dist/node-require-CZ_PU448.cjs.map +1 -0
- package/dist/{node-require-Db1oDpLj.js → node-require-vROmTeJ8.js} +5 -5
- package/dist/node-require-vROmTeJ8.js.map +1 -0
- package/dist/{operation-context-C-2hmmtP.js → operation-context-CKBoA4Qy.js} +3 -3
- package/dist/operation-context-CKBoA4Qy.js.map +1 -0
- package/dist/{operation-context-n4_obUwq.cjs → operation-context-D6LDf4W_.cjs} +3 -1
- package/dist/operation-context-D6LDf4W_.cjs.map +1 -0
- package/dist/register.cjs +3 -1
- package/dist/register.cjs.map +1 -1
- package/dist/register.js +2 -2
- package/dist/register.js.map +1 -1
- package/dist/semantic-helpers.cjs +1 -1
- package/dist/semantic-helpers.js +1 -1
- package/dist/{stable-hash-Cg5cT34Q.js → stable-hash-ChFBIhNt.js} +3 -3
- package/dist/stable-hash-ChFBIhNt.js.map +1 -0
- package/dist/{stable-hash-BNTMrmdB.cjs → stable-hash-brKISGf1.cjs} +4 -2
- package/dist/stable-hash-brKISGf1.cjs.map +1 -0
- package/dist/trace-context-Cijqoi6e.d.cts.map +1 -1
- package/dist/trace-context-Cijqoi6e.d.ts.map +1 -1
- package/dist/trace-helpers.cjs +1 -1
- package/dist/trace-helpers.js +1 -1
- package/dist/{track-wc0HafS_.js → track-COUuU48p.js} +5 -5
- package/dist/track-COUuU48p.js.map +1 -0
- package/dist/{track-D59FfpL0.cjs → track-Cb3Q4QmS.cjs} +4 -2
- package/dist/track-Cb3Q4QmS.cjs.map +1 -0
- package/dist/validate.cjs +1 -1
- package/dist/validate.js +1 -1
- package/dist/webhook.cjs +1 -1
- package/dist/webhook.js +1 -1
- package/dist/workflow-distributed.cjs +1 -1
- package/dist/workflow-distributed.js +1 -1
- package/dist/workflow.cjs +3 -1
- package/dist/workflow.cjs.map +1 -1
- package/dist/workflow.d.cts.map +1 -1
- package/dist/workflow.d.ts.map +1 -1
- package/dist/workflow.js +3 -3
- package/dist/workflow.js.map +1 -1
- package/dist/yaml-config.cjs +233 -4
- package/dist/yaml-config.cjs.map +1 -0
- package/dist/yaml-config.d.cts.map +1 -1
- package/dist/yaml-config.d.ts.map +1 -1
- package/dist/yaml-config.js +8 -7
- package/dist/yaml-config.js.map +1 -1
- package/package.json +1 -2
- package/dist/functional-DtI0u4vx.js.map +0 -1
- package/dist/functional-zpzNLhky.cjs.map +0 -1
- package/dist/logger-thMPLpOG.cjs +0 -487
- package/dist/logger-thMPLpOG.cjs.map +0 -1
- package/dist/node-require-DF5QBX6z.cjs.map +0 -1
- package/dist/node-require-Db1oDpLj.js.map +0 -1
- package/dist/operation-context-C-2hmmtP.js.map +0 -1
- package/dist/operation-context-n4_obUwq.cjs.map +0 -1
- package/dist/stable-hash-BNTMrmdB.cjs.map +0 -1
- package/dist/stable-hash-Cg5cT34Q.js.map +0 -1
- package/dist/track-D59FfpL0.cjs.map +0 -1
- package/dist/track-wc0HafS_.js.map +0 -1
- package/dist/yaml-config-Ck2uB0Dp.cjs +0 -273
- package/dist/yaml-config-Ck2uB0Dp.cjs.map +0 -1
- package/src/attribute-redacting-processor.test.ts +0 -763
- package/src/attribute-redacting-processor.ts +0 -621
- package/src/attributes/attachers.ts +0 -161
- package/src/attributes/builders.ts +0 -529
- package/src/attributes/domains.ts +0 -42
- package/src/attributes/index.ts +0 -81
- package/src/attributes/registry.ts +0 -323
- package/src/attributes/types.ts +0 -211
- package/src/attributes/utils.ts +0 -64
- package/src/attributes/validators.ts +0 -266
- package/src/attributes.test.ts +0 -292
- package/src/auto.ts +0 -67
- package/src/autotel-logger.test.ts +0 -548
- package/src/autotel-logger.ts +0 -364
- package/src/baggage-span-processor.test.ts +0 -202
- package/src/baggage-span-processor.ts +0 -100
- package/src/business-baggage.test.ts +0 -500
- package/src/business-baggage.ts +0 -669
- package/src/circuit-breaker.test.ts +0 -341
- package/src/circuit-breaker.ts +0 -184
- package/src/config.test.ts +0 -94
- package/src/config.ts +0 -172
- package/src/correlated-events.test.ts +0 -151
- package/src/correlated-events.ts +0 -47
- package/src/correlation-id.test.ts +0 -163
- package/src/correlation-id.ts +0 -206
- package/src/db.test.ts +0 -252
- package/src/db.ts +0 -447
- package/src/decorators.test.ts +0 -153
- package/src/decorators.ts +0 -188
- package/src/define-event.test.ts +0 -41
- package/src/define-event.ts +0 -58
- package/src/devtools.ts +0 -60
- package/src/drain-pipeline.test.ts +0 -68
- package/src/drain-pipeline.ts +0 -199
- package/src/drain-toolkit.test.ts +0 -113
- package/src/drain-toolkit.ts +0 -129
- package/src/enricher-toolkit.test.ts +0 -67
- package/src/enricher-toolkit.ts +0 -79
- package/src/enrichers.test.ts +0 -150
- package/src/enrichers.ts +0 -145
- package/src/env-config.test.ts +0 -323
- package/src/env-config.ts +0 -309
- package/src/error-catalog.test.ts +0 -133
- package/src/error-catalog.ts +0 -262
- package/src/event-queue.test.ts +0 -864
- package/src/event-queue.ts +0 -699
- package/src/event-subscriber.ts +0 -262
- package/src/event-testing.ts +0 -197
- package/src/event.test.ts +0 -1104
- package/src/event.ts +0 -988
- package/src/events-config.ts +0 -235
- package/src/exporters.ts +0 -165
- package/src/filtering-span-processor.test.ts +0 -281
- package/src/filtering-span-processor.ts +0 -111
- package/src/flatten-attributes.test.ts +0 -76
- package/src/flatten-attributes.ts +0 -80
- package/src/functional.strict-types.typecheck.ts +0 -53
- package/src/functional.test.ts +0 -1464
- package/src/functional.ts +0 -2539
- package/src/functional.types.test.ts +0 -135
- package/src/hook.mjs +0 -15
- package/src/http.test.ts +0 -485
- package/src/http.ts +0 -424
- package/src/index.ts +0 -433
- package/src/init-auto-redactor.test.ts +0 -53
- package/src/init-redactor.test.ts +0 -8
- package/src/init.customization.test.ts +0 -665
- package/src/init.integrations.test.ts +0 -399
- package/src/init.openllmetry.test.ts +0 -194
- package/src/init.protocol.test.ts +0 -215
- package/src/init.ts +0 -2439
- package/src/instrumentation.test.ts +0 -108
- package/src/instrumentation.ts +0 -319
- package/src/logger.test.ts +0 -125
- package/src/logger.ts +0 -341
- package/src/messaging-adapters.test.ts +0 -595
- package/src/messaging-adapters.ts +0 -583
- package/src/messaging-testing.test.ts +0 -573
- package/src/messaging-testing.ts +0 -935
- package/src/messaging.test.ts +0 -1646
- package/src/messaging.ts +0 -2245
- package/src/metric-helpers.ts +0 -47
- package/src/metric-testing.ts +0 -197
- package/src/metric.ts +0 -446
- package/src/metrics.test.ts +0 -241
- package/src/node-require.ts +0 -123
- package/src/operation-context.ts +0 -93
- package/src/parse-error.test.ts +0 -73
- package/src/parse-error.ts +0 -112
- package/src/posthog-logs.test.ts +0 -115
- package/src/posthog-logs.ts +0 -77
- package/src/pretty-console-exporter.test.ts +0 -545
- package/src/pretty-console-exporter.ts +0 -413
- package/src/pretty-log-formatter.test.ts +0 -123
- package/src/pretty-log-formatter.ts +0 -210
- package/src/processors/canonical-log-line-processor.test.ts +0 -523
- package/src/processors/canonical-log-line-processor.ts +0 -396
- package/src/processors.ts +0 -152
- package/src/rate-limiter.test.ts +0 -199
- package/src/rate-limiter.ts +0 -98
- package/src/redact-values.test.ts +0 -90
- package/src/redact-values.ts +0 -34
- package/src/register.ts +0 -37
- package/src/request-logger.test.ts +0 -545
- package/src/request-logger.ts +0 -342
- package/src/sampling.test.ts +0 -1060
- package/src/sampling.ts +0 -737
- package/src/security-schema.test.ts +0 -45
- package/src/security-schema.ts +0 -107
- package/src/semantic-conventions.ts +0 -15
- package/src/semantic-helpers.test.ts +0 -226
- package/src/semantic-helpers.ts +0 -438
- package/src/shutdown.test.ts +0 -364
- package/src/shutdown.ts +0 -246
- package/src/span-name-normalizer.test.ts +0 -377
- package/src/span-name-normalizer.ts +0 -213
- package/src/stable-hash.ts +0 -27
- package/src/structured-error.test.ts +0 -191
- package/src/structured-error.ts +0 -157
- package/src/stub.integration.test.ts +0 -361
- package/src/tail-sampling-processor.test.ts +0 -230
- package/src/tail-sampling-processor.ts +0 -55
- package/src/test-span-collector.test.ts +0 -234
- package/src/test-span-collector.ts +0 -150
- package/src/testing.ts +0 -705
- package/src/trace-context.test.ts +0 -73
- package/src/trace-context.ts +0 -567
- package/src/trace-helpers.new.test.ts +0 -278
- package/src/trace-helpers.test.ts +0 -290
- package/src/trace-helpers.ts +0 -710
- package/src/trace-hybrid.test.ts +0 -42
- package/src/trace-hybrid.ts +0 -37
- package/src/tracer-provider.test.ts +0 -183
- package/src/tracer-provider.ts +0 -266
- package/src/track.test.ts +0 -154
- package/src/track.ts +0 -216
- package/src/validate.test.ts +0 -287
- package/src/validate.ts +0 -307
- package/src/validation-attributes.ts +0 -43
- package/src/validation.test.ts +0 -330
- package/src/validation.ts +0 -246
- package/src/variable-name-inference.test.ts +0 -178
- package/src/variable-name-inference.ts +0 -242
- package/src/webhook.test.ts +0 -649
- package/src/webhook.ts +0 -637
- package/src/workflow-distributed.test.ts +0 -786
- package/src/workflow-distributed.ts +0 -916
- package/src/workflow.async-safety.integration.test.ts +0 -345
- package/src/workflow.test.ts +0 -647
- package/src/workflow.ts +0 -810
- package/src/yaml-config.test.ts +0 -373
- package/src/yaml-config.ts +0 -351
package/dist/logger-thMPLpOG.cjs
DELETED
|
@@ -1,487 +0,0 @@
|
|
|
1
|
-
const require_config = require('./config.cjs');
|
|
2
|
-
let _opentelemetry_api = require("@opentelemetry/api");
|
|
3
|
-
|
|
4
|
-
//#region src/autotel-logger.ts
|
|
5
|
-
/**
|
|
6
|
-
* Zero-dependency structured logger for autotel
|
|
7
|
-
*
|
|
8
|
-
* This logger provides:
|
|
9
|
-
* - Structured JSON logging (production) or pretty print (development)
|
|
10
|
-
* - Auto trace context injection (traceId, spanId, correlationId)
|
|
11
|
-
* - Dynamic log level control (per-request via OTel context)
|
|
12
|
-
* - Level support (debug, info, warn, error, none)
|
|
13
|
-
* - Zero additional dependencies (uses @opentelemetry/api, already a dep)
|
|
14
|
-
*
|
|
15
|
-
* Uses Pino-compatible signature supporting both patterns:
|
|
16
|
-
* - `log.info('simple message')` - string-only
|
|
17
|
-
* - `log.info({ userId: '123' }, 'message')` - object first with optional message
|
|
18
|
-
*
|
|
19
|
-
* Used as the default fallback when users don't provide Pino/Bunyan.
|
|
20
|
-
* Can also be used directly: import { createBuiltinLogger } from 'autotel/logger'
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* ```typescript
|
|
24
|
-
* import { createBuiltinLogger, runWithLogLevel } from 'autotel/logger';
|
|
25
|
-
*
|
|
26
|
-
* const log = createBuiltinLogger('my-service');
|
|
27
|
-
*
|
|
28
|
-
* // Simple message (no metadata)
|
|
29
|
-
* log.info('Server started');
|
|
30
|
-
*
|
|
31
|
-
* // With metadata (Pino-style: object first, message second)
|
|
32
|
-
* log.info({ userId: '123' }, 'User created');
|
|
33
|
-
* // Output: {"level":"info","service":"my-service","msg":"User created","userId":"123","traceId":"..."}
|
|
34
|
-
*
|
|
35
|
-
* // Dynamic log level per-request
|
|
36
|
-
* runWithLogLevel('debug', () => {
|
|
37
|
-
* log.debug('This will log even if default level is "info"');
|
|
38
|
-
* });
|
|
39
|
-
* ```
|
|
40
|
-
*/
|
|
41
|
-
/**
|
|
42
|
-
* Context key for storing active log level (enables per-request log levels)
|
|
43
|
-
*/
|
|
44
|
-
const LOG_LEVEL_KEY = (0, _opentelemetry_api.createContextKey)("autotel-log-level");
|
|
45
|
-
/**
|
|
46
|
-
* Get the active log level from context (if set)
|
|
47
|
-
* Falls back to undefined if no log level is set in context
|
|
48
|
-
*/
|
|
49
|
-
function getActiveLogLevel() {
|
|
50
|
-
return _opentelemetry_api.context.active().getValue(LOG_LEVEL_KEY);
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Run a function with a specific log level
|
|
54
|
-
* The log level is stored in OpenTelemetry context and applies to all logger calls within the callback
|
|
55
|
-
*
|
|
56
|
-
* @example
|
|
57
|
-
* ```typescript
|
|
58
|
-
* // Enable debug logging for a specific request
|
|
59
|
-
* runWithLogLevel('debug', () => {
|
|
60
|
-
* log.debug('This will be logged');
|
|
61
|
-
* processRequest();
|
|
62
|
-
* });
|
|
63
|
-
*
|
|
64
|
-
* // Disable logging temporarily
|
|
65
|
-
* runWithLogLevel('none', () => {
|
|
66
|
-
* log.info('This will NOT be logged');
|
|
67
|
-
* });
|
|
68
|
-
* ```
|
|
69
|
-
*/
|
|
70
|
-
function runWithLogLevel(level, callback) {
|
|
71
|
-
const ctx = _opentelemetry_api.context.active().setValue(LOG_LEVEL_KEY, level);
|
|
72
|
-
return _opentelemetry_api.context.with(ctx, callback);
|
|
73
|
-
}
|
|
74
|
-
/**
|
|
75
|
-
* Get current trace context from active span
|
|
76
|
-
* Returns null if no active span exists
|
|
77
|
-
*/
|
|
78
|
-
function getTraceContextInternal() {
|
|
79
|
-
const span = _opentelemetry_api.trace.getActiveSpan();
|
|
80
|
-
if (!span) return null;
|
|
81
|
-
const ctx = span.spanContext();
|
|
82
|
-
return {
|
|
83
|
-
traceId: ctx.traceId,
|
|
84
|
-
spanId: ctx.spanId,
|
|
85
|
-
correlationId: ctx.traceId.slice(0, 16)
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
/**
|
|
89
|
-
* Helper to get trace context (useful for BYOL - Bring Your Own Logger)
|
|
90
|
-
*
|
|
91
|
-
* @example
|
|
92
|
-
* ```typescript
|
|
93
|
-
* import bunyan from 'bunyan';
|
|
94
|
-
* import { getTraceContext } from 'autotel/logger';
|
|
95
|
-
*
|
|
96
|
-
* const bunyanLogger = bunyan.createLogger({ name: 'myapp' });
|
|
97
|
-
* const ctx = getTraceContext();
|
|
98
|
-
* bunyanLogger.info({ ...ctx, email: 'test@example.com' }, 'Creating user');
|
|
99
|
-
* ```
|
|
100
|
-
*/
|
|
101
|
-
function getTraceContext() {
|
|
102
|
-
return getTraceContextInternal();
|
|
103
|
-
}
|
|
104
|
-
/**
|
|
105
|
-
* Create a lightweight structured logger
|
|
106
|
-
*
|
|
107
|
-
* @param service - Service name for logging
|
|
108
|
-
* @param options - Optional configuration
|
|
109
|
-
*
|
|
110
|
-
* @example
|
|
111
|
-
* ```typescript
|
|
112
|
-
* const log = createBuiltinLogger('user-service');
|
|
113
|
-
*
|
|
114
|
-
* log.info('Creating user', { email: 'test@example.com' });
|
|
115
|
-
* // Output: {"level":"info","service":"user-service","msg":"Creating user",
|
|
116
|
-
* // "email":"test@example.com","traceId":"...","spanId":"..."}
|
|
117
|
-
*
|
|
118
|
-
* // Dynamic log level control per-request
|
|
119
|
-
* runWithLogLevel('debug', () => {
|
|
120
|
-
* log.debug('This will be logged even if logger was created with level: "info"');
|
|
121
|
-
* });
|
|
122
|
-
* ```
|
|
123
|
-
*/
|
|
124
|
-
function createBuiltinLogger(service, options) {
|
|
125
|
-
const defaultLevel = options?.level || "info";
|
|
126
|
-
const pretty = options?.pretty || false;
|
|
127
|
-
const levelPriority = {
|
|
128
|
-
none: -1,
|
|
129
|
-
debug: 0,
|
|
130
|
-
info: 1,
|
|
131
|
-
warn: 2,
|
|
132
|
-
error: 3
|
|
133
|
-
};
|
|
134
|
-
const shouldLog = (level) => {
|
|
135
|
-
const activeLevel = getActiveLogLevel() ?? defaultLevel;
|
|
136
|
-
if (activeLevel === "none") return false;
|
|
137
|
-
return levelPriority[level] >= levelPriority[activeLevel];
|
|
138
|
-
};
|
|
139
|
-
const log = (level, msg, attrs) => {
|
|
140
|
-
if (!shouldLog(level)) return;
|
|
141
|
-
const ctx = getTraceContextInternal();
|
|
142
|
-
const logEntry = {
|
|
143
|
-
level,
|
|
144
|
-
service,
|
|
145
|
-
msg,
|
|
146
|
-
...attrs,
|
|
147
|
-
...ctx,
|
|
148
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
149
|
-
};
|
|
150
|
-
if (pretty) {
|
|
151
|
-
const traceInfo = ctx ? ` [${ctx.traceId.slice(0, 8)}.../${ctx.spanId.slice(0, 8)}...]` : "";
|
|
152
|
-
console.log(`[${level.toUpperCase()}]${traceInfo} ${service}: ${msg}`, attrs || "");
|
|
153
|
-
} else console.log(JSON.stringify(logEntry));
|
|
154
|
-
};
|
|
155
|
-
const createLogMethod = (level) => {
|
|
156
|
-
return (extraOrMessage, message) => {
|
|
157
|
-
if (typeof extraOrMessage === "string") if (message !== void 0 && typeof message === "object") {
|
|
158
|
-
if (process.env.NODE_ENV !== "production") console.warn(`[autotel] Legacy logger pattern detected: logger.${level}('message', metadata). Autotel recommends Pino signature: logger.${level}({ ...metadata }, 'message'). Auto-swapping arguments for compatibility.`);
|
|
159
|
-
log(level, extraOrMessage, message);
|
|
160
|
-
} else log(level, extraOrMessage);
|
|
161
|
-
else log(level, message || "", extraOrMessage);
|
|
162
|
-
};
|
|
163
|
-
};
|
|
164
|
-
return {
|
|
165
|
-
info: createLogMethod("info"),
|
|
166
|
-
warn: createLogMethod("warn"),
|
|
167
|
-
debug: createLogMethod("debug"),
|
|
168
|
-
error: (extraOrMessage, message) => {
|
|
169
|
-
if (typeof extraOrMessage === "string") {
|
|
170
|
-
if (message instanceof Error) {
|
|
171
|
-
if (process.env.NODE_ENV !== "production") console.warn("[autotel] Legacy logger pattern detected: logger.error('message', error). Autotel recommends Pino signature: logger.error({ err: error }, 'message'). Auto-swapping arguments for compatibility.");
|
|
172
|
-
log("error", extraOrMessage, {
|
|
173
|
-
error: message.message,
|
|
174
|
-
stack: message.stack,
|
|
175
|
-
name: message.name
|
|
176
|
-
});
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
if (message !== void 0 && typeof message === "object") {
|
|
180
|
-
if (process.env.NODE_ENV !== "production") console.warn("[autotel] Legacy logger pattern detected: logger.error('message', metadata). Autotel recommends Pino signature: logger.error({ ...metadata }, 'message'). Auto-swapping arguments for compatibility.");
|
|
181
|
-
const { err, ...rest } = message;
|
|
182
|
-
let errorAttrs = rest;
|
|
183
|
-
if (err instanceof Error) errorAttrs = {
|
|
184
|
-
error: err.message,
|
|
185
|
-
stack: err.stack,
|
|
186
|
-
name: err.name,
|
|
187
|
-
...rest
|
|
188
|
-
};
|
|
189
|
-
else if (err !== void 0) errorAttrs = {
|
|
190
|
-
err,
|
|
191
|
-
...rest
|
|
192
|
-
};
|
|
193
|
-
log("error", extraOrMessage, errorAttrs);
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
log("error", extraOrMessage);
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
199
|
-
const { err, ...rest } = extraOrMessage;
|
|
200
|
-
let errorAttrs = rest;
|
|
201
|
-
if (err instanceof Error) errorAttrs = {
|
|
202
|
-
error: err.message,
|
|
203
|
-
stack: err.stack,
|
|
204
|
-
name: err.name,
|
|
205
|
-
...rest
|
|
206
|
-
};
|
|
207
|
-
else if (err !== void 0) errorAttrs = {
|
|
208
|
-
err,
|
|
209
|
-
...rest
|
|
210
|
-
};
|
|
211
|
-
log("error", message || "", errorAttrs);
|
|
212
|
-
}
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
/**
|
|
216
|
-
* Pino-like factory function for creating an autotel logger
|
|
217
|
-
*
|
|
218
|
-
* @example
|
|
219
|
-
* ```typescript
|
|
220
|
-
* import { autotelLogger } from 'autotel/logger';
|
|
221
|
-
*
|
|
222
|
-
* const log = autotelLogger();
|
|
223
|
-
*
|
|
224
|
-
* // Simple message
|
|
225
|
-
* log.info('Server started');
|
|
226
|
-
*
|
|
227
|
-
* // With metadata (Pino-style: object first, message second)
|
|
228
|
-
* log.info({ userId: '123' }, 'User created');
|
|
229
|
-
*
|
|
230
|
-
* // With options
|
|
231
|
-
* const devLog = autotelLogger({ service: 'my-app', level: 'debug', pretty: true });
|
|
232
|
-
* ```
|
|
233
|
-
*/
|
|
234
|
-
function autotelLogger(options) {
|
|
235
|
-
return createBuiltinLogger(options?.service || "app", {
|
|
236
|
-
level: options?.level,
|
|
237
|
-
pretty: options?.pretty
|
|
238
|
-
});
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
//#endregion
|
|
242
|
-
//#region src/logger.ts
|
|
243
|
-
/**
|
|
244
|
-
* Logger types and utilities for autotel
|
|
245
|
-
*
|
|
246
|
-
* **Zero-Config Option:** Don't provide a logger to `init()` and autotel uses
|
|
247
|
-
* a built-in structured JSON logger with automatic trace context injection.
|
|
248
|
-
*
|
|
249
|
-
* **BYOL (Bring Your Own Logger):** Pass Pino or Bunyan to `init()` for
|
|
250
|
-
* automatic instrumentation with trace context and OTLP log export.
|
|
251
|
-
*
|
|
252
|
-
* ## Logger Signature
|
|
253
|
-
*
|
|
254
|
-
* Autotel v2.10+ uses **Pino's signature**: `logger.info({ metadata }, 'message')`.
|
|
255
|
-
*
|
|
256
|
-
* ### Backward Compatibility
|
|
257
|
-
*
|
|
258
|
-
* The built-in logger auto-detects legacy Winston-style calls and swaps arguments:
|
|
259
|
-
* ```typescript
|
|
260
|
-
* // Legacy (auto-detected and handled)
|
|
261
|
-
* logger.info('User created', { userId: '123' });
|
|
262
|
-
* // → Internally treated as: logger.info({ userId: '123' }, 'User created')
|
|
263
|
-
* // → Logs warning in development, works silently in production
|
|
264
|
-
* ```
|
|
265
|
-
*
|
|
266
|
-
* ### Recommended Usage
|
|
267
|
-
*
|
|
268
|
-
* ```typescript
|
|
269
|
-
* // ✅ Pino-style (preferred)
|
|
270
|
-
* logger.info({ userId: '123' }, 'User created');
|
|
271
|
-
*
|
|
272
|
-
* // ✅ Simple message (no metadata)
|
|
273
|
-
* logger.info('Server started');
|
|
274
|
-
* ```
|
|
275
|
-
*
|
|
276
|
-
* **Note:** If you BYOL (bring your own logger), it must use Pino signature.
|
|
277
|
-
* Winston and other `(message, meta)` loggers are NOT compatible.
|
|
278
|
-
* For Winston, use `@opentelemetry/instrumentation-winston` instead.
|
|
279
|
-
*
|
|
280
|
-
* @example Zero-config (uses built-in logger)
|
|
281
|
-
* ```typescript
|
|
282
|
-
* import { init } from 'autotel';
|
|
283
|
-
*
|
|
284
|
-
* init({ service: 'my-app' });
|
|
285
|
-
* // Internal logs: {"level":"info","service":"my-app","msg":"...","traceId":"..."}
|
|
286
|
-
* ```
|
|
287
|
-
*
|
|
288
|
-
* @example Using built-in logger directly
|
|
289
|
-
* ```typescript
|
|
290
|
-
* import { createBuiltinLogger, runWithLogLevel } from 'autotel/logger';
|
|
291
|
-
*
|
|
292
|
-
* const log = createBuiltinLogger('my-service');
|
|
293
|
-
*
|
|
294
|
-
* // Simple message (no metadata)
|
|
295
|
-
* log.info('Server started');
|
|
296
|
-
*
|
|
297
|
-
* // With metadata (Pino-style: object first, message second)
|
|
298
|
-
* log.info({ userId: '123' }, 'User created');
|
|
299
|
-
* // Output: {"level":"info","service":"my-service","msg":"User created","userId":"123","traceId":"..."}
|
|
300
|
-
*
|
|
301
|
-
* // Dynamic log level per-request
|
|
302
|
-
* runWithLogLevel('debug', () => {
|
|
303
|
-
* log.debug('Debug info for this request only');
|
|
304
|
-
* });
|
|
305
|
-
* ```
|
|
306
|
-
*
|
|
307
|
-
* @example Using Pino (recommended for production, auto-instrumented)
|
|
308
|
-
* ```typescript
|
|
309
|
-
* import pino from 'pino'; // npm install pino
|
|
310
|
-
* import { init } from 'autotel';
|
|
311
|
-
*
|
|
312
|
-
* const logger = pino({ level: 'info' });
|
|
313
|
-
* init({ service: 'my-app', logger });
|
|
314
|
-
*
|
|
315
|
-
* // Logs automatically include traceId/spanId and export via OTLP!
|
|
316
|
-
* logger.info({ userId: '123' }, 'User created');
|
|
317
|
-
* ```
|
|
318
|
-
*
|
|
319
|
-
* @example Using Bunyan (auto-instrumented, same signature as Pino)
|
|
320
|
-
* ```typescript
|
|
321
|
-
* import bunyan from 'bunyan'; // npm install bunyan @opentelemetry/instrumentation-bunyan
|
|
322
|
-
* import { init } from 'autotel';
|
|
323
|
-
* import { BunyanInstrumentation } from '@opentelemetry/instrumentation-bunyan';
|
|
324
|
-
*
|
|
325
|
-
* const logger = bunyan.createLogger({ name: 'my-app' });
|
|
326
|
-
* init({
|
|
327
|
-
* service: 'my-app',
|
|
328
|
-
* logger,
|
|
329
|
-
* instrumentations: [new BunyanInstrumentation()]
|
|
330
|
-
* });
|
|
331
|
-
* ```
|
|
332
|
-
*
|
|
333
|
-
* @example Custom logger (MUST use Pino-compatible signature)
|
|
334
|
-
* ```typescript
|
|
335
|
-
* // ⚠️ Your custom logger MUST accept (object, message?) signature
|
|
336
|
-
* const logger = {
|
|
337
|
-
* info: (extra, msg) => console.log(msg || '', extra),
|
|
338
|
-
* warn: (extra, msg) => console.warn(msg || '', extra),
|
|
339
|
-
* error: (extra, msg) => console.error(msg || '', extra),
|
|
340
|
-
* debug: (extra, msg) => console.debug(msg || '', extra),
|
|
341
|
-
* };
|
|
342
|
-
* init({ service: 'my-app', logger });
|
|
343
|
-
* ```
|
|
344
|
-
*
|
|
345
|
-
* @example BYOL helper: inject trace context into any logger
|
|
346
|
-
* ```typescript
|
|
347
|
-
* import bunyan from 'bunyan';
|
|
348
|
-
* import { getTraceContext } from 'autotel/logger';
|
|
349
|
-
*
|
|
350
|
-
* const bunyanLogger = bunyan.createLogger({ name: 'myapp' });
|
|
351
|
-
* const ctx = getTraceContext();
|
|
352
|
-
* bunyanLogger.info({ ...ctx, userId: '123' }, 'Creating user');
|
|
353
|
-
* ```
|
|
354
|
-
*/
|
|
355
|
-
/**
|
|
356
|
-
* Log level constants
|
|
357
|
-
*/
|
|
358
|
-
const LOG_LEVEL = {
|
|
359
|
-
DEBUG: "debug",
|
|
360
|
-
INFO: "info",
|
|
361
|
-
WARN: "warn",
|
|
362
|
-
ERROR: "error"
|
|
363
|
-
};
|
|
364
|
-
/**
|
|
365
|
-
* TS5+ Standard Decorator for logging and tracing operations
|
|
366
|
-
* Uses TC39 Stage 3 decorator syntax
|
|
367
|
-
*
|
|
368
|
-
* This is the traditional per-method decorator approach.
|
|
369
|
-
* For zero-boilerplate solution, see @Instrumented class decorator.
|
|
370
|
-
*
|
|
371
|
-
* @example
|
|
372
|
-
* // Simple usage (Pino-style: object first, message second)
|
|
373
|
-
* class OrderService {
|
|
374
|
-
* constructor(private readonly deps: { log: Logger }) {}
|
|
375
|
-
*
|
|
376
|
-
* @LoggedOperation('order.create')
|
|
377
|
-
* async createOrder(data: CreateOrderData) {
|
|
378
|
-
* // ✅ Correct Pino-style logging
|
|
379
|
-
* this.deps.log.info({ orderId: data.id }, 'Creating order');
|
|
380
|
-
* }
|
|
381
|
-
* }
|
|
382
|
-
*
|
|
383
|
-
* // Advanced usage (future-proof for options)
|
|
384
|
-
* @LoggedOperation({ operationName: 'order.create' })
|
|
385
|
-
* async createOrder(data: CreateOrderData) { }
|
|
386
|
-
*/
|
|
387
|
-
function LoggedOperation(operationNameOrOptions) {
|
|
388
|
-
const operationName = typeof operationNameOrOptions === "string" ? operationNameOrOptions : operationNameOrOptions.operationName;
|
|
389
|
-
return function(originalMethod, context) {
|
|
390
|
-
const methodName = String(context.name);
|
|
391
|
-
return async function(...args) {
|
|
392
|
-
const log = this.deps?.log;
|
|
393
|
-
const startTime = performance.now();
|
|
394
|
-
return require_config.getConfig().tracer.startActiveSpan(operationName, async (span) => {
|
|
395
|
-
try {
|
|
396
|
-
log?.info({
|
|
397
|
-
operation: operationName,
|
|
398
|
-
method: methodName,
|
|
399
|
-
args
|
|
400
|
-
}, "Operation started");
|
|
401
|
-
const result = await originalMethod.apply(this, args);
|
|
402
|
-
const duration = performance.now() - startTime;
|
|
403
|
-
log?.info({
|
|
404
|
-
operation: operationName,
|
|
405
|
-
method: methodName,
|
|
406
|
-
duration
|
|
407
|
-
}, "Operation completed");
|
|
408
|
-
span.setStatus({ code: _opentelemetry_api.SpanStatusCode.OK });
|
|
409
|
-
span.setAttributes({
|
|
410
|
-
"operation.name": operationName,
|
|
411
|
-
"operation.method": methodName,
|
|
412
|
-
"operation.duration": duration,
|
|
413
|
-
"operation.success": true
|
|
414
|
-
});
|
|
415
|
-
return result;
|
|
416
|
-
} catch (error) {
|
|
417
|
-
const duration = performance.now() - startTime;
|
|
418
|
-
log?.error({
|
|
419
|
-
err: error instanceof Error ? error : void 0,
|
|
420
|
-
operation: operationName,
|
|
421
|
-
method: methodName,
|
|
422
|
-
duration
|
|
423
|
-
}, "Operation failed");
|
|
424
|
-
span.setStatus({
|
|
425
|
-
code: _opentelemetry_api.SpanStatusCode.ERROR,
|
|
426
|
-
message: error instanceof Error ? error.message : "Unknown error"
|
|
427
|
-
});
|
|
428
|
-
span.setAttributes({
|
|
429
|
-
"operation.name": operationName,
|
|
430
|
-
"operation.method": methodName,
|
|
431
|
-
"operation.duration": duration,
|
|
432
|
-
"operation.success": false,
|
|
433
|
-
"error.type": error instanceof Error ? error.constructor.name : "Unknown"
|
|
434
|
-
});
|
|
435
|
-
throw error;
|
|
436
|
-
} finally {
|
|
437
|
-
span.end();
|
|
438
|
-
}
|
|
439
|
-
});
|
|
440
|
-
};
|
|
441
|
-
};
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
//#endregion
|
|
445
|
-
Object.defineProperty(exports, 'LOG_LEVEL', {
|
|
446
|
-
enumerable: true,
|
|
447
|
-
get: function () {
|
|
448
|
-
return LOG_LEVEL;
|
|
449
|
-
}
|
|
450
|
-
});
|
|
451
|
-
Object.defineProperty(exports, 'LoggedOperation', {
|
|
452
|
-
enumerable: true,
|
|
453
|
-
get: function () {
|
|
454
|
-
return LoggedOperation;
|
|
455
|
-
}
|
|
456
|
-
});
|
|
457
|
-
Object.defineProperty(exports, 'autotelLogger', {
|
|
458
|
-
enumerable: true,
|
|
459
|
-
get: function () {
|
|
460
|
-
return autotelLogger;
|
|
461
|
-
}
|
|
462
|
-
});
|
|
463
|
-
Object.defineProperty(exports, 'createBuiltinLogger', {
|
|
464
|
-
enumerable: true,
|
|
465
|
-
get: function () {
|
|
466
|
-
return createBuiltinLogger;
|
|
467
|
-
}
|
|
468
|
-
});
|
|
469
|
-
Object.defineProperty(exports, 'getActiveLogLevel', {
|
|
470
|
-
enumerable: true,
|
|
471
|
-
get: function () {
|
|
472
|
-
return getActiveLogLevel;
|
|
473
|
-
}
|
|
474
|
-
});
|
|
475
|
-
Object.defineProperty(exports, 'getTraceContext', {
|
|
476
|
-
enumerable: true,
|
|
477
|
-
get: function () {
|
|
478
|
-
return getTraceContext;
|
|
479
|
-
}
|
|
480
|
-
});
|
|
481
|
-
Object.defineProperty(exports, 'runWithLogLevel', {
|
|
482
|
-
enumerable: true,
|
|
483
|
-
get: function () {
|
|
484
|
-
return runWithLogLevel;
|
|
485
|
-
}
|
|
486
|
-
});
|
|
487
|
-
//# sourceMappingURL=logger-thMPLpOG.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"logger-thMPLpOG.cjs","names":["api_context","trace","extra","getConfig","SpanStatusCode"],"sources":["../src/autotel-logger.ts","../src/logger.ts"],"sourcesContent":["/**\n * Zero-dependency structured logger for autotel\n *\n * This logger provides:\n * - Structured JSON logging (production) or pretty print (development)\n * - Auto trace context injection (traceId, spanId, correlationId)\n * - Dynamic log level control (per-request via OTel context)\n * - Level support (debug, info, warn, error, none)\n * - Zero additional dependencies (uses @opentelemetry/api, already a dep)\n *\n * Uses Pino-compatible signature supporting both patterns:\n * - `log.info('simple message')` - string-only\n * - `log.info({ userId: '123' }, 'message')` - object first with optional message\n *\n * Used as the default fallback when users don't provide Pino/Bunyan.\n * Can also be used directly: import { createBuiltinLogger } from 'autotel/logger'\n *\n * @example\n * ```typescript\n * import { createBuiltinLogger, runWithLogLevel } from 'autotel/logger';\n *\n * const log = createBuiltinLogger('my-service');\n *\n * // Simple message (no metadata)\n * log.info('Server started');\n *\n * // With metadata (Pino-style: object first, message second)\n * log.info({ userId: '123' }, 'User created');\n * // Output: {\"level\":\"info\",\"service\":\"my-service\",\"msg\":\"User created\",\"userId\":\"123\",\"traceId\":\"...\"}\n *\n * // Dynamic log level per-request\n * runWithLogLevel('debug', () => {\n * log.debug('This will log even if default level is \"info\"');\n * });\n * ```\n */\n\nimport {\n trace,\n context as api_context,\n createContextKey,\n} from '@opentelemetry/api';\nimport type { Logger } from './logger';\n\nexport type BuiltinLogLevel = 'debug' | 'info' | 'warn' | 'error' | 'none';\n\n/**\n * Context key for storing active log level (enables per-request log levels)\n */\nconst LOG_LEVEL_KEY = createContextKey('autotel-log-level');\n\n/**\n * Get the active log level from context (if set)\n * Falls back to undefined if no log level is set in context\n */\nexport function getActiveLogLevel(): BuiltinLogLevel | undefined {\n return api_context.active().getValue(LOG_LEVEL_KEY) as\n | BuiltinLogLevel\n | undefined;\n}\n\n/**\n * Run a function with a specific log level\n * The log level is stored in OpenTelemetry context and applies to all logger calls within the callback\n *\n * @example\n * ```typescript\n * // Enable debug logging for a specific request\n * runWithLogLevel('debug', () => {\n * log.debug('This will be logged');\n * processRequest();\n * });\n *\n * // Disable logging temporarily\n * runWithLogLevel('none', () => {\n * log.info('This will NOT be logged');\n * });\n * ```\n */\nexport function runWithLogLevel<T>(\n level: BuiltinLogLevel,\n callback: () => T,\n): T {\n const ctx = api_context.active().setValue(LOG_LEVEL_KEY, level);\n return api_context.with(ctx, callback);\n}\n\n/**\n * Get current trace context from active span\n * Returns null if no active span exists\n */\nfunction getTraceContextInternal(): {\n traceId: string;\n spanId: string;\n correlationId: string;\n} | null {\n const span = trace.getActiveSpan();\n if (!span) return null;\n\n const ctx = span.spanContext();\n return {\n traceId: ctx.traceId,\n spanId: ctx.spanId,\n correlationId: ctx.traceId.slice(0, 16), // First 16 chars for grouping\n };\n}\n\n/**\n * Helper to get trace context (useful for BYOL - Bring Your Own Logger)\n *\n * @example\n * ```typescript\n * import bunyan from 'bunyan';\n * import { getTraceContext } from 'autotel/logger';\n *\n * const bunyanLogger = bunyan.createLogger({ name: 'myapp' });\n * const ctx = getTraceContext();\n * bunyanLogger.info({ ...ctx, email: 'test@example.com' }, 'Creating user');\n * ```\n */\nexport function getTraceContext() {\n return getTraceContextInternal();\n}\n\nexport interface BuiltinLoggerOptions {\n /** Minimum log level. Default: 'info' */\n level?: BuiltinLogLevel;\n /** Pretty print for development. Default: false (JSON output) */\n pretty?: boolean;\n}\n\n/**\n * Create a lightweight structured logger\n *\n * @param service - Service name for logging\n * @param options - Optional configuration\n *\n * @example\n * ```typescript\n * const log = createBuiltinLogger('user-service');\n *\n * log.info('Creating user', { email: 'test@example.com' });\n * // Output: {\"level\":\"info\",\"service\":\"user-service\",\"msg\":\"Creating user\",\n * // \"email\":\"test@example.com\",\"traceId\":\"...\",\"spanId\":\"...\"}\n *\n * // Dynamic log level control per-request\n * runWithLogLevel('debug', () => {\n * log.debug('This will be logged even if logger was created with level: \"info\"');\n * });\n * ```\n */\nexport function createBuiltinLogger(\n service: string,\n options?: BuiltinLoggerOptions,\n): Logger {\n const defaultLevel = options?.level || 'info';\n const pretty = options?.pretty || false;\n\n const levelPriority: Record<BuiltinLogLevel, number> = {\n none: -1,\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n const shouldLog = (level: BuiltinLogLevel): boolean => {\n // Priority: context level > options level > 'info' default\n const activeLevel = getActiveLogLevel() ?? defaultLevel;\n\n // 'none' means suppress all logging\n if (activeLevel === 'none') return false;\n\n return levelPriority[level] >= levelPriority[activeLevel];\n };\n\n const log = (\n level: 'info' | 'error' | 'warn' | 'debug',\n msg: string,\n attrs?: Record<string, unknown>,\n ) => {\n if (!shouldLog(level)) return;\n\n const ctx = getTraceContextInternal();\n const logEntry: Record<string, unknown> = {\n level,\n service,\n msg,\n ...attrs,\n ...ctx, // Auto-inject traceId, spanId, correlationId\n timestamp: new Date().toISOString(),\n };\n\n if (pretty) {\n // Pretty print for development\n const traceInfo = ctx\n ? ` [${ctx.traceId.slice(0, 8)}.../${ctx.spanId.slice(0, 8)}...]`\n : '';\n console.log(\n `[${level.toUpperCase()}]${traceInfo} ${service}: ${msg}`,\n attrs || '',\n );\n } else {\n // Structured JSON for production\n console.log(JSON.stringify(logEntry));\n }\n };\n\n // Pino-compatible signature: supports both:\n // - logger.info('message') - string-only\n // - logger.info({ extra }, 'message') - Pino style with metadata\n // Also auto-detects and handles legacy Winston-style: logger.info('message', { extra })\n const createLogMethod = (level: 'info' | 'warn' | 'debug') => {\n return (\n extraOrMessage: Record<string, unknown> | string,\n message?: string | Record<string, unknown>,\n ) => {\n if (typeof extraOrMessage === 'string') {\n // First arg is string - could be:\n // 1. String-only: logger.info('message')\n // 2. Legacy Winston-style: logger.info('message', { extra })\n if (message !== undefined && typeof message === 'object') {\n // Legacy Winston-style detected - auto-swap for backward compatibility\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[autotel] Legacy logger pattern detected: logger.${level}('message', metadata). ` +\n `Autotel recommends Pino signature: logger.${level}({ ...metadata }, 'message'). ` +\n `Auto-swapping arguments for compatibility.`,\n );\n }\n // Swap: treat first arg as message, second as metadata\n log(level, extraOrMessage, message as Record<string, unknown>);\n } else {\n // Pure string-only call: logger.info('message')\n log(level, extraOrMessage);\n }\n } else {\n // Pino style: logger.info({ extra }, 'message')\n log(level, (message as string) || '', extraOrMessage);\n }\n };\n };\n\n return {\n info: createLogMethod('info'),\n warn: createLogMethod('warn'),\n debug: createLogMethod('debug'),\n\n error: (\n extraOrMessage: Record<string, unknown> | string,\n message?: string | Record<string, unknown> | Error,\n ) => {\n if (typeof extraOrMessage === 'string') {\n // First arg is string - could be:\n // 1. String-only: logger.error('message')\n // 2. Legacy: logger.error('message', error) - Error as second arg\n // 3. Legacy: logger.error('message', { extra }) - object as second arg\n\n // Handle legacy logger.error('message', error) pattern\n if (message instanceof Error) {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[autotel] Legacy logger pattern detected: logger.error('message', error). ` +\n `Autotel recommends Pino signature: logger.error({ err: error }, 'message'). ` +\n `Auto-swapping arguments for compatibility.`,\n );\n }\n log('error', extraOrMessage, {\n error: message.message,\n stack: message.stack,\n name: message.name,\n });\n return;\n }\n\n // Handle legacy logger.error('message', { extra }) pattern\n if (message !== undefined && typeof message === 'object') {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[autotel] Legacy logger pattern detected: logger.error('message', metadata). ` +\n `Autotel recommends Pino signature: logger.error({ ...metadata }, 'message'). ` +\n `Auto-swapping arguments for compatibility.`,\n );\n }\n // Swap: treat first arg as message, second as metadata (handle err extraction)\n const extra = message as Record<string, unknown>;\n const { err, ...rest } = extra as Record<string, unknown> & {\n err?: unknown;\n };\n let errorAttrs: Record<string, unknown> = rest;\n if (err instanceof Error) {\n errorAttrs = {\n error: err.message,\n stack: err.stack,\n name: err.name,\n ...rest,\n };\n } else if (err !== undefined) {\n errorAttrs = { err, ...rest };\n }\n log('error', extraOrMessage, errorAttrs);\n return;\n }\n\n // Pure string-only call: logger.error('message')\n log('error', extraOrMessage);\n return;\n }\n\n // Pino style: logger.error({ err, ...extra }, 'message')\n // Extract err from extra if present (Pino convention)\n const { err, ...rest } = extraOrMessage as Record<string, unknown> & {\n err?: unknown;\n };\n let errorAttrs: Record<string, unknown> = rest;\n if (err instanceof Error) {\n // err is an Error - extract message, stack, name for structured logging\n errorAttrs = {\n error: err.message,\n stack: err.stack,\n name: err.name,\n ...rest,\n };\n } else if (err !== undefined) {\n // err is not an Error but exists - preserve it as-is\n errorAttrs = {\n err,\n ...rest,\n };\n }\n log('error', (message as string) || '', errorAttrs);\n },\n };\n}\n\n/**\n * Pino-like factory function for creating an autotel logger\n *\n * @example\n * ```typescript\n * import { autotelLogger } from 'autotel/logger';\n *\n * const log = autotelLogger();\n *\n * // Simple message\n * log.info('Server started');\n *\n * // With metadata (Pino-style: object first, message second)\n * log.info({ userId: '123' }, 'User created');\n *\n * // With options\n * const devLog = autotelLogger({ service: 'my-app', level: 'debug', pretty: true });\n * ```\n */\nexport function autotelLogger(options?: {\n service?: string;\n level?: BuiltinLogLevel;\n pretty?: boolean;\n}): Logger {\n return createBuiltinLogger(options?.service || 'app', {\n level: options?.level,\n pretty: options?.pretty,\n });\n}\n","/**\n * Logger types and utilities for autotel\n *\n * **Zero-Config Option:** Don't provide a logger to `init()` and autotel uses\n * a built-in structured JSON logger with automatic trace context injection.\n *\n * **BYOL (Bring Your Own Logger):** Pass Pino or Bunyan to `init()` for\n * automatic instrumentation with trace context and OTLP log export.\n *\n * ## Logger Signature\n *\n * Autotel v2.10+ uses **Pino's signature**: `logger.info({ metadata }, 'message')`.\n *\n * ### Backward Compatibility\n *\n * The built-in logger auto-detects legacy Winston-style calls and swaps arguments:\n * ```typescript\n * // Legacy (auto-detected and handled)\n * logger.info('User created', { userId: '123' });\n * // → Internally treated as: logger.info({ userId: '123' }, 'User created')\n * // → Logs warning in development, works silently in production\n * ```\n *\n * ### Recommended Usage\n *\n * ```typescript\n * // ✅ Pino-style (preferred)\n * logger.info({ userId: '123' }, 'User created');\n *\n * // ✅ Simple message (no metadata)\n * logger.info('Server started');\n * ```\n *\n * **Note:** If you BYOL (bring your own logger), it must use Pino signature.\n * Winston and other `(message, meta)` loggers are NOT compatible.\n * For Winston, use `@opentelemetry/instrumentation-winston` instead.\n *\n * @example Zero-config (uses built-in logger)\n * ```typescript\n * import { init } from 'autotel';\n *\n * init({ service: 'my-app' });\n * // Internal logs: {\"level\":\"info\",\"service\":\"my-app\",\"msg\":\"...\",\"traceId\":\"...\"}\n * ```\n *\n * @example Using built-in logger directly\n * ```typescript\n * import { createBuiltinLogger, runWithLogLevel } from 'autotel/logger';\n *\n * const log = createBuiltinLogger('my-service');\n *\n * // Simple message (no metadata)\n * log.info('Server started');\n *\n * // With metadata (Pino-style: object first, message second)\n * log.info({ userId: '123' }, 'User created');\n * // Output: {\"level\":\"info\",\"service\":\"my-service\",\"msg\":\"User created\",\"userId\":\"123\",\"traceId\":\"...\"}\n *\n * // Dynamic log level per-request\n * runWithLogLevel('debug', () => {\n * log.debug('Debug info for this request only');\n * });\n * ```\n *\n * @example Using Pino (recommended for production, auto-instrumented)\n * ```typescript\n * import pino from 'pino'; // npm install pino\n * import { init } from 'autotel';\n *\n * const logger = pino({ level: 'info' });\n * init({ service: 'my-app', logger });\n *\n * // Logs automatically include traceId/spanId and export via OTLP!\n * logger.info({ userId: '123' }, 'User created');\n * ```\n *\n * @example Using Bunyan (auto-instrumented, same signature as Pino)\n * ```typescript\n * import bunyan from 'bunyan'; // npm install bunyan @opentelemetry/instrumentation-bunyan\n * import { init } from 'autotel';\n * import { BunyanInstrumentation } from '@opentelemetry/instrumentation-bunyan';\n *\n * const logger = bunyan.createLogger({ name: 'my-app' });\n * init({\n * service: 'my-app',\n * logger,\n * instrumentations: [new BunyanInstrumentation()]\n * });\n * ```\n *\n * @example Custom logger (MUST use Pino-compatible signature)\n * ```typescript\n * // ⚠️ Your custom logger MUST accept (object, message?) signature\n * const logger = {\n * info: (extra, msg) => console.log(msg || '', extra),\n * warn: (extra, msg) => console.warn(msg || '', extra),\n * error: (extra, msg) => console.error(msg || '', extra),\n * debug: (extra, msg) => console.debug(msg || '', extra),\n * };\n * init({ service: 'my-app', logger });\n * ```\n *\n * @example BYOL helper: inject trace context into any logger\n * ```typescript\n * import bunyan from 'bunyan';\n * import { getTraceContext } from 'autotel/logger';\n *\n * const bunyanLogger = bunyan.createLogger({ name: 'myapp' });\n * const ctx = getTraceContext();\n * bunyanLogger.info({ ...ctx, userId: '123' }, 'Creating user');\n * ```\n */\n\nimport { SpanStatusCode } from '@opentelemetry/api';\nimport { getConfig } from './config';\n\n// ============================================================================\n// Logger Types\n// ============================================================================\n\n/**\n * Log level constants\n */\nexport const LOG_LEVEL = {\n DEBUG: 'debug',\n INFO: 'info',\n WARN: 'warn',\n ERROR: 'error',\n} as const;\n\nexport type LogLevel = (typeof LOG_LEVEL)[keyof typeof LOG_LEVEL];\n\n/**\n * Logger configuration (for reference - not needed with BYOL approach)\n */\nexport interface LoggerConfig {\n service: string;\n level?: LogLevel;\n pretty?: boolean;\n redact?: string[] | false;\n}\n\n/**\n * Pino-compatible log function signature\n *\n * Matches Pino's actual LogFn type which supports:\n * - `(msg: string)` - simple string message\n * - `(obj: object, msg?: string)` - object first with optional message\n *\n * @example\n * ```typescript\n * logger.info('User logged in');\n * logger.info({ userId: '123' }, 'User created');\n * logger.error({ err: error }, 'Operation failed');\n * ```\n */\nexport interface LogFn {\n (msg: string): void;\n (obj: Record<string, unknown>, msg?: string): void;\n}\n\n/**\n * Simple logger interface - Pino/Bunyan-compatible\n *\n * Uses Pino's LogFn signature which supports both:\n * - `logger.info('message')` - simple string message\n * - `logger.info({ extra }, 'message')` - object first with optional message\n *\n * This is compatible with Pino, Bunyan, and any logger following this pattern.\n *\n * @example Using Pino (just works!)\n * ```typescript\n * import pino from 'pino';\n * const logger = pino({ level: 'info' });\n * init({ service: 'my-app', logger });\n * ```\n *\n * @example Direct usage\n * ```typescript\n * logger.info('Simple message');\n * logger.info({ userId: '123' }, 'User created');\n * logger.error({ err: error }, 'Operation failed');\n * ```\n */\nexport interface Logger {\n info: LogFn;\n warn: LogFn;\n error: LogFn;\n debug: LogFn;\n}\n\n/**\n * Alias for Logger interface (backwards compatibility)\n * @deprecated Use Logger instead\n */\nexport type ILogger = Logger;\n\n/**\n * Pino logger type - re-exported for convenience\n *\n * Note: This is a type-only export. To use Pino, install it as a peer dependency:\n * `npm install pino`\n */\nexport type { Logger as PinoLogger } from 'pino';\n\n// ============================================================================\n// LoggedOperation Decorator\n// ============================================================================\n\nexport interface LoggedOperationOptions {\n /** Operation name for tracing (e.g., 'user.createUser') */\n operationName: string;\n}\n\n/**\n * TS5+ Standard Decorator for logging and tracing operations\n * Uses TC39 Stage 3 decorator syntax\n *\n * This is the traditional per-method decorator approach.\n * For zero-boilerplate solution, see @Instrumented class decorator.\n *\n * @example\n * // Simple usage (Pino-style: object first, message second)\n * class OrderService {\n * constructor(private readonly deps: { log: Logger }) {}\n *\n * @LoggedOperation('order.create')\n * async createOrder(data: CreateOrderData) {\n * // ✅ Correct Pino-style logging\n * this.deps.log.info({ orderId: data.id }, 'Creating order');\n * }\n * }\n *\n * // Advanced usage (future-proof for options)\n * @LoggedOperation({ operationName: 'order.create' })\n * async createOrder(data: CreateOrderData) { }\n */\nexport function LoggedOperation(\n operationNameOrOptions: string | LoggedOperationOptions,\n) {\n const operationName =\n typeof operationNameOrOptions === 'string'\n ? operationNameOrOptions\n : operationNameOrOptions.operationName;\n\n return function <This, Args extends unknown[], Return>(\n originalMethod: (this: This, ...args: Args) => Promise<Return>,\n context: ClassMethodDecoratorContext<\n This,\n (this: This, ...args: Args) => Promise<Return>\n >,\n ) {\n const methodName = String(context.name);\n\n return async function (this: This, ...args: Args): Promise<Return> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const log = (this as any).deps?.log;\n const startTime = performance.now();\n\n const config = getConfig();\n const tracer = config.tracer;\n\n return tracer.startActiveSpan(operationName, async (span) => {\n try {\n log?.info(\n {\n operation: operationName,\n method: methodName,\n args,\n },\n 'Operation started',\n );\n\n const result = await originalMethod.apply(this, args);\n\n const duration = performance.now() - startTime;\n log?.info(\n {\n operation: operationName,\n method: methodName,\n duration,\n },\n 'Operation completed',\n );\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n 'operation.name': operationName,\n 'operation.method': methodName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n return result;\n } catch (error) {\n const duration = performance.now() - startTime;\n log?.error(\n {\n err: error instanceof Error ? error : undefined,\n operation: operationName,\n method: methodName,\n duration,\n },\n 'Operation failed',\n );\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : 'Unknown error',\n });\n span.setAttributes({\n 'operation.name': operationName,\n 'operation.method': methodName,\n 'operation.duration': duration,\n 'operation.success': false,\n 'error.type':\n error instanceof Error ? error.constructor.name : 'Unknown',\n });\n\n throw error;\n } finally {\n span.end();\n }\n });\n };\n };\n}\n\n// ============================================================================\n// Built-in Logger (re-exports)\n// ============================================================================\n\nexport {\n autotelLogger,\n createBuiltinLogger,\n runWithLogLevel,\n getTraceContext,\n getActiveLogLevel,\n type BuiltinLogLevel,\n type BuiltinLoggerOptions,\n} from './autotel-logger';\n"],"mappings":"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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"node-require-DF5QBX6z.cjs","names":[],"sources":["../src/node-require.ts"],"sourcesContent":["/**\n * Cross-format require() helper for CJS and ESM compatibility\n *\n * Provides a synchronous `require()` function that works in both:\n * - CJS builds: Uses native `require`\n * - ESM builds: Uses `createRequire(import.meta.url)`\n *\n * This allows optional peer dependencies and dynamic module loading\n * to work synchronously in both module formats.\n */\n\nimport { createRequire } from 'node:module';\n\n// `__filename` is provided by CJS and by esbuild's CJS output wrapper, but\n// is undefined under pure ESM. `import.meta.url` is provided by ESM. Pick\n// whichever is available so the helper works in:\n// - native CJS (autotel's published `.cjs`)\n// - native ESM (autotel's published `.js`)\n// - ESM-bundled-into-CJS by a downstream consumer (e.g. CDK's\n// `aws-lambda-nodejs` → esbuild with `format: cjs`). esbuild rewrites\n// `import.meta` to `{}` in this case, so `createRequire(import.meta.url)`\n// alone collapses to `createRequire(undefined)` and crashes at load.\n// `typeof __filename` does NOT throw when the identifier is undeclared, so\n// the ESM build evaluates the conditional safely.\ndeclare const __filename: string | undefined;\n\n// Build the Node `require` lazily on first use. Calling `createRequire`\n// eagerly at module load crashes in runtimes where neither `__filename` nor\n// `import.meta.url` resolves to a path — e.g. Cloudflare Workers / workerd,\n// where the bundle has no module path and `createRequire(undefined)` throws\n// synchronously at import. Deferring the call keeps merely importing this\n// module (and therefore anything that re-exports it, such as `track`)\n// side-effect-free; Node/CJS/ESM still get a real `require` on first call.\nlet cachedRequire: NodeRequire | undefined;\n\nfunction getNodeRequire(): NodeRequire {\n if (cachedRequire) return cachedRequire;\n const base = typeof __filename === 'string' ? __filename : import.meta.url;\n if (!base) {\n // No module path in this runtime. Surface as a missing-module error so\n // optional lookups via `safeRequire()` degrade gracefully to `undefined`.\n throw Object.assign(\n new Error('node require() is unavailable in this runtime'),\n { code: 'MODULE_NOT_FOUND' },\n );\n }\n cachedRequire = createRequire(base);\n return cachedRequire;\n}\n\n/**\n * Synchronously require a module (works in both CJS and ESM)\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { safeRequire } from './node-require';\n *\n * const traceloop = safeRequire('@traceloop/node-server-sdk');\n * if (traceloop) {\n * traceloop.initialize({ ... });\n * }\n * ```\n */\nexport function safeRequire<T = unknown>(id: string): T | undefined {\n try {\n return getNodeRequire()(id) as T;\n } catch (error) {\n if (error && (error as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n // Optional dependency missing – return undefined\n return undefined;\n }\n // Any other error is a real bug: rethrow\n throw error;\n }\n}\n\n/**\n * Synchronously require a module (throws if not found)\n *\n * Use this when the module is required (not optional).\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { requireModule } from './node-require';\n *\n * const fs = requireModule<typeof import('node:fs')>('node:fs');\n * const content = fs.readFileSync('file.txt', 'utf8');\n * ```\n */\nexport function requireModule<T = unknown>(id: string): T {\n return getNodeRequire()(id) as T;\n}\n\n/**\n * Direct access to the nodeRequire function (for advanced use cases).\n *\n * Lazily resolves the underlying Node `require` on first call, so importing\n * this binding never triggers `createRequire` in runtimes that lack a module\n * path (e.g. Cloudflare Workers).\n *\n * Only the call signature and `resolve` (including `resolve.paths`) are\n * forwarded. The live, mutable members of a real `require` — `.cache`,\n * `.main`, `.extensions` — are intentionally NOT exposed: a lazy wrapper\n * can't mirror that shared state without resolving eagerly, which would\n * reintroduce the workerd crash. Use `createRequire` directly if you need\n * them.\n */\nconst nodeRequire = ((id: string) => getNodeRequire()(id)) as NodeRequire;\nconst lazyResolve = ((id: string, options?: { paths?: string[] }) =>\n getNodeRequire().resolve(id, options)) as NodeRequire['resolve'];\nlazyResolve.paths = (request: string) =>\n getNodeRequire().resolve.paths(request);\nnodeRequire.resolve = lazyResolve;\n\nexport { nodeRequire };\n"],"mappings":";;;;;;;;;;;;;AAiCA,IAAI;AAEJ,SAAS,iBAA8B;CACrC,IAAI,eAAe,OAAO;CAC1B,MAAM,OAAO,OAAO,eAAe,WAAW;CAC9C,IAAI,CAAC,MAGH,MAAM,OAAO,uBACX,IAAI,MAAM,+CAA+C,GACzD,EAAE,MAAM,mBAAmB,CAC7B;CAEF,+CAA8B,IAAI;CAClC,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YAAyB,IAA2B;CAClE,IAAI;EACF,OAAO,eAAe,CAAC,CAAC,EAAE;CAC5B,SAAS,OAAO;EACd,IAAI,SAAU,MAAgC,SAAS,oBAErD;EAGF,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,cAA2B,IAAe;CACxD,OAAO,eAAe,CAAC,CAAC,EAAE;AAC5B;;;;;;;;;;;;;;;AAgBA,MAAM,gBAAgB,OAAe,eAAe,CAAC,CAAC,EAAE;AACxD,MAAM,gBAAgB,IAAY,YAChC,eAAe,CAAC,CAAC,QAAQ,IAAI,OAAO;AACtC,YAAY,SAAS,YACnB,eAAe,CAAC,CAAC,QAAQ,MAAM,OAAO;AACxC,YAAY,UAAU"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"node-require-Db1oDpLj.js","names":[],"sources":["../src/node-require.ts"],"sourcesContent":["/**\n * Cross-format require() helper for CJS and ESM compatibility\n *\n * Provides a synchronous `require()` function that works in both:\n * - CJS builds: Uses native `require`\n * - ESM builds: Uses `createRequire(import.meta.url)`\n *\n * This allows optional peer dependencies and dynamic module loading\n * to work synchronously in both module formats.\n */\n\nimport { createRequire } from 'node:module';\n\n// `__filename` is provided by CJS and by esbuild's CJS output wrapper, but\n// is undefined under pure ESM. `import.meta.url` is provided by ESM. Pick\n// whichever is available so the helper works in:\n// - native CJS (autotel's published `.cjs`)\n// - native ESM (autotel's published `.js`)\n// - ESM-bundled-into-CJS by a downstream consumer (e.g. CDK's\n// `aws-lambda-nodejs` → esbuild with `format: cjs`). esbuild rewrites\n// `import.meta` to `{}` in this case, so `createRequire(import.meta.url)`\n// alone collapses to `createRequire(undefined)` and crashes at load.\n// `typeof __filename` does NOT throw when the identifier is undeclared, so\n// the ESM build evaluates the conditional safely.\ndeclare const __filename: string | undefined;\n\n// Build the Node `require` lazily on first use. Calling `createRequire`\n// eagerly at module load crashes in runtimes where neither `__filename` nor\n// `import.meta.url` resolves to a path — e.g. Cloudflare Workers / workerd,\n// where the bundle has no module path and `createRequire(undefined)` throws\n// synchronously at import. Deferring the call keeps merely importing this\n// module (and therefore anything that re-exports it, such as `track`)\n// side-effect-free; Node/CJS/ESM still get a real `require` on first call.\nlet cachedRequire: NodeRequire | undefined;\n\nfunction getNodeRequire(): NodeRequire {\n if (cachedRequire) return cachedRequire;\n const base = typeof __filename === 'string' ? __filename : import.meta.url;\n if (!base) {\n // No module path in this runtime. Surface as a missing-module error so\n // optional lookups via `safeRequire()` degrade gracefully to `undefined`.\n throw Object.assign(\n new Error('node require() is unavailable in this runtime'),\n { code: 'MODULE_NOT_FOUND' },\n );\n }\n cachedRequire = createRequire(base);\n return cachedRequire;\n}\n\n/**\n * Synchronously require a module (works in both CJS and ESM)\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { safeRequire } from './node-require';\n *\n * const traceloop = safeRequire('@traceloop/node-server-sdk');\n * if (traceloop) {\n * traceloop.initialize({ ... });\n * }\n * ```\n */\nexport function safeRequire<T = unknown>(id: string): T | undefined {\n try {\n return getNodeRequire()(id) as T;\n } catch (error) {\n if (error && (error as NodeJS.ErrnoException).code === 'MODULE_NOT_FOUND') {\n // Optional dependency missing – return undefined\n return undefined;\n }\n // Any other error is a real bug: rethrow\n throw error;\n }\n}\n\n/**\n * Synchronously require a module (throws if not found)\n *\n * Use this when the module is required (not optional).\n *\n * @param id - Module ID to require\n * @returns The required module\n * @throws Error if module cannot be loaded\n *\n * @example\n * ```typescript\n * import { requireModule } from './node-require';\n *\n * const fs = requireModule<typeof import('node:fs')>('node:fs');\n * const content = fs.readFileSync('file.txt', 'utf8');\n * ```\n */\nexport function requireModule<T = unknown>(id: string): T {\n return getNodeRequire()(id) as T;\n}\n\n/**\n * Direct access to the nodeRequire function (for advanced use cases).\n *\n * Lazily resolves the underlying Node `require` on first call, so importing\n * this binding never triggers `createRequire` in runtimes that lack a module\n * path (e.g. Cloudflare Workers).\n *\n * Only the call signature and `resolve` (including `resolve.paths`) are\n * forwarded. The live, mutable members of a real `require` — `.cache`,\n * `.main`, `.extensions` — are intentionally NOT exposed: a lazy wrapper\n * can't mirror that shared state without resolving eagerly, which would\n * reintroduce the workerd crash. Use `createRequire` directly if you need\n * them.\n */\nconst nodeRequire = ((id: string) => getNodeRequire()(id)) as NodeRequire;\nconst lazyResolve = ((id: string, options?: { paths?: string[] }) =>\n getNodeRequire().resolve(id, options)) as NodeRequire['resolve'];\nlazyResolve.paths = (request: string) =>\n getNodeRequire().resolve.paths(request);\nnodeRequire.resolve = lazyResolve;\n\nexport { nodeRequire };\n"],"mappings":";;;;;;;;;;;;;AAiCA,IAAI;AAEJ,SAAS,iBAA8B;CACrC,IAAI,eAAe,OAAO;CAC1B,MAAM,OAAO,OAAO,eAAe,WAAW,aAAa,OAAO,KAAK;CACvE,IAAI,CAAC,MAGH,MAAM,OAAO,uBACX,IAAI,MAAM,+CAA+C,GACzD,EAAE,MAAM,mBAAmB,CAC7B;CAEF,gBAAgB,cAAc,IAAI;CAClC,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,YAAyB,IAA2B;CAClE,IAAI;EACF,OAAO,eAAe,CAAC,CAAC,EAAE;CAC5B,SAAS,OAAO;EACd,IAAI,SAAU,MAAgC,SAAS,oBAErD;EAGF,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,cAA2B,IAAe;CACxD,OAAO,eAAe,CAAC,CAAC,EAAE;AAC5B;;;;;;;;;;;;;;;AAgBA,MAAM,gBAAgB,OAAe,eAAe,CAAC,CAAC,EAAE;AACxD,MAAM,gBAAgB,IAAY,YAChC,eAAe,CAAC,CAAC,QAAQ,IAAI,OAAO;AACtC,YAAY,SAAS,YACnB,eAAe,CAAC,CAAC,QAAQ,MAAM,OAAO;AACxC,YAAY,UAAU"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"operation-context-C-2hmmtP.js","names":[],"sources":["../src/operation-context.ts"],"sourcesContent":["/**\n * Operation context tracking using AsyncLocalStorage\n *\n * This module provides a way to track operation names across async boundaries\n * so they can be automatically captured in events events.\n *\n * We cannot read span attributes from OpenTelemetry's API (it's write-only),\n * so we maintain our own async context storage.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Operation context that flows through async operations\n */\nexport interface OperationContext {\n /**\n * The name of the current operation\n * This is set by trace() or span() and can be read by events\n */\n name: string;\n}\n\n/**\n * AsyncLocalStorage instance for tracking operation context\n */\nconst operationStorage = new AsyncLocalStorage<OperationContext>();\n\n/**\n * Get the current operation context (if any)\n *\n * @returns The current operation context, or undefined if not in an operation\n *\n * @example\n * ```typescript\n * const ctx = getOperationContext();\n * if (ctx) {\n * console.log('Current operation:', ctx.name);\n * }\n * ```\n */\nexport function getOperationContext(): OperationContext | undefined {\n return operationStorage.getStore();\n}\n\n/**\n * Run a function within an operation context\n *\n * This sets the operation name for the duration of the function execution,\n * including all async operations spawned from it.\n *\n * @param name - The operation name to set\n * @param fn - The function to execute within the context\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await runInOperationContext('user.create', async () => {\n * // Any events.trackEvent() calls here will automatically capture\n * // 'operation.name': 'user.create'\n * await createUser();\n * return 'success';\n * });\n * ```\n */\nexport function runInOperationContext<T>(name: string, fn: () => T): T {\n return operationStorage.run({ name }, fn);\n}\n\n/**\n * Update the operation name in the current context\n *\n * This is useful when you want to change the operation name within\n * an already-established context (e.g., when entering a nested span).\n *\n * @param name - The new operation name\n *\n * @example\n * ```typescript\n * runInOperationContext('parent.operation', () => {\n * // operation.name is 'parent.operation'\n *\n * updateOperationName('nested.operation');\n * // operation.name is now 'nested.operation'\n * });\n * ```\n */\nexport function updateOperationName(name: string): void {\n const store = operationStorage.getStore();\n if (store) {\n store.name = name;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,MAAM,mBAAmB,IAAI,kBAAoC;;;;;;;;;;;;;;AAejE,SAAgB,sBAAoD;CAClE,OAAO,iBAAiB,SAAS;AACnC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,sBAAyB,MAAc,IAAgB;CACrE,OAAO,iBAAiB,IAAI,EAAE,KAAK,GAAG,EAAE;AAC1C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"operation-context-n4_obUwq.cjs","names":["AsyncLocalStorage"],"sources":["../src/operation-context.ts"],"sourcesContent":["/**\n * Operation context tracking using AsyncLocalStorage\n *\n * This module provides a way to track operation names across async boundaries\n * so they can be automatically captured in events events.\n *\n * We cannot read span attributes from OpenTelemetry's API (it's write-only),\n * so we maintain our own async context storage.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Operation context that flows through async operations\n */\nexport interface OperationContext {\n /**\n * The name of the current operation\n * This is set by trace() or span() and can be read by events\n */\n name: string;\n}\n\n/**\n * AsyncLocalStorage instance for tracking operation context\n */\nconst operationStorage = new AsyncLocalStorage<OperationContext>();\n\n/**\n * Get the current operation context (if any)\n *\n * @returns The current operation context, or undefined if not in an operation\n *\n * @example\n * ```typescript\n * const ctx = getOperationContext();\n * if (ctx) {\n * console.log('Current operation:', ctx.name);\n * }\n * ```\n */\nexport function getOperationContext(): OperationContext | undefined {\n return operationStorage.getStore();\n}\n\n/**\n * Run a function within an operation context\n *\n * This sets the operation name for the duration of the function execution,\n * including all async operations spawned from it.\n *\n * @param name - The operation name to set\n * @param fn - The function to execute within the context\n * @returns The result of the function\n *\n * @example\n * ```typescript\n * const result = await runInOperationContext('user.create', async () => {\n * // Any events.trackEvent() calls here will automatically capture\n * // 'operation.name': 'user.create'\n * await createUser();\n * return 'success';\n * });\n * ```\n */\nexport function runInOperationContext<T>(name: string, fn: () => T): T {\n return operationStorage.run({ name }, fn);\n}\n\n/**\n * Update the operation name in the current context\n *\n * This is useful when you want to change the operation name within\n * an already-established context (e.g., when entering a nested span).\n *\n * @param name - The new operation name\n *\n * @example\n * ```typescript\n * runInOperationContext('parent.operation', () => {\n * // operation.name is 'parent.operation'\n *\n * updateOperationName('nested.operation');\n * // operation.name is now 'nested.operation'\n * });\n * ```\n */\nexport function updateOperationName(name: string): void {\n const store = operationStorage.getStore();\n if (store) {\n store.name = name;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA0BA,MAAM,mBAAmB,IAAIA,mCAAoC;;;;;;;;;;;;;;AAejE,SAAgB,sBAAoD;CAClE,OAAO,iBAAiB,SAAS;AACnC;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,sBAAyB,MAAc,IAAgB;CACrE,OAAO,iBAAiB,IAAI,EAAE,KAAK,GAAG,EAAE;AAC1C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stable-hash-BNTMrmdB.cjs","names":[],"sources":["../src/stable-hash.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\n/**\n * Deterministic JSON stringify with sorted object keys, so two structurally\n * equal values always produce the same string regardless of key insertion\n * order. Shared by `defineEvent` and the validation layer for stable schema\n * hashes.\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return '[' + value.map((v) => stableStringify(v)).join(',') + ']';\n }\n const obj = value as Record<string, unknown>;\n const body = Object.keys(obj)\n .toSorted()\n .map((k) => JSON.stringify(k) + ':' + stableStringify(obj[k]))\n .join(',');\n return '{' + body + '}';\n}\n\n/** Stable sha256 of any JSON-serializable value. */\nexport function hashJson(value: unknown): string {\n return createHash('sha256').update(stableStringify(value)).digest('hex');\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,gBAAgB,OAAwB;CACtD,IAAI,UAAU,QAAQ,UAAU,UAAa,OAAO,UAAU,UAC5D,OAAO,KAAK,UAAU,KAAK;CAE7B,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,MAAM,KAAK,MAAM,gBAAgB,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI;CAEhE,MAAM,MAAM;CAKZ,OAAO,MAJM,OAAO,KAAK,GAAG,CAAC,CAC1B,SAAS,CAAC,CACV,KAAK,MAAM,KAAK,UAAU,CAAC,IAAI,MAAM,gBAAgB,IAAI,EAAE,CAAC,CAAC,CAC7D,KAAK,GACQ,IAAI;AACtB;;AAGA,SAAgB,SAAS,OAAwB;CAC/C,mCAAkB,QAAQ,CAAC,CAAC,OAAO,gBAAgB,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AACzE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"stable-hash-Cg5cT34Q.js","names":[],"sources":["../src/stable-hash.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\n/**\n * Deterministic JSON stringify with sorted object keys, so two structurally\n * equal values always produce the same string regardless of key insertion\n * order. Shared by `defineEvent` and the validation layer for stable schema\n * hashes.\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return '[' + value.map((v) => stableStringify(v)).join(',') + ']';\n }\n const obj = value as Record<string, unknown>;\n const body = Object.keys(obj)\n .toSorted()\n .map((k) => JSON.stringify(k) + ':' + stableStringify(obj[k]))\n .join(',');\n return '{' + body + '}';\n}\n\n/** Stable sha256 of any JSON-serializable value. */\nexport function hashJson(value: unknown): string {\n return createHash('sha256').update(stableStringify(value)).digest('hex');\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,gBAAgB,OAAwB;CACtD,IAAI,UAAU,QAAQ,UAAU,UAAa,OAAO,UAAU,UAC5D,OAAO,KAAK,UAAU,KAAK;CAE7B,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,MAAM,KAAK,MAAM,gBAAgB,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI;CAEhE,MAAM,MAAM;CAKZ,OAAO,MAJM,OAAO,KAAK,GAAG,CAAC,CAC1B,SAAS,CAAC,CACV,KAAK,MAAM,KAAK,UAAU,CAAC,IAAI,MAAM,gBAAgB,IAAI,EAAE,CAAC,CAAC,CAC7D,KAAK,GACQ,IAAI;AACtB;;AAGA,SAAgB,SAAS,OAAwB;CAC/C,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,gBAAgB,KAAK,CAAC,CAAC,CAAC,OAAO,KAAK;AACzE"}
|