@elisra-devops/docgen-data-provider 1.140.0 → 1.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/bin/helpers/requestContext.d.ts +51 -0
  3. package/bin/helpers/requestContext.js +218 -0
  4. package/bin/helpers/requestContext.js.map +1 -0
  5. package/bin/helpers/tfs.d.ts +5 -0
  6. package/bin/helpers/tfs.js +24 -24
  7. package/bin/helpers/tfs.js.map +1 -1
  8. package/bin/modules/GitDataProvider.js +3 -2
  9. package/bin/modules/GitDataProvider.js.map +1 -1
  10. package/bin/modules/JfrogDataProvider.js +3 -2
  11. package/bin/modules/JfrogDataProvider.js.map +1 -1
  12. package/bin/modules/PipelinesDataProvider.js +5 -4
  13. package/bin/modules/PipelinesDataProvider.js.map +1 -1
  14. package/bin/modules/ResultDataProvider.js +32 -25
  15. package/bin/modules/ResultDataProvider.js.map +1 -1
  16. package/bin/modules/TestDataProvider.js +4 -3
  17. package/bin/modules/TestDataProvider.js.map +1 -1
  18. package/bin/modules/TicketsDataProvider.js +26 -22
  19. package/bin/modules/TicketsDataProvider.js.map +1 -1
  20. package/bin/tests/helpers/requestContext.test.d.ts +1 -0
  21. package/bin/tests/helpers/requestContext.test.js +165 -0
  22. package/bin/tests/helpers/requestContext.test.js.map +1 -0
  23. package/bin/tests/helpers/tfs.test.js +54 -0
  24. package/bin/tests/helpers/tfs.test.js.map +1 -1
  25. package/bin/tests/modules/JfrogDataProvider.test.js +4 -2
  26. package/bin/tests/modules/JfrogDataProvider.test.js.map +1 -1
  27. package/bin/tests/modules/ResultDataProvider.test.js +9 -3
  28. package/bin/tests/modules/ResultDataProvider.test.js.map +1 -1
  29. package/bin/tests/modules/gitDataProvider.test.js +1 -1
  30. package/bin/tests/modules/gitDataProvider.test.js.map +1 -1
  31. package/bin/tests/modules/pipelineDataProvider.test.js +1 -1
  32. package/bin/tests/modules/pipelineDataProvider.test.js.map +1 -1
  33. package/bin/tests/modules/testDataProvider.test.js +1 -1
  34. package/bin/tests/modules/testDataProvider.test.js.map +1 -1
  35. package/bin/tests/modules/ticketsDataProvider.test.js +2 -2
  36. package/bin/tests/modules/ticketsDataProvider.test.js.map +1 -1
  37. package/bin/tests/utils/logger.test.d.ts +1 -0
  38. package/bin/tests/utils/logger.test.js +332 -0
  39. package/bin/tests/utils/logger.test.js.map +1 -0
  40. package/bin/tests/utils/runContext.test.d.ts +1 -0
  41. package/bin/tests/utils/runContext.test.js +51 -0
  42. package/bin/tests/utils/runContext.test.js.map +1 -0
  43. package/bin/utils/logSink.d.ts +39 -0
  44. package/bin/utils/logSink.js +28 -0
  45. package/bin/utils/logSink.js.map +1 -0
  46. package/bin/utils/logger.d.ts +7 -0
  47. package/bin/utils/logger.js +266 -27
  48. package/bin/utils/logger.js.map +1 -1
  49. package/bin/utils/runContext.d.ts +8 -0
  50. package/bin/utils/runContext.js +12 -0
  51. package/bin/utils/runContext.js.map +1 -0
  52. package/eslint.config.mjs +40 -0
  53. package/package.json +8 -3
  54. package/src/helpers/requestContext.ts +222 -0
  55. package/src/helpers/tfs.ts +30 -24
  56. package/src/modules/GitDataProvider.ts +3 -2
  57. package/src/modules/JfrogDataProvider.ts +3 -2
  58. package/src/modules/PipelinesDataProvider.ts +5 -4
  59. package/src/modules/ResultDataProvider.ts +31 -25
  60. package/src/modules/TestDataProvider.ts +4 -3
  61. package/src/modules/TicketsDataProvider.ts +28 -26
  62. package/src/tests/helpers/requestContext.test.ts +202 -0
  63. package/src/tests/helpers/tfs.test.ts +86 -0
  64. package/src/tests/modules/JfrogDataProvider.test.ts +5 -2
  65. package/src/tests/modules/ResultDataProvider.test.ts +10 -3
  66. package/src/tests/modules/gitDataProvider.test.ts +2 -1
  67. package/src/tests/modules/pipelineDataProvider.test.ts +2 -1
  68. package/src/tests/modules/testDataProvider.test.ts +4 -1
  69. package/src/tests/modules/ticketsDataProvider.test.ts +2 -2
  70. package/src/tests/utils/logger.test.ts +381 -0
  71. package/src/tests/utils/runContext.test.ts +48 -0
  72. package/src/utils/logSink.ts +59 -0
  73. package/src/utils/logger.ts +269 -29
  74. package/src/utils/runContext.ts +25 -0
@@ -0,0 +1,381 @@
1
+ import * as winston from 'winston';
2
+ import Transport = require('winston-transport');
3
+ import { redact, DiagnosticsTransport } from '../../utils/logger';
4
+ import { installLogSink, LogSink, DiagnosticEvent } from '../../utils/logSink';
5
+ import { runContextStore } from '../../utils/runContext';
6
+
7
+ const applyRedact = (info: Record<string, unknown>) => (redact() as any).transform({ ...info });
8
+
9
+ describe('logger redact format', () => {
10
+ test('scrubs a top-level token/password/secret regardless of key casing', () => {
11
+ const out = applyRedact({ level: 'info', message: 'x', token: 'abc', Password: 'p', SECRET: 's' });
12
+ expect(out.token).toBe('[REDACTED]');
13
+ expect(out.Password).toBe('[REDACTED]');
14
+ expect(out.SECRET).toBe('[REDACTED]');
15
+ });
16
+
17
+ test('scrubs nested config.auth.password and config.headers.Authorization — the AxiosError.toJSON() leak', () => {
18
+ // This is the exact shape that was leaking via logger.error(JSON.stringify(error))
19
+ // in TicketsDataProvider.ts on ADO batch work-item failures.
20
+ const axiosLikeError = {
21
+ message: 'Request failed',
22
+ config: {
23
+ auth: { username: '', password: 'super-secret-pat' },
24
+ headers: { Authorization: 'Bearer abc.def.ghi' },
25
+ },
26
+ };
27
+ const out: any = applyRedact({ level: 'error', message: 'error populating workitems array', err: axiosLikeError });
28
+ expect(out.err.config.auth.password).toBe('[REDACTED]');
29
+ expect(out.err.config.headers.Authorization).toBe('[REDACTED]');
30
+ expect(out.err.message).toBe('Request failed');
31
+ });
32
+
33
+ test('leaves non-sensitive fields untouched', () => {
34
+ const out = applyRedact({ level: 'info', message: 'ok', project: 'Cube-ADCS', docType: 'SVD' });
35
+ expect(out.project).toBe('Cube-ADCS');
36
+ expect(out.docType).toBe('SVD');
37
+ });
38
+
39
+ test('never throws on a circular object', () => {
40
+ const circular: any = { name: 'x' };
41
+ circular.self = circular;
42
+ expect(() => applyRedact({ level: 'info', message: 'x', circular })).not.toThrow();
43
+ });
44
+
45
+ test('never throws and passes info through on null/undefined meta', () => {
46
+ expect(() => applyRedact({ level: 'info', message: 'x', meta: null })).not.toThrow();
47
+ expect(() => applyRedact({ level: 'info', message: 'x', meta: undefined })).not.toThrow();
48
+ });
49
+ });
50
+
51
+ // A capturing transport + the exact JSON format chain logger.ts uses (errors -> timestamp ->
52
+ // redact -> splat -> json), so these tests exercise the real pipeline, not just redact() alone.
53
+ class CaptureTransport extends Transport {
54
+ lines: Record<string, unknown>[] = [];
55
+ log(info: Record<string, unknown>, callback: () => void) {
56
+ this.lines.push(JSON.parse((info as any)[Symbol.for('message')] ?? JSON.stringify(info)));
57
+ callback();
58
+ }
59
+ }
60
+ function makeTestLogger() {
61
+ const capture = new CaptureTransport();
62
+ const logger = winston.createLogger({
63
+ level: 'silly',
64
+ format: winston.format.combine(
65
+ winston.format.errors({ stack: true }),
66
+ winston.format.timestamp(),
67
+ redact(),
68
+ winston.format.splat(),
69
+ winston.format.json()
70
+ ),
71
+ transports: [capture],
72
+ });
73
+ return { logger, capture };
74
+ }
75
+
76
+ describe('logger pipeline — errors({stack:true})', () => {
77
+ test('logger.error(err) (single-arg Error) still produces a non-empty message and a stack', () => {
78
+ // This is the regression errors({stack:true}) exists to prevent: without it, winston's
79
+ // single-arg path makes `info` *be* the Error, and message/stack are non-enumerable, so
80
+ // json() would emit {"level":"error","timestamp":"…"} — content-free.
81
+ const { logger, capture } = makeTestLogger();
82
+ logger.error(new Error('boom'));
83
+ expect(capture.lines).toHaveLength(1);
84
+ expect(capture.lines[0].message).toBe('boom');
85
+ expect(typeof capture.lines[0].stack).toBe('string');
86
+ expect((capture.lines[0].stack as string).length).toBeGreaterThan(0);
87
+ });
88
+ });
89
+
90
+ describe('logger pipeline — hostile inputs never throw', () => {
91
+ test.each([
92
+ ['null', null],
93
+ ['undefined', undefined],
94
+ ['NaN', NaN],
95
+ ['a circular object', (() => { const c: any = { a: 1 }; c.self = c; return c; })()],
96
+ ['an object with a throwing getter', { get boom() { throw new Error('nope'); } }],
97
+ ['a BigInt', BigInt(9007199254740993)],
98
+ ['a Symbol', Symbol('x')],
99
+ ['an Error with no message', new Error()],
100
+ ['a 10MB string', 'x'.repeat(10 * 1024 * 1024)],
101
+ ])('logger.error(%s) does not throw', (_label, value) => {
102
+ const { logger } = makeTestLogger();
103
+ expect(() => logger.error(value as any)).not.toThrow();
104
+ });
105
+ });
106
+
107
+ describe('DiagnosticsTransport (Phase 6a)', () => {
108
+ function makeDiagnosticsLogger() {
109
+ const capture = new CaptureTransport();
110
+ const logger = winston.createLogger({
111
+ level: 'silly',
112
+ format: winston.format.combine(
113
+ winston.format.errors({ stack: true }),
114
+ winston.format.timestamp(),
115
+ redact(),
116
+ winston.format.splat(),
117
+ winston.format.json()
118
+ ),
119
+ transports: [capture, new DiagnosticsTransport()],
120
+ });
121
+ return { logger, capture };
122
+ }
123
+
124
+ test('pushes warn/error records to whatever sink is installed', () => {
125
+ const events: DiagnosticEvent[] = [];
126
+ const sink: LogSink = { push: (e) => events.push(e) };
127
+ installLogSink(sink);
128
+ const { logger } = makeDiagnosticsLogger();
129
+ logger.warn('a stable warning');
130
+ logger.error('a stable error', Object.assign(new Error('boom'), { code: 'ECONN' }));
131
+ expect(events).toHaveLength(2);
132
+ expect(events[0].level).toBe('warn');
133
+ expect(events[1].err?.code).toBe('ECONN');
134
+ expect(events[1].err?.stack).toEqual(expect.any(String));
135
+ });
136
+
137
+ test('does not push info/debug records', () => {
138
+ const events: DiagnosticEvent[] = [];
139
+ installLogSink({ push: (e) => events.push(e) });
140
+ const { logger } = makeDiagnosticsLogger();
141
+ logger.info('not interesting to the dashboard');
142
+ expect(events).toHaveLength(0);
143
+ });
144
+
145
+ test('a throwing sink cannot break the log call', () => {
146
+ installLogSink({
147
+ push: () => {
148
+ throw new Error('sink is down');
149
+ },
150
+ });
151
+ const { logger } = makeDiagnosticsLogger();
152
+ expect(() => logger.error('still must not throw')).not.toThrow();
153
+ });
154
+
155
+ test.each([
156
+ ['null', null],
157
+ ['undefined', undefined],
158
+ ['NaN', NaN],
159
+ ['a circular object', (() => { const c: any = { a: 1 }; c.self = c; return c; })()],
160
+ ['an object with a throwing getter', { get boom() { throw new Error('nope'); } }],
161
+ ['a BigInt', BigInt(9007199254740993)],
162
+ ['a Symbol', Symbol('x')],
163
+ ['an Error with no message', new Error()],
164
+ ['a 10MB string', 'x'.repeat(10 * 1024 * 1024)],
165
+ ])('logger.error(%s) with a sink installed does not throw', (_label, value) => {
166
+ installLogSink({ push: () => undefined });
167
+ const { logger } = makeDiagnosticsLogger();
168
+ expect(() => logger.error(value as any)).not.toThrow();
169
+ });
170
+ });
171
+
172
+ describe('DiagnosticsTransport request context', () => {
173
+ function makeLogger() {
174
+ return winston.createLogger({
175
+ level: 'silly',
176
+ format: winston.format.combine(
177
+ winston.format.errors({ stack: true }),
178
+ winston.format.timestamp(),
179
+ redact(),
180
+ winston.format.splat(),
181
+ winston.format.json()
182
+ ),
183
+ transports: [new DiagnosticsTransport()],
184
+ });
185
+ }
186
+
187
+ test('persists an annotated error\'s request as event.context, however the call site words its message', () => {
188
+ const events: DiagnosticEvent[] = [];
189
+ installLogSink({ push: (e) => events.push(e) });
190
+ const err = Object.assign(new Error('Request failed with status code 404'), {
191
+ adoRequest: { method: 'GET', url: 'https://dev.azure.com/org/_apis/x', status: 404, attempt: 1, responseExcerpt: 'nope' },
192
+ });
193
+
194
+ makeLogger().error(err); // the bare-error shape (3 call sites) — no stable message at all
195
+
196
+ expect(events[0].context).toEqual({
197
+ method: 'GET',
198
+ url: 'https://dev.azure.com/org/_apis/x',
199
+ status: 404,
200
+ attempt: 1,
201
+ responseExcerpt: 'nope',
202
+ });
203
+ });
204
+
205
+ test('also works for the stable-message + error shape and for the explicit meta shape', () => {
206
+ const events: DiagnosticEvent[] = [];
207
+ installLogSink({ push: (e) => events.push(e) });
208
+ const logger = makeLogger();
209
+ const ctx = { method: 'POST', url: 'https://h/wiql', requestBody: '{"query":"q"}' };
210
+
211
+ logger.error('Failed querying work items', Object.assign(new Error('boom'), { adoRequest: ctx }));
212
+ logger.error('ADO request failed', { message: 'boom', stack: 'at x', adoRequest: ctx });
213
+
214
+ expect(events[0].context).toEqual(ctx);
215
+ expect(events[1].context).toEqual(ctx);
216
+ });
217
+
218
+ test('an event with no request context has no context field', () => {
219
+ const events: DiagnosticEvent[] = [];
220
+ installLogSink({ push: (e) => events.push(e) });
221
+ makeLogger().error('plain failure', new Error('boom'));
222
+ expect(events[0].context).toBeUndefined();
223
+ });
224
+
225
+ test('re-validates the shape at the transport: unknown keys, wrong types and oversize values are dropped or bounded', () => {
226
+ const events: DiagnosticEvent[] = [];
227
+ installLogSink({ push: (e) => events.push(e) });
228
+ const err = Object.assign(new Error('x'), {
229
+ adoRequest: {
230
+ method: 'GET',
231
+ url: 'u'.repeat(5000),
232
+ status: 'not-a-number',
233
+ attempt: 2,
234
+ requestBody: 'b'.repeat(5000),
235
+ secretHeader: 'Bearer abc',
236
+ },
237
+ });
238
+
239
+ makeLogger().error('m', err);
240
+
241
+ const ctx = events[0].context!;
242
+ expect(ctx.url!.length).toBe(1000);
243
+ expect(ctx.requestBody!.length).toBe(2000);
244
+ expect(ctx.status).toBeUndefined();
245
+ expect(ctx.attempt).toBe(2);
246
+ expect(ctx).not.toHaveProperty('secretHeader');
247
+ });
248
+ });
249
+
250
+ describe('text format request suffix', () => {
251
+ // The default (LOG_FORMAT unset) prints only the message — without this the URL would never
252
+ // reach stdout for a record whose own message doesn't carry it. A stream transport on the
253
+ // real logger receives the already-formatted line, independent of how jest wires console.
254
+ test('appends the request to the printed line when the error carries one, and never throws', () => {
255
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
256
+ const logger = require('../../utils/logger').default;
257
+ const { Writable } = require('stream');
258
+ const lines: string[] = [];
259
+ const sink = new winston.transports.Stream({
260
+ stream: new Writable({
261
+ write(chunk: Buffer, _enc: string, cb: () => void) {
262
+ lines.push(chunk.toString());
263
+ cb();
264
+ },
265
+ }),
266
+ });
267
+ logger.add(sink);
268
+ try {
269
+ const err = Object.assign(new Error('Request failed with status code 404'), {
270
+ adoRequest: { method: 'GET', url: 'https://dev.azure.com/org/_apis/x', status: 404 },
271
+ });
272
+ expect(() => logger.error('Failed fetching', err)).not.toThrow();
273
+ expect(() => logger.error('odd', Object.assign(new Error('e'), { adoRequest: { url: 123 } }))).not.toThrow();
274
+ } finally {
275
+ logger.remove(sink);
276
+ }
277
+ const joined = lines.join('');
278
+ expect(joined).toContain('[GET https://dev.azure.com/org/_apis/x -> 404]');
279
+ expect(joined).toContain('Failed fetching');
280
+ });
281
+ });
282
+
283
+ describe('textFormat safety (regression)', () => {
284
+ // The hostile-input matrix above exercises makeTestLogger()'s json() pipeline — it never
285
+ // touched the real singleton logger's text-format branch (LOG_FORMAT's default), which is
286
+ // where a Symbol message crashed: a template literal's implicit ToString throws on a Symbol,
287
+ // and this formatter sits with no try/catch around it.
288
+ test('logger.error(Symbol) does not throw through the real default-exported logger', () => {
289
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
290
+ const logger = require('../../utils/logger').default;
291
+ expect(() => logger.error(Symbol('x'))).not.toThrow();
292
+ });
293
+ });
294
+
295
+ describe('DiagnosticsTransport capture policy (Phase 6b)', () => {
296
+ function makeDiagnosticsLogger() {
297
+ const capture = new CaptureTransport();
298
+ const logger = winston.createLogger({
299
+ level: 'silly',
300
+ format: winston.format.combine(
301
+ winston.format.errors({ stack: true }),
302
+ winston.format.timestamp(),
303
+ redact(),
304
+ winston.format.splat(),
305
+ winston.format.json()
306
+ ),
307
+ transports: [capture, new DiagnosticsTransport()],
308
+ });
309
+ return { logger, capture };
310
+ }
311
+
312
+ test('normal mode (no captureMode) does not persist debug/info', () => {
313
+ const events: DiagnosticEvent[] = [];
314
+ installLogSink({ push: (e) => events.push(e) });
315
+ const { logger } = makeDiagnosticsLogger();
316
+ runContextStore.run({ runId: 'run-1' }, () => {
317
+ logger.debug('a debug line');
318
+ logger.info('an info line');
319
+ });
320
+ expect(events).toHaveLength(0);
321
+ });
322
+
323
+ test('verbose mode persists debug and info', () => {
324
+ const events: DiagnosticEvent[] = [];
325
+ installLogSink({ push: (e) => events.push(e) });
326
+ const { logger } = makeDiagnosticsLogger();
327
+ runContextStore.run({ runId: 'run-2', captureMode: 'verbose' }, () => {
328
+ logger.debug('a debug line');
329
+ logger.info('an info line');
330
+ });
331
+ expect(events).toHaveLength(2);
332
+ expect(events[0].retainPending).toBeUndefined();
333
+ });
334
+
335
+ test('warn/error persist regardless of capture mode', () => {
336
+ const events: DiagnosticEvent[] = [];
337
+ installLogSink({ push: (e) => events.push(e) });
338
+ const { logger } = makeDiagnosticsLogger();
339
+ runContextStore.run({ runId: 'run-3' }, () => {
340
+ logger.warn('a warning');
341
+ logger.error('an error');
342
+ });
343
+ expect(events).toHaveLength(2);
344
+ });
345
+
346
+ test('retain-on-failure persists debug/info tagged retainPending: true', () => {
347
+ const events: DiagnosticEvent[] = [];
348
+ installLogSink({ push: (e) => events.push(e) });
349
+ const { logger } = makeDiagnosticsLogger();
350
+ runContextStore.run({ runId: 'run-4', captureMode: 'retain-on-failure' }, () => {
351
+ logger.debug('a debug line');
352
+ });
353
+ expect(events).toHaveLength(1);
354
+ expect(events[0].retainPending).toBe(true);
355
+ });
356
+
357
+ test('retain-on-failure does not tag warn/error as retainPending', () => {
358
+ const events: DiagnosticEvent[] = [];
359
+ installLogSink({ push: (e) => events.push(e) });
360
+ const { logger } = makeDiagnosticsLogger();
361
+ runContextStore.run({ runId: 'run-5', captureMode: 'retain-on-failure' }, () => {
362
+ logger.error('an error');
363
+ });
364
+ expect(events).toHaveLength(1);
365
+ expect(events[0].retainPending).toBeUndefined();
366
+ });
367
+
368
+ test('a concurrent normal-mode run is unaffected by a sibling verbose run', () => {
369
+ const events: DiagnosticEvent[] = [];
370
+ installLogSink({ push: (e) => events.push(e) });
371
+ const { logger } = makeDiagnosticsLogger();
372
+ runContextStore.run({ runId: 'verbose-run', captureMode: 'verbose' }, () => {
373
+ logger.debug('verbose debug');
374
+ });
375
+ runContextStore.run({ runId: 'normal-run' }, () => {
376
+ logger.debug('normal debug');
377
+ });
378
+ expect(events).toHaveLength(1);
379
+ expect(events[0].message).toBe('verbose debug');
380
+ });
381
+ });
@@ -0,0 +1,48 @@
1
+ import * as winston from 'winston';
2
+ import Transport = require('winston-transport');
3
+ import { withRunContext } from '../../utils/logger';
4
+ import { runContextStore } from '../../utils/runContext';
5
+
6
+ class CaptureTransport extends Transport {
7
+ lines: Record<string, unknown>[] = [];
8
+ log(info: Record<string, unknown>, callback: () => void) {
9
+ this.lines.push(JSON.parse((info as any)[Symbol.for('message')] ?? JSON.stringify(info)));
10
+ callback();
11
+ }
12
+ }
13
+ function makeTestLogger() {
14
+ const capture = new CaptureTransport();
15
+ const logger = winston.createLogger({
16
+ level: 'silly',
17
+ format: winston.format.combine(withRunContext(), winston.format.json()),
18
+ transports: [capture],
19
+ });
20
+ return { logger, capture };
21
+ }
22
+
23
+ describe('withRunContext', () => {
24
+ test('is a no-op when the store was never populated', () => {
25
+ const { logger, capture } = makeTestLogger();
26
+ logger.info('outside any run');
27
+ expect(capture.lines[0].runId).toBeUndefined();
28
+ });
29
+
30
+ test('stamps runId onto every log emitted inside store.run(...)', () => {
31
+ const { logger, capture } = makeTestLogger();
32
+ runContextStore.run({ runId: 'run-123' }, () => {
33
+ logger.info('inside the run');
34
+ });
35
+ logger.info('outside again');
36
+ expect(capture.lines[0].runId).toBe('run-123');
37
+ expect(capture.lines[1].runId).toBeUndefined();
38
+ });
39
+
40
+ test('async work started inside the run keeps the runId across the await boundary', async () => {
41
+ const { logger, capture } = makeTestLogger();
42
+ await runContextStore.run({ runId: 'run-async' }, async () => {
43
+ await new Promise((resolve) => setTimeout(resolve, 0));
44
+ logger.info('after await');
45
+ });
46
+ expect(capture.lines[0].runId).toBe('run-async');
47
+ });
48
+ });
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ // The one queryable-error-store event shape, emitted by DiagnosticsTransport (logger.ts).
4
+ // This package never installs a sink itself — it only reads whatever the host process
5
+ // (docgen-content-control's index.ts) installed. err stays narrow — {message, code, stack}.
6
+ // `context` is the one deliberate exception to "no extra-fields bucket": a sanitized
7
+ // description of the failed outbound request (method, url, status, attempt, request-body
8
+ // summary, response excerpt) — without it a 404 in the dashboard can't be traced to the call
9
+ // that produced it. A fixed, allowlisted shape, not a free-form bag.
10
+ // Bounds for DiagnosticEvent.context. Single source for this package (requestContext.ts and the
11
+ // logger transport); docgen-api-gate's DiagnosticsController.sanitizeContext re-validates at
12
+ // ingest with its own copy — keep the two in step.
13
+ export const CONTEXT_LIMITS = { method: 10, url: 1000, requestBody: 2000, responseExcerpt: 300 } as const;
14
+
15
+ export interface DiagnosticEvent {
16
+ ts: string;
17
+ level: string;
18
+ service: string;
19
+ version: string;
20
+ runId?: string;
21
+ docType?: string;
22
+ step?: string;
23
+ contentControlType?: string;
24
+ contentControlTitle?: string;
25
+ project?: string;
26
+ userId?: string;
27
+ message: string;
28
+ err?: { message: string; code?: string; stack?: string };
29
+ context?: {
30
+ method?: string;
31
+ url?: string;
32
+ status?: number;
33
+ attempt?: number;
34
+ requestBody?: string;
35
+ responseExcerpt?: string;
36
+ };
37
+ // Phase 6b — set on a debug/info event captured under retain-on-failure. Deleted by
38
+ // api-gate at the run's one success point; left alone (and thus permanent, subject to the
39
+ // normal TTL) if the run fails.
40
+ retainPending?: boolean;
41
+ }
42
+
43
+ export interface LogSink {
44
+ push(event: DiagnosticEvent): void;
45
+ }
46
+
47
+ // Symbol.for so this package's copy converges on the same installed sink as
48
+ // docgen-content-control's (the host process this package runs inside) and
49
+ // docgen-dg-skins-package's, the same reasoning as runContext.ts's AsyncLocalStorage. A
50
+ // never-populated sink is a harmless no-op — this package only reads it, never installs one.
51
+ const KEY = Symbol.for('elisradevops.docgen.logSink');
52
+
53
+ export function getLogSink(): LogSink | undefined {
54
+ return (globalThis as Record<symbol, unknown>)[KEY] as LogSink | undefined;
55
+ }
56
+
57
+ export function installLogSink(sink: LogSink): void {
58
+ (globalThis as Record<symbol, unknown>)[KEY] = sink;
59
+ }