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.
Files changed (253) hide show
  1. package/dist/auto.cjs +5 -3
  2. package/dist/auto.cjs.map +1 -1
  3. package/dist/auto.js +3 -3
  4. package/dist/auto.js.map +1 -1
  5. package/dist/chunk-C_NdSu1c.cjs +34 -0
  6. package/dist/correlation-id.cjs +1 -1
  7. package/dist/correlation-id.d.cts.map +1 -1
  8. package/dist/correlation-id.d.ts.map +1 -1
  9. package/dist/correlation-id.js +1 -1
  10. package/dist/decorators.cjs +1 -1
  11. package/dist/decorators.js +1 -1
  12. package/dist/{event-ByBTV9M2.js → event-531asIM6.js} +4 -4
  13. package/dist/{event-ByBTV9M2.js.map → event-531asIM6.js.map} +1 -1
  14. package/dist/{event-BhHREDJk.cjs → event-CcZYwp50.cjs} +4 -4
  15. package/dist/{event-BhHREDJk.cjs.map → event-CcZYwp50.cjs.map} +1 -1
  16. package/dist/event.cjs +1 -1
  17. package/dist/event.js +1 -1
  18. package/dist/{functional-zpzNLhky.cjs → functional-C8B0Qa7o.cjs} +10 -7
  19. package/dist/functional-C8B0Qa7o.cjs.map +1 -0
  20. package/dist/{functional-DtI0u4vx.js → functional-r-AUIRy_.js} +9 -9
  21. package/dist/functional-r-AUIRy_.js.map +1 -0
  22. package/dist/functional.cjs +1 -1
  23. package/dist/functional.js +1 -1
  24. package/dist/http.cjs +1 -1
  25. package/dist/http.js +1 -1
  26. package/dist/index.cjs +15 -13
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts.map +1 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +14 -14
  31. package/dist/index.js.map +1 -1
  32. package/dist/{init-D-jnNMix.js → init-BS2JVkrL.js} +2 -2
  33. package/dist/{init-D-jnNMix.js.map → init-BS2JVkrL.js.map} +1 -1
  34. package/dist/{init-BX7AmFRl.cjs → init-BXiuPK6j.cjs} +3 -3
  35. package/dist/{init-BX7AmFRl.cjs.map → init-BXiuPK6j.cjs.map} +1 -1
  36. package/dist/instrumentation.cjs +2 -2
  37. package/dist/instrumentation.js +2 -2
  38. package/dist/logger.cjs +236 -8
  39. package/dist/logger.cjs.map +1 -0
  40. package/dist/messaging.cjs +1 -1
  41. package/dist/messaging.js +1 -1
  42. package/dist/{node-require-DF5QBX6z.cjs → node-require-CZ_PU448.cjs} +6 -4
  43. package/dist/node-require-CZ_PU448.cjs.map +1 -0
  44. package/dist/{node-require-Db1oDpLj.js → node-require-vROmTeJ8.js} +5 -5
  45. package/dist/node-require-vROmTeJ8.js.map +1 -0
  46. package/dist/{operation-context-C-2hmmtP.js → operation-context-CKBoA4Qy.js} +3 -3
  47. package/dist/operation-context-CKBoA4Qy.js.map +1 -0
  48. package/dist/{operation-context-n4_obUwq.cjs → operation-context-D6LDf4W_.cjs} +3 -1
  49. package/dist/operation-context-D6LDf4W_.cjs.map +1 -0
  50. package/dist/register.cjs +3 -1
  51. package/dist/register.cjs.map +1 -1
  52. package/dist/register.js +2 -2
  53. package/dist/register.js.map +1 -1
  54. package/dist/semantic-helpers.cjs +1 -1
  55. package/dist/semantic-helpers.js +1 -1
  56. package/dist/{stable-hash-Cg5cT34Q.js → stable-hash-ChFBIhNt.js} +3 -3
  57. package/dist/stable-hash-ChFBIhNt.js.map +1 -0
  58. package/dist/{stable-hash-BNTMrmdB.cjs → stable-hash-brKISGf1.cjs} +4 -2
  59. package/dist/stable-hash-brKISGf1.cjs.map +1 -0
  60. package/dist/trace-context-Cijqoi6e.d.cts.map +1 -1
  61. package/dist/trace-context-Cijqoi6e.d.ts.map +1 -1
  62. package/dist/trace-helpers.cjs +1 -1
  63. package/dist/trace-helpers.js +1 -1
  64. package/dist/{track-wc0HafS_.js → track-COUuU48p.js} +5 -5
  65. package/dist/track-COUuU48p.js.map +1 -0
  66. package/dist/{track-D59FfpL0.cjs → track-Cb3Q4QmS.cjs} +4 -2
  67. package/dist/track-Cb3Q4QmS.cjs.map +1 -0
  68. package/dist/validate.cjs +1 -1
  69. package/dist/validate.js +1 -1
  70. package/dist/webhook.cjs +1 -1
  71. package/dist/webhook.js +1 -1
  72. package/dist/workflow-distributed.cjs +1 -1
  73. package/dist/workflow-distributed.js +1 -1
  74. package/dist/workflow.cjs +3 -1
  75. package/dist/workflow.cjs.map +1 -1
  76. package/dist/workflow.d.cts.map +1 -1
  77. package/dist/workflow.d.ts.map +1 -1
  78. package/dist/workflow.js +3 -3
  79. package/dist/workflow.js.map +1 -1
  80. package/dist/yaml-config.cjs +233 -4
  81. package/dist/yaml-config.cjs.map +1 -0
  82. package/dist/yaml-config.d.cts.map +1 -1
  83. package/dist/yaml-config.d.ts.map +1 -1
  84. package/dist/yaml-config.js +8 -7
  85. package/dist/yaml-config.js.map +1 -1
  86. package/package.json +1 -2
  87. package/dist/functional-DtI0u4vx.js.map +0 -1
  88. package/dist/functional-zpzNLhky.cjs.map +0 -1
  89. package/dist/logger-thMPLpOG.cjs +0 -487
  90. package/dist/logger-thMPLpOG.cjs.map +0 -1
  91. package/dist/node-require-DF5QBX6z.cjs.map +0 -1
  92. package/dist/node-require-Db1oDpLj.js.map +0 -1
  93. package/dist/operation-context-C-2hmmtP.js.map +0 -1
  94. package/dist/operation-context-n4_obUwq.cjs.map +0 -1
  95. package/dist/stable-hash-BNTMrmdB.cjs.map +0 -1
  96. package/dist/stable-hash-Cg5cT34Q.js.map +0 -1
  97. package/dist/track-D59FfpL0.cjs.map +0 -1
  98. package/dist/track-wc0HafS_.js.map +0 -1
  99. package/dist/yaml-config-Ck2uB0Dp.cjs +0 -273
  100. package/dist/yaml-config-Ck2uB0Dp.cjs.map +0 -1
  101. package/src/attribute-redacting-processor.test.ts +0 -763
  102. package/src/attribute-redacting-processor.ts +0 -621
  103. package/src/attributes/attachers.ts +0 -161
  104. package/src/attributes/builders.ts +0 -529
  105. package/src/attributes/domains.ts +0 -42
  106. package/src/attributes/index.ts +0 -81
  107. package/src/attributes/registry.ts +0 -323
  108. package/src/attributes/types.ts +0 -211
  109. package/src/attributes/utils.ts +0 -64
  110. package/src/attributes/validators.ts +0 -266
  111. package/src/attributes.test.ts +0 -292
  112. package/src/auto.ts +0 -67
  113. package/src/autotel-logger.test.ts +0 -548
  114. package/src/autotel-logger.ts +0 -364
  115. package/src/baggage-span-processor.test.ts +0 -202
  116. package/src/baggage-span-processor.ts +0 -100
  117. package/src/business-baggage.test.ts +0 -500
  118. package/src/business-baggage.ts +0 -669
  119. package/src/circuit-breaker.test.ts +0 -341
  120. package/src/circuit-breaker.ts +0 -184
  121. package/src/config.test.ts +0 -94
  122. package/src/config.ts +0 -172
  123. package/src/correlated-events.test.ts +0 -151
  124. package/src/correlated-events.ts +0 -47
  125. package/src/correlation-id.test.ts +0 -163
  126. package/src/correlation-id.ts +0 -206
  127. package/src/db.test.ts +0 -252
  128. package/src/db.ts +0 -447
  129. package/src/decorators.test.ts +0 -153
  130. package/src/decorators.ts +0 -188
  131. package/src/define-event.test.ts +0 -41
  132. package/src/define-event.ts +0 -58
  133. package/src/devtools.ts +0 -60
  134. package/src/drain-pipeline.test.ts +0 -68
  135. package/src/drain-pipeline.ts +0 -199
  136. package/src/drain-toolkit.test.ts +0 -113
  137. package/src/drain-toolkit.ts +0 -129
  138. package/src/enricher-toolkit.test.ts +0 -67
  139. package/src/enricher-toolkit.ts +0 -79
  140. package/src/enrichers.test.ts +0 -150
  141. package/src/enrichers.ts +0 -145
  142. package/src/env-config.test.ts +0 -323
  143. package/src/env-config.ts +0 -309
  144. package/src/error-catalog.test.ts +0 -133
  145. package/src/error-catalog.ts +0 -262
  146. package/src/event-queue.test.ts +0 -864
  147. package/src/event-queue.ts +0 -699
  148. package/src/event-subscriber.ts +0 -262
  149. package/src/event-testing.ts +0 -197
  150. package/src/event.test.ts +0 -1104
  151. package/src/event.ts +0 -988
  152. package/src/events-config.ts +0 -235
  153. package/src/exporters.ts +0 -165
  154. package/src/filtering-span-processor.test.ts +0 -281
  155. package/src/filtering-span-processor.ts +0 -111
  156. package/src/flatten-attributes.test.ts +0 -76
  157. package/src/flatten-attributes.ts +0 -80
  158. package/src/functional.strict-types.typecheck.ts +0 -53
  159. package/src/functional.test.ts +0 -1464
  160. package/src/functional.ts +0 -2539
  161. package/src/functional.types.test.ts +0 -135
  162. package/src/hook.mjs +0 -15
  163. package/src/http.test.ts +0 -485
  164. package/src/http.ts +0 -424
  165. package/src/index.ts +0 -433
  166. package/src/init-auto-redactor.test.ts +0 -53
  167. package/src/init-redactor.test.ts +0 -8
  168. package/src/init.customization.test.ts +0 -665
  169. package/src/init.integrations.test.ts +0 -399
  170. package/src/init.openllmetry.test.ts +0 -194
  171. package/src/init.protocol.test.ts +0 -215
  172. package/src/init.ts +0 -2439
  173. package/src/instrumentation.test.ts +0 -108
  174. package/src/instrumentation.ts +0 -319
  175. package/src/logger.test.ts +0 -125
  176. package/src/logger.ts +0 -341
  177. package/src/messaging-adapters.test.ts +0 -595
  178. package/src/messaging-adapters.ts +0 -583
  179. package/src/messaging-testing.test.ts +0 -573
  180. package/src/messaging-testing.ts +0 -935
  181. package/src/messaging.test.ts +0 -1646
  182. package/src/messaging.ts +0 -2245
  183. package/src/metric-helpers.ts +0 -47
  184. package/src/metric-testing.ts +0 -197
  185. package/src/metric.ts +0 -446
  186. package/src/metrics.test.ts +0 -241
  187. package/src/node-require.ts +0 -123
  188. package/src/operation-context.ts +0 -93
  189. package/src/parse-error.test.ts +0 -73
  190. package/src/parse-error.ts +0 -112
  191. package/src/posthog-logs.test.ts +0 -115
  192. package/src/posthog-logs.ts +0 -77
  193. package/src/pretty-console-exporter.test.ts +0 -545
  194. package/src/pretty-console-exporter.ts +0 -413
  195. package/src/pretty-log-formatter.test.ts +0 -123
  196. package/src/pretty-log-formatter.ts +0 -210
  197. package/src/processors/canonical-log-line-processor.test.ts +0 -523
  198. package/src/processors/canonical-log-line-processor.ts +0 -396
  199. package/src/processors.ts +0 -152
  200. package/src/rate-limiter.test.ts +0 -199
  201. package/src/rate-limiter.ts +0 -98
  202. package/src/redact-values.test.ts +0 -90
  203. package/src/redact-values.ts +0 -34
  204. package/src/register.ts +0 -37
  205. package/src/request-logger.test.ts +0 -545
  206. package/src/request-logger.ts +0 -342
  207. package/src/sampling.test.ts +0 -1060
  208. package/src/sampling.ts +0 -737
  209. package/src/security-schema.test.ts +0 -45
  210. package/src/security-schema.ts +0 -107
  211. package/src/semantic-conventions.ts +0 -15
  212. package/src/semantic-helpers.test.ts +0 -226
  213. package/src/semantic-helpers.ts +0 -438
  214. package/src/shutdown.test.ts +0 -364
  215. package/src/shutdown.ts +0 -246
  216. package/src/span-name-normalizer.test.ts +0 -377
  217. package/src/span-name-normalizer.ts +0 -213
  218. package/src/stable-hash.ts +0 -27
  219. package/src/structured-error.test.ts +0 -191
  220. package/src/structured-error.ts +0 -157
  221. package/src/stub.integration.test.ts +0 -361
  222. package/src/tail-sampling-processor.test.ts +0 -230
  223. package/src/tail-sampling-processor.ts +0 -55
  224. package/src/test-span-collector.test.ts +0 -234
  225. package/src/test-span-collector.ts +0 -150
  226. package/src/testing.ts +0 -705
  227. package/src/trace-context.test.ts +0 -73
  228. package/src/trace-context.ts +0 -567
  229. package/src/trace-helpers.new.test.ts +0 -278
  230. package/src/trace-helpers.test.ts +0 -290
  231. package/src/trace-helpers.ts +0 -710
  232. package/src/trace-hybrid.test.ts +0 -42
  233. package/src/trace-hybrid.ts +0 -37
  234. package/src/tracer-provider.test.ts +0 -183
  235. package/src/tracer-provider.ts +0 -266
  236. package/src/track.test.ts +0 -154
  237. package/src/track.ts +0 -216
  238. package/src/validate.test.ts +0 -287
  239. package/src/validate.ts +0 -307
  240. package/src/validation-attributes.ts +0 -43
  241. package/src/validation.test.ts +0 -330
  242. package/src/validation.ts +0 -246
  243. package/src/variable-name-inference.test.ts +0 -178
  244. package/src/variable-name-inference.ts +0 -242
  245. package/src/webhook.test.ts +0 -649
  246. package/src/webhook.ts +0 -637
  247. package/src/workflow-distributed.test.ts +0 -786
  248. package/src/workflow-distributed.ts +0 -916
  249. package/src/workflow.async-safety.integration.test.ts +0 -345
  250. package/src/workflow.test.ts +0 -647
  251. package/src/workflow.ts +0 -810
  252. package/src/yaml-config.test.ts +0 -373
  253. package/src/yaml-config.ts +0 -351
@@ -1,191 +0,0 @@
1
- import { describe, expect, it, vi } from 'vitest';
2
- import type { Span, SpanContext } from '@opentelemetry/api';
3
- import {
4
- createStructuredError,
5
- getStructuredErrorAttributes,
6
- recordStructuredError,
7
- } from './structured-error';
8
- import { createTraceContext, type TraceContext } from './trace-context';
9
-
10
- function createFakeSpan(): {
11
- span: Span;
12
- recordException: ReturnType<typeof vi.fn>;
13
- setStatus: ReturnType<typeof vi.fn>;
14
- setAttributes: ReturnType<typeof vi.fn>;
15
- } {
16
- const recordException = vi.fn();
17
- const setStatus = vi.fn();
18
- const setAttributes = vi.fn();
19
- const spanContext: SpanContext = {
20
- traceId: '0123456789abcdef0123456789abcdef',
21
- spanId: '0123456789abcdef',
22
- traceFlags: 1,
23
- };
24
- const span = {
25
- spanContext: () => spanContext,
26
- setAttribute: vi.fn(),
27
- setAttributes,
28
- setStatus,
29
- recordException,
30
- addEvent: vi.fn(),
31
- addLink: vi.fn(),
32
- addLinks: vi.fn(),
33
- updateName: vi.fn(),
34
- isRecording: () => true,
35
- end: vi.fn(),
36
- } as unknown as Span;
37
- return { span, recordException, setStatus, setAttributes };
38
- }
39
-
40
- describe('structured-error helpers', () => {
41
- it('creates an error with structured diagnostic fields', () => {
42
- const err = createStructuredError({
43
- message: 'Payment failed',
44
- why: 'Card declined by issuer',
45
- fix: 'Use a different card',
46
- link: 'https://docs.example.com/errors/card-declined',
47
- code: 'PAYMENT_DECLINED',
48
- status: 402,
49
- details: { retryable: false, provider: 'stripe' },
50
- });
51
-
52
- expect(err.message).toBe('Payment failed');
53
- expect(err.why).toBe('Card declined by issuer');
54
- expect(err.fix).toBe('Use a different card');
55
- expect(err.link).toBe('https://docs.example.com/errors/card-declined');
56
- expect(err.code).toBe('PAYMENT_DECLINED');
57
- expect(err.status).toBe(402);
58
- expect(err.details).toEqual({ retryable: false, provider: 'stripe' });
59
- });
60
-
61
- it('toString() renders a human-readable diagnostic summary', () => {
62
- const err = createStructuredError({
63
- message: 'Payment failed',
64
- why: 'Card declined by issuer',
65
- fix: 'Use a different card',
66
- link: 'https://docs.example.com/errors/card-declined',
67
- code: 'PAYMENT_DECLINED',
68
- status: 402,
69
- cause: new Error('upstream timeout'),
70
- });
71
-
72
- const output = err.toString();
73
- expect(output).toBe(
74
- [
75
- 'StructuredError: Payment failed',
76
- ' Why: Card declined by issuer',
77
- ' Fix: Use a different card',
78
- ' Link: https://docs.example.com/errors/card-declined',
79
- ' Code: PAYMENT_DECLINED',
80
- ' Status: 402',
81
- ' Caused by: Error: upstream timeout',
82
- ].join('\n'),
83
- );
84
- });
85
-
86
- it('toString() omits undefined fields', () => {
87
- const err = createStructuredError({ message: 'Something broke' });
88
- expect(err.toString()).toBe('StructuredError: Something broke');
89
- });
90
-
91
- it('extracts canonical attributes for span logging', () => {
92
- const err = createStructuredError({
93
- message: 'Export failed',
94
- why: 'Template not found',
95
- fix: 'Upload template and retry',
96
- details: { export: { format: 'pdf' } },
97
- });
98
-
99
- const attrs = getStructuredErrorAttributes(err);
100
- expect(attrs).toMatchObject({
101
- 'error.type': 'StructuredError',
102
- 'error.message': 'Export failed',
103
- 'error.why': 'Template not found',
104
- 'error.fix': 'Upload template and retry',
105
- 'error.details.export.format': 'pdf',
106
- });
107
- });
108
-
109
- it('records structured error onto trace context', () => {
110
- const ctx = {
111
- recordException: vi.fn(),
112
- setStatus: vi.fn(),
113
- setAttributes: vi.fn(),
114
- } as unknown as TraceContext;
115
-
116
- const err = createStructuredError({
117
- message: 'Checkout failed',
118
- why: 'Inventory mismatch',
119
- fix: 'Re-sync inventory and retry',
120
- });
121
-
122
- recordStructuredError(ctx, err);
123
-
124
- expect(ctx.recordException).toHaveBeenCalledWith(err);
125
- expect(ctx.setStatus).toHaveBeenCalledWith({
126
- code: 2,
127
- message: 'Checkout failed',
128
- });
129
- expect(ctx.setAttributes).toHaveBeenCalledWith(
130
- expect.objectContaining({
131
- 'error.message': 'Checkout failed',
132
- 'error.why': 'Inventory mismatch',
133
- 'error.fix': 'Re-sync inventory and retry',
134
- }),
135
- );
136
- });
137
- });
138
-
139
- describe('ctx.recordError', () => {
140
- it('records a structured error onto the underlying span', () => {
141
- const { span, recordException, setStatus, setAttributes } =
142
- createFakeSpan();
143
- const ctx = createTraceContext(span);
144
- const err = createStructuredError({
145
- message: 'Order failed',
146
- why: 'Inventory unavailable',
147
- fix: 'Retry after restock',
148
- });
149
-
150
- ctx.recordError(err);
151
-
152
- expect(recordException).toHaveBeenCalledWith(err);
153
- expect(setStatus).toHaveBeenCalledWith({
154
- code: 2,
155
- message: 'Order failed',
156
- });
157
- expect(setAttributes).toHaveBeenCalledWith(
158
- expect.objectContaining({
159
- 'error.message': 'Order failed',
160
- 'error.why': 'Inventory unavailable',
161
- 'error.fix': 'Retry after restock',
162
- }),
163
- );
164
- });
165
-
166
- it('coerces non-Error values to Error so it is safe in catch blocks', () => {
167
- const { span, recordException, setStatus, setAttributes } =
168
- createFakeSpan();
169
- const ctx = createTraceContext(span);
170
-
171
- ctx.recordError('boom');
172
-
173
- expect(recordException).toHaveBeenCalledTimes(1);
174
- const recorded = recordException.mock.calls[0][0];
175
- expect(recorded).toBeInstanceOf(Error);
176
- expect(recorded.message).toBe('boom');
177
- expect(setStatus).toHaveBeenCalledWith({ code: 2, message: 'boom' });
178
- expect(setAttributes).toHaveBeenCalled();
179
- });
180
- });
181
-
182
- describe('ctx.track', () => {
183
- it('exposes track on the trace context as the ergonomic replacement for ctx.addEvent', () => {
184
- const { span } = createFakeSpan();
185
- const ctx = createTraceContext(span);
186
-
187
- expect(typeof ctx.track).toBe('function');
188
- // Smoke test — should not throw without init() (track is a no-op when no queue is configured)
189
- expect(() => ctx.track('test.event', { foo: 'bar' })).not.toThrow();
190
- });
191
- });
@@ -1,157 +0,0 @@
1
- import { SpanStatusCode } from '@opentelemetry/api';
2
- import type { AttributeValue, TraceContext } from './trace-context';
3
- import { flattenToAttributes } from './flatten-attributes';
4
-
5
- const internalKey = Symbol.for('autotel.error.internal');
6
-
7
- export interface StructuredErrorInput {
8
- message: string;
9
- why?: string;
10
- fix?: string;
11
- link?: string;
12
- code?: string | number;
13
- status?: number;
14
- cause?: unknown;
15
- details?: Record<string, unknown>;
16
- name?: string;
17
- /** Backend-only context. Omitted from toJSON() and never serialized to clients. */
18
- internal?: Record<string, unknown>;
19
- }
20
-
21
- export interface StructuredError extends Error {
22
- why?: string;
23
- fix?: string;
24
- link?: string;
25
- code?: string | number;
26
- status?: number;
27
- details?: Record<string, unknown>;
28
- /** Backend-only context. Omitted from toJSON() and never serialized to clients. */
29
- readonly internal?: Record<string, unknown>;
30
- }
31
-
32
- export function createStructuredError(
33
- input: StructuredErrorInput,
34
- ): StructuredError {
35
- const error = new Error(input.message, {
36
- cause: input.cause,
37
- }) as StructuredError;
38
-
39
- error.name = input.name ?? 'StructuredError';
40
- if (input.why !== undefined) error.why = input.why;
41
- if (input.fix !== undefined) error.fix = input.fix;
42
- if (input.link !== undefined) error.link = input.link;
43
- if (input.code !== undefined) error.code = input.code;
44
- if (input.status !== undefined) error.status = input.status;
45
- if (input.details !== undefined) error.details = input.details;
46
-
47
- if (input.internal !== undefined) {
48
- Object.defineProperty(error, internalKey, {
49
- value: input.internal,
50
- enumerable: false,
51
- writable: false,
52
- configurable: true,
53
- });
54
- }
55
-
56
- Object.defineProperty(error, 'internal', {
57
- get() {
58
- return (
59
- this as StructuredError & { [internalKey]?: Record<string, unknown> }
60
- )[internalKey];
61
- },
62
- enumerable: false,
63
- configurable: true,
64
- });
65
-
66
- error.toString = () => {
67
- const lines = [`${error.name}: ${error.message}`];
68
- if (error.why) lines.push(` Why: ${error.why}`);
69
- if (error.fix) lines.push(` Fix: ${error.fix}`);
70
- if (error.link) lines.push(` Link: ${error.link}`);
71
- if (error.code !== undefined) lines.push(` Code: ${error.code}`);
72
- if (error.status !== undefined) lines.push(` Status: ${error.status}`);
73
- if (error.cause) {
74
- const cause = error.cause as Error;
75
- lines.push(` Caused by: ${cause.name}: ${cause.message}`);
76
- }
77
- return lines.join('\n');
78
- };
79
-
80
- return error;
81
- }
82
-
83
- export function structuredErrorToJSON(
84
- error: StructuredError,
85
- ): Record<string, unknown> {
86
- const result: Record<string, unknown> = {
87
- name: error.name,
88
- message: error.message,
89
- };
90
-
91
- if (error.status !== undefined) result.status = error.status;
92
- if (error.why || error.fix || error.link) {
93
- result.data = {
94
- ...(error.why && { why: error.why }),
95
- ...(error.fix && { fix: error.fix }),
96
- ...(error.link && { link: error.link }),
97
- };
98
- }
99
- if (error.code !== undefined) result.code = error.code;
100
- if (error.details) result.details = error.details;
101
- if (error.cause instanceof Error) {
102
- result.cause = { name: error.cause.name, message: error.cause.message };
103
- }
104
-
105
- return result;
106
- }
107
-
108
- export function getStructuredErrorAttributes(
109
- error: Error,
110
- ): Record<string, AttributeValue> {
111
- const structured = error as StructuredError;
112
- const attributes: Record<string, AttributeValue> = {
113
- 'error.type': error.name || 'Error',
114
- 'error.message': error.message,
115
- };
116
-
117
- if (error.stack) attributes['error.stack'] = error.stack;
118
- if (structured.why) attributes['error.why'] = structured.why;
119
- if (structured.fix) attributes['error.fix'] = structured.fix;
120
- if (structured.link) attributes['error.link'] = structured.link;
121
- if (structured.code !== undefined) {
122
- attributes['error.code'] =
123
- typeof structured.code === 'string'
124
- ? structured.code
125
- : String(structured.code);
126
- }
127
- if (structured.status !== undefined) {
128
- attributes['error.status'] = structured.status;
129
- }
130
- if (structured.details) {
131
- Object.assign(
132
- attributes,
133
- flattenToAttributes(structured.details, 'error.details'),
134
- );
135
- }
136
-
137
- return attributes;
138
- }
139
-
140
- export function recordStructuredError(
141
- ctx: Pick<TraceContext, 'setAttributes' | 'setStatus'>,
142
- error: Error,
143
- ): void {
144
- const maybeRecordException = (
145
- ctx as unknown as {
146
- recordException?: (e: Error) => void;
147
- }
148
- ).recordException;
149
- if (typeof maybeRecordException === 'function') {
150
- maybeRecordException(error);
151
- }
152
- ctx.setStatus({
153
- code: SpanStatusCode.ERROR,
154
- message: error.message,
155
- });
156
- ctx.setAttributes(getStructuredErrorAttributes(error));
157
- }
@@ -1,361 +0,0 @@
1
- /**
2
- * Integration tests for autotel
3
- *
4
- * Tests end-to-end flows with all components working together
5
- */
6
-
7
- import { describe, it, expect, beforeEach, afterEach } from 'vitest';
8
- import { init } from './init';
9
- import { trace } from './functional';
10
- import { track, resetEventQueue } from './track';
11
- import { Event, resetEvents } from './event';
12
- import { flush, shutdown } from './shutdown';
13
- import { resetMetrics } from './metric';
14
- import { resetConfig } from './config';
15
- import { EventAttributes, EventSubscriber } from './event-subscriber';
16
-
17
- // Test adapter that collects events
18
- class TestAdapter implements EventSubscriber {
19
- name = 'test-adapter';
20
- events: Array<{ type: string; name: string; attributes?: EventAttributes }> =
21
- [];
22
-
23
- async trackEvent(name: string, attributes?: EventAttributes): Promise<void> {
24
- this.events.push({ type: 'event', name, attributes });
25
- }
26
-
27
- async trackFunnelStep(
28
- funnel: string,
29
- status: string,
30
- attributes?: EventAttributes,
31
- ): Promise<void> {
32
- this.events.push({
33
- type: 'funnel',
34
- name: `${funnel}.${status}`,
35
- attributes,
36
- });
37
- }
38
-
39
- async trackOutcome(
40
- operation: string,
41
- status: string,
42
- attributes?: EventAttributes,
43
- ): Promise<void> {
44
- this.events.push({
45
- type: 'outcome',
46
- name: `${operation}.${status}`,
47
- attributes,
48
- });
49
- }
50
-
51
- async trackValue(
52
- metric: string,
53
- value: number,
54
- attributes?: EventAttributes,
55
- ): Promise<void> {
56
- this.events.push({
57
- type: 'value',
58
- name: metric,
59
- attributes: { ...attributes, value },
60
- });
61
- }
62
-
63
- async shutdown(): Promise<void> {
64
- // Cleanup if needed
65
- }
66
-
67
- reset(): void {
68
- this.events = [];
69
- }
70
- }
71
-
72
- describe('Integration Test Suite', () => {
73
- let testAdapter: TestAdapter;
74
-
75
- beforeEach(() => {
76
- // Reset all global state between tests
77
- resetEventQueue();
78
- resetEvents();
79
- resetMetrics();
80
- resetConfig();
81
- testAdapter = new TestAdapter();
82
- });
83
-
84
- afterEach(async () => {
85
- // Clean up after each test
86
- await shutdown();
87
- });
88
-
89
- describe('Full stack initialization', () => {
90
- it('should initialize all components together', () => {
91
- init({
92
- service: 'test-app',
93
- subscribers: [testAdapter],
94
- version: '1.0.0',
95
- environment: 'test',
96
- });
97
-
98
- expect(true).toBe(true); // Should not throw
99
- });
100
- });
101
-
102
- describe('Tracing + Events integration', () => {
103
- it('should correlate traces with events events', async () => {
104
- init({
105
- service: 'user-service',
106
- subscribers: [testAdapter],
107
- });
108
-
109
- // Create trace function
110
- const createUser = trace(async (userId: string, plan: string) => {
111
- // Track events event inside trace function
112
- track('user.signup', { userId, plan });
113
- return { id: userId, plan };
114
- });
115
-
116
- // Execute
117
- const result = await createUser('user123', 'pro');
118
-
119
- // Should return expected result
120
- expect(result).toEqual({ id: 'user123', plan: 'pro' });
121
-
122
- // Flush to send events
123
- await flush();
124
-
125
- // Events event should be tracked
126
- // (traceId correlation happens automatically)
127
- const event = testAdapter.events.filter((e) => e.name === 'user.signup');
128
- expect(event.length).toBeGreaterThan(0);
129
- });
130
-
131
- it('should handle nested trace functions', async () => {
132
- init({
133
- service: 'order-service',
134
- subscribers: [testAdapter],
135
- });
136
-
137
- const validateOrder = trace(async (orderId: string) => {
138
- track('order.validated', { orderId });
139
- return true;
140
- });
141
-
142
- const processPayment = trace(async (orderId: string, amount: number) => {
143
- track('payment.processed', { orderId, amount });
144
- return { success: true };
145
- });
146
-
147
- const createOrder = trace(async (orderId: string, amount: number) => {
148
- await validateOrder(orderId);
149
- await processPayment(orderId, amount);
150
- track('order.completed', { orderId, amount });
151
- return { orderId, status: 'completed' };
152
- });
153
-
154
- await createOrder('order123', 99.99);
155
- await flush();
156
-
157
- // All events should be tracked
158
- expect(testAdapter.events.length).toBeGreaterThanOrEqual(3);
159
- expect(testAdapter.events.map((e) => e.name)).toContain(
160
- 'order.validated',
161
- );
162
- expect(testAdapter.events.map((e) => e.name)).toContain(
163
- 'payment.processed',
164
- );
165
- expect(testAdapter.events.map((e) => e.name)).toContain(
166
- 'order.completed',
167
- );
168
- });
169
- });
170
-
171
- describe('Events class integration', () => {
172
- it('should track all events event types', async () => {
173
- const event = new Event('checkout', {
174
- subscribers: [testAdapter],
175
- });
176
-
177
- // Track different event types
178
- event.trackEvent('checkout.started', { cartValue: 149.99 });
179
- event.trackFunnelStep('checkout', 'started', { userId: '123' });
180
- event.trackFunnelStep('checkout', 'started', {
181
- userId: '123',
182
- step: 'payment_info',
183
- });
184
- event.trackFunnelStep('checkout', 'completed', { userId: '123' });
185
- event.trackOutcome('payment.process', 'success', { amount: 149.99 });
186
- event.trackValue('revenue', 149.99, { currency: 'USD' });
187
-
188
- // Flush adapters
189
- await event.flush();
190
-
191
- // All events should be captured
192
- expect(testAdapter.events.length).toBe(6);
193
- expect(testAdapter.events.map((e) => e.type)).toEqual([
194
- 'event',
195
- 'funnel',
196
- 'funnel',
197
- 'funnel',
198
- 'outcome',
199
- 'value',
200
- ]);
201
- });
202
- });
203
-
204
- describe('Error handling integration', () => {
205
- it('should handle adapter failures gracefully', async () => {
206
- const failingAdapter: EventSubscriber = {
207
- name: 'failing-adapter',
208
- trackEvent: async () => {
209
- throw new Error('Adapter error');
210
- },
211
- trackFunnelStep: async () => {},
212
- trackOutcome: async () => {},
213
- trackValue: async () => {},
214
- };
215
-
216
- const event = new Event('test', {
217
- subscribers: [failingAdapter, testAdapter], // Mix failing and working
218
- });
219
-
220
- // Should not throw even though one adapter fails
221
- event.trackEvent('test.event', { foo: 'bar' });
222
-
223
- await event.flush();
224
-
225
- // Working adapter should still receive events
226
- expect(testAdapter.events.length).toBeGreaterThan(0);
227
- });
228
-
229
- it('should handle circuit breaker opening', async () => {
230
- let callCount = 0;
231
-
232
- const unreliableAdapter: EventSubscriber = {
233
- name: 'unreliable-adapter',
234
- trackEvent: async () => {
235
- callCount++;
236
- // Fail first 5 times to trip circuit breaker
237
- if (callCount <= 5) {
238
- throw new Error('Service unavailable');
239
- }
240
- },
241
- trackFunnelStep: async () => {},
242
- trackOutcome: async () => {},
243
- trackValue: async () => {},
244
- };
245
-
246
- const event = new Event('test', {
247
- subscribers: [unreliableAdapter],
248
- });
249
-
250
- // Send events one at a time to allow circuit breaker to open
251
- for (let i = 0; i < 10; i++) {
252
- event.trackEvent(`event.${i}`, { index: i });
253
- // Wait a bit to allow circuit breaker to process
254
- await new Promise((resolve) => setTimeout(resolve, 10));
255
- }
256
-
257
- await event.flush();
258
-
259
- // Circuit should open after 5 failures
260
- // Remaining calls should be fast-failed
261
- expect(callCount).toBeLessThanOrEqual(6); // 5 failures + maybe 1 half-open test
262
- });
263
- });
264
-
265
- describe('Input validation integration', () => {
266
- it('should sanitize sensitive data across all components', async () => {
267
- init({
268
- service: 'auth-service',
269
- subscribers: [testAdapter],
270
- });
271
-
272
- // Track with sensitive data
273
- track('user.login', {
274
- email: 'user@example.com',
275
- password: 'secret123', // Should be redacted
276
- apiKey: 'abc123', // Should be redacted
277
- userId: '123', // Should NOT be redacted
278
- });
279
-
280
- await flush();
281
-
282
- const event = testAdapter.events.find((e) => e.name === 'user.login');
283
- expect(event?.attributes?.email).toBe('user@example.com');
284
- expect(event?.attributes?.password).toBe('[REDACTED]');
285
- expect(event?.attributes?.apiKey).toBe('[REDACTED]');
286
- expect(event?.attributes?.userId).toBe('123');
287
- });
288
-
289
- it('should validate event names', () => {
290
- const event = new Event('test', {
291
- subscribers: [testAdapter],
292
- });
293
-
294
- // Invalid event names should throw
295
- expect(() => {
296
- event.trackEvent('', { foo: 'bar' });
297
- }).toThrow();
298
-
299
- expect(() => {
300
- event.trackEvent('invalid event name', { foo: 'bar' });
301
- }).toThrow();
302
- });
303
- });
304
-
305
- describe('Graceful shutdown integration', () => {
306
- it('should shutdown all components cleanly', async () => {
307
- init({
308
- service: 'test-service',
309
- subscribers: [testAdapter],
310
- });
311
-
312
- track('test.event', { foo: 'bar' });
313
-
314
- await shutdown();
315
-
316
- // Events should be flushed
317
- expect(testAdapter.events.length).toBeGreaterThan(0);
318
- });
319
- });
320
-
321
- describe('Performance under load', () => {
322
- it('should handle high event volume', async () => {
323
- init({
324
- service: 'high-volume-service',
325
- subscribers: [testAdapter],
326
- });
327
-
328
- // Send 1000 events
329
- for (let i = 0; i < 1000; i++) {
330
- track(`event.${i}`, { index: i });
331
- }
332
-
333
- await flush({ timeout: 10_000 }); // 10s timeout for high-volume test
334
-
335
- // All events should be captured
336
- expect(testAdapter.events.length).toBeGreaterThanOrEqual(1000);
337
- });
338
-
339
- it('should batch events efficiently', async () => {
340
- init({
341
- service: 'batch-test',
342
- subscribers: [testAdapter],
343
- });
344
-
345
- const startTime = Date.now();
346
-
347
- // Track 500 events
348
- for (let i = 0; i < 500; i++) {
349
- track(`event.${i}`, { index: i });
350
- }
351
-
352
- await flush({ timeout: 10_000 }); // 10s timeout for high-volume test
353
-
354
- const duration = Date.now() - startTime;
355
-
356
- // Should complete in reasonable time (batching improves performance)
357
- // This is a sanity check - actual threshold depends on hardware
358
- expect(duration).toBeLessThan(10_000); // 10 seconds (increased for CI/CD reliability)
359
- });
360
- });
361
- });