trickle-observe 0.2.95 → 0.2.96

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.
@@ -21,3 +21,13 @@ export declare function patchMysql2(mysqlModule: any, debug: boolean): void;
21
21
  * Patch better-sqlite3 to capture queries.
22
22
  */
23
23
  export declare function patchBetterSqlite3(dbConstructor: any, debug: boolean): void;
24
+ /**
25
+ * Patch ioredis to capture Redis commands.
26
+ * Called from observe-register when ioredis is required.
27
+ */
28
+ export declare function patchIoredis(ioredisModule: any, debug: boolean): void;
29
+ /**
30
+ * Patch mongoose to capture MongoDB operations.
31
+ * Called from observe-register when mongoose is required.
32
+ */
33
+ export declare function patchMongoose(mongooseModule: any, debug: boolean): void;
@@ -46,6 +46,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
46
46
  exports.patchPg = patchPg;
47
47
  exports.patchMysql2 = patchMysql2;
48
48
  exports.patchBetterSqlite3 = patchBetterSqlite3;
49
+ exports.patchIoredis = patchIoredis;
50
+ exports.patchMongoose = patchMongoose;
49
51
  const fs = __importStar(require("fs"));
50
52
  const path = __importStar(require("path"));
51
53
  let queriesFile = null;
@@ -290,3 +292,99 @@ function patchBetterSqlite3(dbConstructor, debug) {
290
292
  if (debug)
291
293
  console.log('[trickle/db] SQLite query tracing enabled');
292
294
  }
295
+ /**
296
+ * Patch ioredis to capture Redis commands.
297
+ * Called from observe-register when ioredis is required.
298
+ */
299
+ function patchIoredis(ioredisModule, debug) {
300
+ debugMode = debug;
301
+ const RedisClass = ioredisModule.default || ioredisModule;
302
+ const proto = RedisClass.prototype;
303
+ if (!proto || proto.sendCommand?.__trickle_patched)
304
+ return;
305
+ const origSendCommand = proto.sendCommand;
306
+ if (!origSendCommand)
307
+ return;
308
+ proto.sendCommand = function patchedSendCommand(command, ...rest) {
309
+ const cmdName = command?.name || 'UNKNOWN';
310
+ const cmdArgs = (command?.args || []).slice(0, 3).map((a) => typeof a === 'string' ? (a.length > 50 ? a.substring(0, 50) + '...' : a) : String(a).substring(0, 50));
311
+ const queryStr = `${cmdName.toUpperCase()} ${cmdArgs.join(' ')}`.trim();
312
+ const startTime = performance.now();
313
+ const result = origSendCommand.call(this, command, ...rest);
314
+ // ioredis returns a Promise
315
+ if (result && typeof result.then === 'function') {
316
+ result.then(() => {
317
+ writeQuery({
318
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
319
+ durationMs: Math.round((performance.now() - startTime) * 100) / 100,
320
+ rowCount: 1, timestamp: Date.now(),
321
+ });
322
+ }, (err) => {
323
+ writeQuery({
324
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
325
+ durationMs: Math.round((performance.now() - startTime) * 100) / 100,
326
+ rowCount: 0, error: err?.message?.substring(0, 200), timestamp: Date.now(),
327
+ });
328
+ });
329
+ }
330
+ return result;
331
+ };
332
+ proto.sendCommand.__trickle_patched = true;
333
+ if (debug)
334
+ console.log('[trickle/db] Redis (ioredis) query tracing enabled');
335
+ }
336
+ /**
337
+ * Patch mongoose to capture MongoDB operations.
338
+ * Called from observe-register when mongoose is required.
339
+ */
340
+ function patchMongoose(mongooseModule, debug) {
341
+ debugMode = debug;
342
+ const Model = mongooseModule.Model;
343
+ if (!Model || Model.__trickle_patched)
344
+ return;
345
+ const methodsToWrap = [
346
+ 'find', 'findOne', 'findById', 'findOneAndUpdate', 'findOneAndDelete',
347
+ 'create', 'insertMany', 'updateOne', 'updateMany',
348
+ 'deleteOne', 'deleteMany', 'countDocuments', 'aggregate',
349
+ ];
350
+ for (const method of methodsToWrap) {
351
+ const orig = Model[method];
352
+ if (!orig || orig.__trickle_patched)
353
+ continue;
354
+ Model[method] = function patchedMethod(...args) {
355
+ const collName = this.modelName || this.collection?.name || '?';
356
+ let filterStr = '';
357
+ if (args[0] && typeof args[0] === 'object') {
358
+ try {
359
+ filterStr = ' ' + JSON.stringify(args[0]).substring(0, 200);
360
+ }
361
+ catch { }
362
+ }
363
+ const queryStr = `db.${collName}.${method}(${filterStr.trim()})`;
364
+ const startTime = performance.now();
365
+ const result = orig.apply(this, args);
366
+ // Mongoose methods return Query objects (thenables) or Promises
367
+ if (result && typeof result.then === 'function') {
368
+ result.then((res) => {
369
+ const durationMs = Math.round((performance.now() - startTime) * 100) / 100;
370
+ const rowCount = Array.isArray(res) ? res.length : (res ? 1 : 0);
371
+ writeQuery({
372
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
373
+ durationMs, rowCount, timestamp: Date.now(),
374
+ });
375
+ }, (err) => {
376
+ writeQuery({
377
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
378
+ durationMs: Math.round((performance.now() - startTime) * 100) / 100,
379
+ rowCount: 0, error: err?.message?.substring(0, 200), timestamp: Date.now(),
380
+ });
381
+ });
382
+ }
383
+ return result;
384
+ };
385
+ Model[method].__trickle_patched = true;
386
+ }
387
+ Model.__trickle_patched = true;
388
+ if (debug)
389
+ console.log('[trickle/db] MongoDB (mongoose) query tracing enabled');
390
+ }
@@ -1148,6 +1148,24 @@ if (enabled) {
1148
1148
  }
1149
1149
  catch { /* not critical */ }
1150
1150
  }
1151
+ // Redis (ioredis)
1152
+ if (request === 'ioredis' && !expressPatched.has('ioredis')) {
1153
+ expressPatched.add('ioredis');
1154
+ try {
1155
+ const { patchIoredis } = require(path_1.default.join(__dirname, 'db-observer.js'));
1156
+ patchIoredis(exports, debug);
1157
+ }
1158
+ catch { /* not critical */ }
1159
+ }
1160
+ // MongoDB (mongoose)
1161
+ if (request === 'mongoose' && !expressPatched.has('mongoose')) {
1162
+ expressPatched.add('mongoose');
1163
+ try {
1164
+ const { patchMongoose } = require(path_1.default.join(__dirname, 'db-observer.js'));
1165
+ patchMongoose(exports, debug);
1166
+ }
1167
+ catch { /* not critical */ }
1168
+ }
1151
1169
  // Resolve to absolute path for dedup — do this FIRST since bundlers like
1152
1170
  // tsx/esbuild may use path aliases (e.g., @config/env) that don't start
1153
1171
  // with './' or '/'. We need the resolved path to decide if it's user code.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trickle-observe",
3
- "version": "0.2.95",
3
+ "version": "0.2.96",
4
4
  "description": "Runtime type observability for JavaScript applications",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -281,3 +281,113 @@ export function patchBetterSqlite3(dbConstructor: any, debug: boolean): void {
281
281
 
282
282
  if (debug) console.log('[trickle/db] SQLite query tracing enabled');
283
283
  }
284
+
285
+ /**
286
+ * Patch ioredis to capture Redis commands.
287
+ * Called from observe-register when ioredis is required.
288
+ */
289
+ export function patchIoredis(ioredisModule: any, debug: boolean): void {
290
+ debugMode = debug;
291
+
292
+ const RedisClass = ioredisModule.default || ioredisModule;
293
+ const proto = RedisClass.prototype;
294
+ if (!proto || (proto.sendCommand as any)?.__trickle_patched) return;
295
+
296
+ const origSendCommand = proto.sendCommand;
297
+ if (!origSendCommand) return;
298
+
299
+ proto.sendCommand = function patchedSendCommand(command: any, ...rest: any[]): any {
300
+ const cmdName = command?.name || 'UNKNOWN';
301
+ const cmdArgs = (command?.args || []).slice(0, 3).map((a: any) =>
302
+ typeof a === 'string' ? (a.length > 50 ? a.substring(0, 50) + '...' : a) : String(a).substring(0, 50)
303
+ );
304
+ const queryStr = `${cmdName.toUpperCase()} ${cmdArgs.join(' ')}`.trim();
305
+
306
+ const startTime = performance.now();
307
+ const result = origSendCommand.call(this, command, ...rest);
308
+
309
+ // ioredis returns a Promise
310
+ if (result && typeof result.then === 'function') {
311
+ result.then(
312
+ () => {
313
+ writeQuery({
314
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
315
+ durationMs: Math.round((performance.now() - startTime) * 100) / 100,
316
+ rowCount: 1, timestamp: Date.now(),
317
+ });
318
+ },
319
+ (err: any) => {
320
+ writeQuery({
321
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
322
+ durationMs: Math.round((performance.now() - startTime) * 100) / 100,
323
+ rowCount: 0, error: err?.message?.substring(0, 200), timestamp: Date.now(),
324
+ });
325
+ }
326
+ );
327
+ }
328
+ return result;
329
+ };
330
+ (proto.sendCommand as any).__trickle_patched = true;
331
+
332
+ if (debug) console.log('[trickle/db] Redis (ioredis) query tracing enabled');
333
+ }
334
+
335
+ /**
336
+ * Patch mongoose to capture MongoDB operations.
337
+ * Called from observe-register when mongoose is required.
338
+ */
339
+ export function patchMongoose(mongooseModule: any, debug: boolean): void {
340
+ debugMode = debug;
341
+
342
+ const Model = mongooseModule.Model;
343
+ if (!Model || (Model as any).__trickle_patched) return;
344
+
345
+ const methodsToWrap = [
346
+ 'find', 'findOne', 'findById', 'findOneAndUpdate', 'findOneAndDelete',
347
+ 'create', 'insertMany', 'updateOne', 'updateMany',
348
+ 'deleteOne', 'deleteMany', 'countDocuments', 'aggregate',
349
+ ];
350
+
351
+ for (const method of methodsToWrap) {
352
+ const orig = Model[method];
353
+ if (!orig || (orig as any).__trickle_patched) continue;
354
+
355
+ Model[method] = function patchedMethod(this: any, ...args: any[]): any {
356
+ const collName = this.modelName || this.collection?.name || '?';
357
+ let filterStr = '';
358
+ if (args[0] && typeof args[0] === 'object') {
359
+ try { filterStr = ' ' + JSON.stringify(args[0]).substring(0, 200); } catch {}
360
+ }
361
+ const queryStr = `db.${collName}.${method}(${filterStr.trim()})`;
362
+
363
+ const startTime = performance.now();
364
+ const result = orig.apply(this, args);
365
+
366
+ // Mongoose methods return Query objects (thenables) or Promises
367
+ if (result && typeof result.then === 'function') {
368
+ result.then(
369
+ (res: any) => {
370
+ const durationMs = Math.round((performance.now() - startTime) * 100) / 100;
371
+ const rowCount = Array.isArray(res) ? res.length : (res ? 1 : 0);
372
+ writeQuery({
373
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
374
+ durationMs, rowCount, timestamp: Date.now(),
375
+ });
376
+ },
377
+ (err: any) => {
378
+ writeQuery({
379
+ kind: 'query', query: queryStr.substring(0, MAX_QUERY_LENGTH),
380
+ durationMs: Math.round((performance.now() - startTime) * 100) / 100,
381
+ rowCount: 0, error: err?.message?.substring(0, 200), timestamp: Date.now(),
382
+ });
383
+ }
384
+ );
385
+ }
386
+ return result;
387
+ };
388
+ (Model[method] as any).__trickle_patched = true;
389
+ }
390
+ (Model as any).__trickle_patched = true;
391
+
392
+ if (debug) console.log('[trickle/db] MongoDB (mongoose) query tracing enabled');
393
+ }
@@ -1136,6 +1136,24 @@ if (enabled) {
1136
1136
  } catch { /* not critical */ }
1137
1137
  }
1138
1138
 
1139
+ // Redis (ioredis)
1140
+ if (request === 'ioredis' && !expressPatched.has('ioredis')) {
1141
+ expressPatched.add('ioredis');
1142
+ try {
1143
+ const { patchIoredis } = require(path.join(__dirname, 'db-observer.js'));
1144
+ patchIoredis(exports, debug);
1145
+ } catch { /* not critical */ }
1146
+ }
1147
+
1148
+ // MongoDB (mongoose)
1149
+ if (request === 'mongoose' && !expressPatched.has('mongoose')) {
1150
+ expressPatched.add('mongoose');
1151
+ try {
1152
+ const { patchMongoose } = require(path.join(__dirname, 'db-observer.js'));
1153
+ patchMongoose(exports, debug);
1154
+ } catch { /* not critical */ }
1155
+ }
1156
+
1139
1157
  // Resolve to absolute path for dedup — do this FIRST since bundlers like
1140
1158
  // tsx/esbuild may use path aliases (e.g., @config/env) that don't start
1141
1159
  // with './' or '/'. We need the resolved path to decide if it's user code.