@geekmidas/telescope 9.0.2 → 10.0.0-alpha.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 (122) hide show
  1. package/README.md +14 -4
  2. package/dist/{http-D5kn3_Mt.d.mts → http-BiNtg85L.d.mts} +3 -3
  3. package/dist/{http-D5kn3_Mt.d.mts.map → http-BiNtg85L.d.mts.map} +1 -1
  4. package/dist/instrumentation/http.d.mts +1 -1
  5. package/dist/instrumentation/index.cjs +2 -2
  6. package/dist/instrumentation/index.d.cts +2 -2
  7. package/dist/instrumentation/index.d.mts +3 -3
  8. package/dist/instrumentation/index.mjs +2 -2
  9. package/dist/instrumentation/middleware.cjs +1 -1
  10. package/dist/instrumentation/middleware.d.cts +1 -1
  11. package/dist/instrumentation/middleware.d.mts +1 -1
  12. package/dist/instrumentation/middleware.mjs +1 -1
  13. package/dist/instrumentation/otel.cjs +1 -1
  14. package/dist/instrumentation/otel.d.cts +1 -1
  15. package/dist/instrumentation/otel.d.mts +1 -1
  16. package/dist/instrumentation/otel.mjs +1 -1
  17. package/dist/logger/console.d.cts.map +1 -1
  18. package/dist/logger/pino.d.mts +2 -2
  19. package/dist/{middleware-DqPQpcup.cjs → middleware-Bcq6XXGG.cjs} +2 -2
  20. package/dist/middleware-Bcq6XXGG.cjs.map +1 -0
  21. package/dist/{middleware-4-GrQlOT.mjs → middleware-D1XEHvyy.mjs} +2 -2
  22. package/dist/middleware-D1XEHvyy.mjs.map +1 -0
  23. package/dist/{middleware-CA84nsNN.d.cts → middleware-PeyS-9Ny.d.cts} +2 -2
  24. package/dist/{middleware-CA84nsNN.d.cts.map → middleware-PeyS-9Ny.d.cts.map} +1 -1
  25. package/dist/{middleware-DAceVpfw.d.mts → middleware-oHvo_ZgU.d.mts} +2 -2
  26. package/dist/{middleware-DAceVpfw.d.mts.map → middleware-oHvo_ZgU.d.mts.map} +1 -1
  27. package/dist/{otel-40udNP5g.mjs → otel-B9bNoeZ2.mjs} +3 -3
  28. package/dist/otel-B9bNoeZ2.mjs.map +1 -0
  29. package/dist/{otel-SBVoVEHr.d.cts → otel-Bk89b1lX.d.cts} +3 -3
  30. package/dist/{otel-1bJPb2Z7.d.mts.map → otel-Bk89b1lX.d.cts.map} +1 -1
  31. package/dist/{otel-COrpz_GZ.cjs → otel-BzjOtVxZ.cjs} +3 -3
  32. package/dist/otel-BzjOtVxZ.cjs.map +1 -0
  33. package/dist/{otel-1bJPb2Z7.d.mts → otel-lPMsM26e.d.mts} +3 -3
  34. package/dist/{otel-SBVoVEHr.d.cts.map → otel-lPMsM26e.d.mts.map} +1 -1
  35. package/dist/storage/kysely.cjs +48 -38
  36. package/dist/storage/kysely.cjs.map +1 -1
  37. package/dist/storage/kysely.d.cts +29 -9
  38. package/dist/storage/kysely.d.cts.map +1 -1
  39. package/dist/storage/kysely.d.mts +29 -9
  40. package/dist/storage/kysely.d.mts.map +1 -1
  41. package/dist/storage/kysely.mjs +48 -38
  42. package/dist/storage/kysely.mjs.map +1 -1
  43. package/dist/tracing-PnECEbEu.d.mts.map +1 -1
  44. package/package.json +6 -3
  45. package/CHANGELOG.md +0 -72
  46. package/dist/middleware-4-GrQlOT.mjs.map +0 -1
  47. package/dist/middleware-DqPQpcup.cjs.map +0 -1
  48. package/dist/otel-40udNP5g.mjs.map +0 -1
  49. package/dist/otel-COrpz_GZ.cjs.map +0 -1
  50. package/src/Telescope.ts +0 -561
  51. package/src/__tests__/Telescope.spec.ts +0 -438
  52. package/src/__tests__/pino-transport.spec.ts +0 -115
  53. package/src/__tests__/redact.spec.ts +0 -336
  54. package/src/adapters/__tests__/lambda.spec.ts +0 -318
  55. package/src/adapters/__tests__/middy.spec.ts +0 -741
  56. package/src/adapters/index.ts +0 -22
  57. package/src/adapters/lambda.ts +0 -432
  58. package/src/adapters/middy.ts +0 -402
  59. package/src/adapters/types.ts +0 -181
  60. package/src/core.ts +0 -51
  61. package/src/index.ts +0 -34
  62. package/src/instrumentation/__tests__/core.spec.ts +0 -248
  63. package/src/instrumentation/__tests__/hono.spec.ts +0 -348
  64. package/src/instrumentation/__tests__/middleware.spec.ts +0 -528
  65. package/src/instrumentation/__tests__/otel.spec.ts +0 -291
  66. package/src/instrumentation/__tests__/tracing.spec.ts +0 -208
  67. package/src/instrumentation/core.ts +0 -228
  68. package/src/instrumentation/hono.ts +0 -270
  69. package/src/instrumentation/http.ts +0 -306
  70. package/src/instrumentation/index.ts +0 -90
  71. package/src/instrumentation/middleware.ts +0 -297
  72. package/src/instrumentation/otel.ts +0 -271
  73. package/src/instrumentation/setup.ts +0 -246
  74. package/src/instrumentation/tracing.ts +0 -145
  75. package/src/logger/__tests__/console.spec.ts +0 -366
  76. package/src/logger/__tests__/pino.spec.ts +0 -217
  77. package/src/logger/console.ts +0 -230
  78. package/src/logger/pino.ts +0 -201
  79. package/src/metrics/MetricsAggregator.ts +0 -555
  80. package/src/metrics/__tests__/MetricsAggregator.spec.ts +0 -298
  81. package/src/metrics/index.ts +0 -2
  82. package/src/metrics/storage/InMemoryMetricsStorage.ts +0 -380
  83. package/src/metrics/storage/MetricsStorage.ts +0 -74
  84. package/src/metrics/storage/index.ts +0 -3
  85. package/src/metrics/storage/types.ts +0 -243
  86. package/src/otlp/__tests__/receiver.spec.ts +0 -367
  87. package/src/otlp/__tests__/transformer.spec.ts +0 -455
  88. package/src/otlp/hono.ts +0 -120
  89. package/src/otlp/index.ts +0 -22
  90. package/src/otlp/receiver.ts +0 -162
  91. package/src/otlp/transformer.ts +0 -367
  92. package/src/otlp/types.ts +0 -364
  93. package/src/redact.ts +0 -116
  94. package/src/server/__tests__/hono.spec.ts +0 -814
  95. package/src/server/hono.ts +0 -442
  96. package/src/storage/__tests__/kysely.spec.ts +0 -715
  97. package/src/storage/__tests__/memory.spec.ts +0 -694
  98. package/src/storage/kysely.ts +0 -599
  99. package/src/storage/memory.ts +0 -204
  100. package/src/types.ts +0 -447
  101. package/src/ui-assets.ts +0 -40
  102. package/tsconfig.json +0 -9
  103. package/ui/CHANGELOG.md +0 -7
  104. package/ui/index.html +0 -12
  105. package/ui/node_modules/.bin/tsc +0 -21
  106. package/ui/node_modules/.bin/tsserver +0 -21
  107. package/ui/node_modules/.bin/vite +0 -21
  108. package/ui/package.json +0 -24
  109. package/ui/src/App.tsx +0 -595
  110. package/ui/src/api.ts +0 -88
  111. package/ui/src/components/ExceptionDetail.tsx +0 -100
  112. package/ui/src/components/FilterBar.tsx +0 -162
  113. package/ui/src/components/LogDetail.tsx +0 -91
  114. package/ui/src/components/RequestDetail.tsx +0 -143
  115. package/ui/src/main.tsx +0 -10
  116. package/ui/src/styles.css +0 -11
  117. package/ui/src/types.ts +0 -63
  118. package/ui/src/vite-env.d.ts +0 -1
  119. package/ui/src/vite-plugin-gkm-config.ts +0 -54
  120. package/ui/tsconfig.json +0 -20
  121. package/ui/tsconfig.tsbuildinfo +0 -1
  122. package/ui/vite.config.ts +0 -13
@@ -1,599 +0,0 @@
1
- import type { Kysely } from 'kysely';
2
- import type {
3
- ExceptionEntry,
4
- LogEntry,
5
- QueryOptions,
6
- RequestEntry,
7
- TelescopeStats,
8
- TelescopeStorage,
9
- } from '../types';
10
-
11
- /**
12
- * Database table interface for telescope requests.
13
- * Use this to define your telescope_requests table in your Kysely database schema.
14
- */
15
- export interface TelescopeRequestTable {
16
- id: string;
17
- method: string;
18
- path: string;
19
- url: string;
20
- headers: unknown;
21
- body: unknown | null;
22
- query: unknown | null;
23
- status: number;
24
- response_headers: unknown;
25
- response_body: unknown | null;
26
- duration: number;
27
- timestamp: Date;
28
- ip: string | null;
29
- user_id: string | null;
30
- tags: unknown | null;
31
- }
32
-
33
- /**
34
- * Database table interface for telescope exceptions.
35
- */
36
- export interface TelescopeExceptionTable {
37
- id: string;
38
- name: string;
39
- message: string;
40
- stack: unknown;
41
- source: unknown | null;
42
- request_id: string | null;
43
- timestamp: Date;
44
- handled: boolean;
45
- tags: unknown | null;
46
- }
47
-
48
- /**
49
- * Database table interface for telescope logs.
50
- */
51
- export interface TelescopeLogTable {
52
- id: string;
53
- level: string;
54
- message: string;
55
- context: unknown | null;
56
- request_id: string | null;
57
- timestamp: Date;
58
- }
59
-
60
- /**
61
- * Combined database interface for all telescope tables.
62
- * Use this to extend your database schema.
63
- *
64
- * @example
65
- * ```typescript
66
- * import type { TelescopeTables } from '@geekmidas/telescope/storage/kysely';
67
- *
68
- * interface Database extends TelescopeTables {
69
- * users: UserTable;
70
- * // ... other tables
71
- * }
72
- * ```
73
- */
74
- export interface TelescopeTables {
75
- telescope_requests: TelescopeRequestTable;
76
- telescope_exceptions: TelescopeExceptionTable;
77
- telescope_logs: TelescopeLogTable;
78
- }
79
-
80
- /**
81
- * Configuration for KyselyStorage.
82
- */
83
- export interface KyselyStorageConfig<DB> {
84
- /** Kysely database instance */
85
- db: Kysely<DB>;
86
- /**
87
- * Table name prefix (default: 'telescope').
88
- * Tables will be named: {prefix}_requests, {prefix}_exceptions, {prefix}_logs
89
- */
90
- tablePrefix?: string;
91
- }
92
-
93
- /**
94
- * Kysely-based storage implementation for Telescope.
95
- * Stores telescope data in PostgreSQL, MySQL, or SQLite using Kysely.
96
- *
97
- * @template DB - Your Kysely database schema (must include TelescopeTables)
98
- *
99
- * @example
100
- * ```typescript
101
- * import { Kysely, PostgresDialect } from 'kysely';
102
- * import { KyselyStorage, type TelescopeTables } from '@geekmidas/telescope/storage/kysely';
103
- *
104
- * interface Database extends TelescopeTables {
105
- * users: UserTable;
106
- * }
107
- *
108
- * const db = new Kysely<Database>({ dialect: new PostgresDialect({ pool }) });
109
- * const storage = new KyselyStorage({ db });
110
- *
111
- * const telescope = new Telescope({ storage });
112
- * ```
113
- */
114
- export class KyselyStorage<DB> implements TelescopeStorage {
115
- private readonly db: Kysely<DB>;
116
- private readonly requestsTable: string;
117
- private readonly exceptionsTable: string;
118
- private readonly logsTable: string;
119
-
120
- constructor(config: KyselyStorageConfig<DB>) {
121
- this.db = config.db;
122
- const prefix = config.tablePrefix ?? 'telescope';
123
- this.requestsTable = `${prefix}_requests`;
124
- this.exceptionsTable = `${prefix}_exceptions`;
125
- this.logsTable = `${prefix}_logs`;
126
- }
127
-
128
- // ============================================
129
- // Requests
130
- // ============================================
131
-
132
- async saveRequest(entry: RequestEntry): Promise<void> {
133
- const row = this.requestToRow(entry);
134
- await (this.db as any).insertInto(this.requestsTable).values(row).execute();
135
- }
136
-
137
- async saveRequests(entries: RequestEntry[]): Promise<void> {
138
- if (entries.length === 0) return;
139
-
140
- const rows = entries.map((e) => this.requestToRow(e));
141
- await (this.db as any)
142
- .insertInto(this.requestsTable)
143
- .values(rows)
144
- .execute();
145
- }
146
-
147
- async getRequests(options?: QueryOptions): Promise<RequestEntry[]> {
148
- let query = (this.db as any)
149
- .selectFrom(this.requestsTable)
150
- .selectAll()
151
- .orderBy('timestamp', 'desc');
152
-
153
- // Apply request-specific filters
154
- if (options?.method) {
155
- query = query.where('method', '=', options.method);
156
- }
157
-
158
- if (options?.status) {
159
- const statusFilter = options.status;
160
- if (statusFilter.endsWith('xx')) {
161
- // Handle status ranges like "2xx", "4xx", "5xx"
162
- const firstChar = statusFilter[0];
163
- if (firstChar) {
164
- const category = parseInt(firstChar, 10);
165
- const minStatus = category * 100;
166
- const maxStatus = minStatus + 99;
167
- query = query
168
- .where('status', '>=', minStatus)
169
- .where('status', '<=', maxStatus);
170
- }
171
- } else {
172
- // Handle exact status codes
173
- query = query.where('status', '=', parseInt(statusFilter, 10));
174
- }
175
- }
176
-
177
- query = this.applyQueryOptions(query, options);
178
-
179
- const rows = await query.execute();
180
- return rows.map((row: TelescopeRequestTable) => this.rowToRequest(row));
181
- }
182
-
183
- async getRequest(id: string): Promise<RequestEntry | null> {
184
- const row = await (this.db as any)
185
- .selectFrom(this.requestsTable)
186
- .selectAll()
187
- .where('id', '=', id)
188
- .executeTakeFirst();
189
-
190
- return row ? this.rowToRequest(row) : null;
191
- }
192
-
193
- // ============================================
194
- // Exceptions
195
- // ============================================
196
-
197
- async saveException(entry: ExceptionEntry): Promise<void> {
198
- const row = this.exceptionToRow(entry);
199
- await (this.db as any)
200
- .insertInto(this.exceptionsTable)
201
- .values(row)
202
- .execute();
203
- }
204
-
205
- async saveExceptions(entries: ExceptionEntry[]): Promise<void> {
206
- if (entries.length === 0) return;
207
-
208
- const rows = entries.map((e) => this.exceptionToRow(e));
209
- await (this.db as any)
210
- .insertInto(this.exceptionsTable)
211
- .values(rows)
212
- .execute();
213
- }
214
-
215
- async getExceptions(options?: QueryOptions): Promise<ExceptionEntry[]> {
216
- let query = (this.db as any)
217
- .selectFrom(this.exceptionsTable)
218
- .selectAll()
219
- .orderBy('timestamp', 'desc');
220
-
221
- query = this.applyQueryOptions(query, options);
222
-
223
- const rows = await query.execute();
224
- return rows.map((row: TelescopeExceptionTable) => this.rowToException(row));
225
- }
226
-
227
- async getException(id: string): Promise<ExceptionEntry | null> {
228
- const row = await (this.db as any)
229
- .selectFrom(this.exceptionsTable)
230
- .selectAll()
231
- .where('id', '=', id)
232
- .executeTakeFirst();
233
-
234
- return row ? this.rowToException(row) : null;
235
- }
236
-
237
- // ============================================
238
- // Logs
239
- // ============================================
240
-
241
- async saveLog(entry: LogEntry): Promise<void> {
242
- const row = this.logToRow(entry);
243
- await (this.db as any).insertInto(this.logsTable).values(row).execute();
244
- }
245
-
246
- async saveLogs(entries: LogEntry[]): Promise<void> {
247
- if (entries.length === 0) return;
248
-
249
- const rows = entries.map((e) => this.logToRow(e));
250
- await (this.db as any).insertInto(this.logsTable).values(rows).execute();
251
- }
252
-
253
- async getLogs(options?: QueryOptions): Promise<LogEntry[]> {
254
- let query = (this.db as any)
255
- .selectFrom(this.logsTable)
256
- .selectAll()
257
- .orderBy('timestamp', 'desc');
258
-
259
- // Apply log-specific filters
260
- if (options?.level) {
261
- query = query.where('level', '=', options.level);
262
- }
263
-
264
- query = this.applyQueryOptions(query, options);
265
-
266
- const rows = await query.execute();
267
- return rows.map((row: TelescopeLogTable) => this.rowToLog(row));
268
- }
269
-
270
- // ============================================
271
- // Cleanup
272
- // ============================================
273
-
274
- async prune(olderThan: Date): Promise<number> {
275
- const results = await Promise.all([
276
- (this.db as any)
277
- .deleteFrom(this.requestsTable)
278
- .where('timestamp', '<', olderThan)
279
- .executeTakeFirst(),
280
- (this.db as any)
281
- .deleteFrom(this.exceptionsTable)
282
- .where('timestamp', '<', olderThan)
283
- .executeTakeFirst(),
284
- (this.db as any)
285
- .deleteFrom(this.logsTable)
286
- .where('timestamp', '<', olderThan)
287
- .executeTakeFirst(),
288
- ]);
289
-
290
- return results.reduce(
291
- (sum, result) => sum + Number(result.numDeletedRows ?? 0),
292
- 0,
293
- );
294
- }
295
-
296
- // ============================================
297
- // Stats
298
- // ============================================
299
-
300
- async getStats(): Promise<TelescopeStats> {
301
- const [requestsResult, exceptionsResult, logsResult] = await Promise.all([
302
- (this.db as any)
303
- .selectFrom(this.requestsTable)
304
- .select((eb: any) => [
305
- eb.fn.count('id').as('count'),
306
- eb.fn.min('timestamp').as('oldest'),
307
- eb.fn.max('timestamp').as('newest'),
308
- ])
309
- .executeTakeFirst(),
310
- (this.db as any)
311
- .selectFrom(this.exceptionsTable)
312
- .select((eb: any) => [
313
- eb.fn.count('id').as('count'),
314
- eb.fn.min('timestamp').as('oldest'),
315
- eb.fn.max('timestamp').as('newest'),
316
- ])
317
- .executeTakeFirst(),
318
- (this.db as any)
319
- .selectFrom(this.logsTable)
320
- .select((eb: any) => [
321
- eb.fn.count('id').as('count'),
322
- eb.fn.min('timestamp').as('oldest'),
323
- eb.fn.max('timestamp').as('newest'),
324
- ])
325
- .executeTakeFirst(),
326
- ]);
327
-
328
- const allDates = [
329
- requestsResult?.oldest,
330
- requestsResult?.newest,
331
- exceptionsResult?.oldest,
332
- exceptionsResult?.newest,
333
- logsResult?.oldest,
334
- logsResult?.newest,
335
- ]
336
- .filter((d): d is Date => d != null)
337
- .sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
338
-
339
- const newestDate = allDates[allDates.length - 1];
340
- return {
341
- requests: Number(requestsResult?.count ?? 0),
342
- exceptions: Number(exceptionsResult?.count ?? 0),
343
- logs: Number(logsResult?.count ?? 0),
344
- oldestEntry: allDates[0] ? new Date(allDates[0]) : undefined,
345
- newestEntry: newestDate ? new Date(newestDate) : undefined,
346
- };
347
- }
348
-
349
- // ============================================
350
- // Private Helpers
351
- // ============================================
352
-
353
- private applyQueryOptions(query: any, options?: QueryOptions): any {
354
- if (!options) {
355
- return query.limit(50);
356
- }
357
-
358
- if (options.after) {
359
- query = query.where('timestamp', '>=', options.after);
360
- }
361
-
362
- if (options.before) {
363
- query = query.where('timestamp', '<=', options.before);
364
- }
365
-
366
- if (options.search) {
367
- // Search in relevant text fields - using ILIKE for case-insensitive
368
- // This is a simple implementation; for production you'd want full-text search
369
- query = query.where((eb: any) =>
370
- eb.or([
371
- eb('message', 'ilike', `%${options.search}%`),
372
- eb('path', 'ilike', `%${options.search}%`),
373
- eb('url', 'ilike', `%${options.search}%`),
374
- ]),
375
- );
376
- }
377
-
378
- // Tags filter would require array contains operation
379
- // which is database-specific (PostgreSQL: @>, etc.)
380
-
381
- const limit = options.limit ?? 50;
382
- const offset = options.offset ?? 0;
383
-
384
- return query.limit(limit).offset(offset);
385
- }
386
-
387
- private requestToRow(entry: RequestEntry): TelescopeRequestTable {
388
- return {
389
- id: entry.id,
390
- method: entry.method,
391
- path: entry.path,
392
- url: entry.url,
393
- headers: entry.headers,
394
- body: entry.body ?? null,
395
- query: entry.query ?? null,
396
- status: entry.status,
397
- response_headers: entry.responseHeaders,
398
- response_body: entry.responseBody ?? null,
399
- duration: entry.duration,
400
- timestamp: entry.timestamp,
401
- ip: entry.ip ?? null,
402
- user_id: entry.userId ?? null,
403
- tags: entry.tags ?? null,
404
- };
405
- }
406
-
407
- private rowToRequest(row: TelescopeRequestTable): RequestEntry {
408
- return {
409
- id: row.id,
410
- method: row.method,
411
- path: row.path,
412
- url: row.url,
413
- headers: this.parseJson(row.headers) as Record<string, string>,
414
- body: row.body ? this.parseJson(row.body) : undefined,
415
- query: row.query
416
- ? (this.parseJson(row.query) as Record<string, string>)
417
- : undefined,
418
- status: row.status,
419
- responseHeaders: this.parseJson(row.response_headers) as Record<
420
- string,
421
- string
422
- >,
423
- responseBody: row.response_body
424
- ? this.parseJson(row.response_body)
425
- : undefined,
426
- duration: row.duration,
427
- timestamp: new Date(row.timestamp),
428
- ip: row.ip ?? undefined,
429
- userId: row.user_id ?? undefined,
430
- tags: row.tags ? (this.parseJson(row.tags) as string[]) : undefined,
431
- };
432
- }
433
-
434
- private exceptionToRow(entry: ExceptionEntry): TelescopeExceptionTable {
435
- return {
436
- id: entry.id,
437
- name: entry.name,
438
- message: entry.message,
439
- stack: entry.stack,
440
- source: entry.source ?? null,
441
- request_id: entry.requestId ?? null,
442
- timestamp: entry.timestamp,
443
- handled: entry.handled,
444
- tags: entry.tags ?? null,
445
- };
446
- }
447
-
448
- private rowToException(row: TelescopeExceptionTable): ExceptionEntry {
449
- return {
450
- id: row.id,
451
- name: row.name,
452
- message: row.message,
453
- stack: this.parseJson(row.stack) as ExceptionEntry['stack'],
454
- source: row.source
455
- ? (this.parseJson(row.source) as ExceptionEntry['source'])
456
- : undefined,
457
- requestId: row.request_id ?? undefined,
458
- timestamp: new Date(row.timestamp),
459
- handled: row.handled,
460
- tags: row.tags ? (this.parseJson(row.tags) as string[]) : undefined,
461
- };
462
- }
463
-
464
- private logToRow(entry: LogEntry): TelescopeLogTable {
465
- return {
466
- id: entry.id,
467
- level: entry.level,
468
- message: entry.message,
469
- context: entry.context ?? null,
470
- request_id: entry.requestId ?? null,
471
- timestamp: entry.timestamp,
472
- };
473
- }
474
-
475
- private rowToLog(row: TelescopeLogTable): LogEntry {
476
- return {
477
- id: row.id,
478
- level: row.level as LogEntry['level'],
479
- message: row.message,
480
- context: row.context
481
- ? (this.parseJson(row.context) as Record<string, unknown>)
482
- : undefined,
483
- requestId: row.request_id ?? undefined,
484
- timestamp: new Date(row.timestamp),
485
- };
486
- }
487
-
488
- /**
489
- * Parse a JSON value that may already be parsed (e.g., from jsonb columns).
490
- */
491
- private parseJson(value: unknown): unknown {
492
- if (typeof value === 'object' && value !== null) {
493
- return value;
494
- }
495
- if (typeof value === 'string') {
496
- try {
497
- return JSON.parse(value);
498
- } catch {
499
- return value;
500
- }
501
- }
502
- return value;
503
- }
504
- }
505
-
506
- /**
507
- * SQL migration to create telescope tables.
508
- * Use this to set up the required tables in your database.
509
- *
510
- * @example
511
- * ```typescript
512
- * import { getTelescopeMigration } from '@geekmidas/telescope/storage/kysely';
513
- *
514
- * // In your migration file
515
- * export async function up(db: Kysely<any>): Promise<void> {
516
- * const migration = getTelescopeMigration();
517
- * await db.schema.executeRaw(migration.up).execute();
518
- * }
519
- *
520
- * export async function down(db: Kysely<any>): Promise<void> {
521
- * const migration = getTelescopeMigration();
522
- * await db.schema.executeRaw(migration.down).execute();
523
- * }
524
- * ```
525
- */
526
- export function getTelescopeMigration(tablePrefix = 'telescope'): {
527
- up: string;
528
- down: string;
529
- } {
530
- return {
531
- up: `
532
- -- Telescope requests table
533
- CREATE TABLE IF NOT EXISTS ${tablePrefix}_requests (
534
- id VARCHAR(21) PRIMARY KEY,
535
- method VARCHAR(10) NOT NULL,
536
- path TEXT NOT NULL,
537
- url TEXT NOT NULL,
538
- headers JSONB NOT NULL,
539
- body JSONB,
540
- query JSONB,
541
- status INTEGER NOT NULL,
542
- response_headers JSONB NOT NULL,
543
- response_body JSONB,
544
- duration DOUBLE PRECISION NOT NULL,
545
- timestamp TIMESTAMPTZ NOT NULL,
546
- ip VARCHAR(45),
547
- user_id VARCHAR(255),
548
- tags JSONB
549
- );
550
-
551
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_requests_timestamp
552
- ON ${tablePrefix}_requests (timestamp DESC);
553
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_requests_path
554
- ON ${tablePrefix}_requests (path);
555
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_requests_status
556
- ON ${tablePrefix}_requests (status);
557
-
558
- -- Telescope exceptions table
559
- CREATE TABLE IF NOT EXISTS ${tablePrefix}_exceptions (
560
- id VARCHAR(21) PRIMARY KEY,
561
- name VARCHAR(255) NOT NULL,
562
- message TEXT NOT NULL,
563
- stack JSONB NOT NULL,
564
- source JSONB,
565
- request_id VARCHAR(21),
566
- timestamp TIMESTAMPTZ NOT NULL,
567
- handled BOOLEAN NOT NULL DEFAULT FALSE,
568
- tags JSONB
569
- );
570
-
571
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_exceptions_timestamp
572
- ON ${tablePrefix}_exceptions (timestamp DESC);
573
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_exceptions_request_id
574
- ON ${tablePrefix}_exceptions (request_id);
575
-
576
- -- Telescope logs table
577
- CREATE TABLE IF NOT EXISTS ${tablePrefix}_logs (
578
- id VARCHAR(21) PRIMARY KEY,
579
- level VARCHAR(10) NOT NULL,
580
- message TEXT NOT NULL,
581
- context JSONB,
582
- request_id VARCHAR(21),
583
- timestamp TIMESTAMPTZ NOT NULL
584
- );
585
-
586
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_logs_timestamp
587
- ON ${tablePrefix}_logs (timestamp DESC);
588
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_logs_level
589
- ON ${tablePrefix}_logs (level);
590
- CREATE INDEX IF NOT EXISTS idx_${tablePrefix}_logs_request_id
591
- ON ${tablePrefix}_logs (request_id);
592
- `,
593
- down: `
594
- DROP TABLE IF EXISTS ${tablePrefix}_logs;
595
- DROP TABLE IF EXISTS ${tablePrefix}_exceptions;
596
- DROP TABLE IF EXISTS ${tablePrefix}_requests;
597
- `,
598
- };
599
- }