trickle-observe 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auto-codegen.d.ts +1 -1
- package/dist/auto-codegen.js +234 -17
- package/dist/auto-register.js +1 -1
- package/dist/express.js +13 -0
- package/dist/observe-register.js +450 -41
- package/dist/trace-var.d.ts +44 -0
- package/dist/trace-var.js +219 -0
- package/dist/type-inference.js +9 -1
- package/dist/vite-plugin.d.ts +5 -2
- package/dist/vite-plugin.js +385 -25
- package/dist/wrap.js +4 -12
- package/package.json +10 -3
- package/src/auto-codegen.ts +226 -18
- package/src/auto-register.ts +1 -1
- package/src/express.d.ts +387 -0
- package/src/express.ts +14 -0
- package/src/observe-register.ts +420 -41
- package/src/trace-var.ts +202 -0
- package/src/type-inference.ts +11 -1
- package/src/vite-plugin.ts +444 -24
- package/src/wrap.ts +4 -12
package/dist/vite-plugin.js
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
* Vite plugin for trickle observation.
|
|
4
4
|
*
|
|
5
5
|
* Integrates into Vite's (and Vitest's) transform pipeline to wrap
|
|
6
|
-
* user functions with trickle observation
|
|
7
|
-
* does for Node's Module._compile,
|
|
6
|
+
* user functions with trickle observation AND trace variable assignments —
|
|
7
|
+
* the same thing observe-register.ts does for Node's Module._compile,
|
|
8
|
+
* but for Vite/Vitest.
|
|
8
9
|
*
|
|
9
10
|
* Usage in vitest.config.ts:
|
|
10
11
|
*
|
|
@@ -23,6 +24,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
23
24
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
25
|
exports.tricklePlugin = tricklePlugin;
|
|
25
26
|
const path_1 = __importDefault(require("path"));
|
|
27
|
+
const fs_1 = __importDefault(require("fs"));
|
|
26
28
|
function tricklePlugin(options = {}) {
|
|
27
29
|
const include = options.include
|
|
28
30
|
?? (process.env.TRICKLE_OBSERVE_INCLUDE
|
|
@@ -37,6 +39,7 @@ function tricklePlugin(options = {}) {
|
|
|
37
39
|
?? 'http://localhost:4888';
|
|
38
40
|
const debug = options.debug
|
|
39
41
|
?? (process.env.TRICKLE_DEBUG === '1' || process.env.TRICKLE_DEBUG === 'true');
|
|
42
|
+
const traceVars = options.traceVars ?? (process.env.TRICKLE_TRACE_VARS !== '0');
|
|
40
43
|
function shouldTransform(id) {
|
|
41
44
|
// Only JS/TS files
|
|
42
45
|
const ext = path_1.default.extname(id).toLowerCase();
|
|
@@ -66,8 +69,18 @@ function tricklePlugin(options = {}) {
|
|
|
66
69
|
transform(code, id) {
|
|
67
70
|
if (!shouldTransform(id))
|
|
68
71
|
return null;
|
|
72
|
+
// Read the original source file to get accurate line numbers.
|
|
73
|
+
// Vite transforms the code before our plugin (enforce: 'post'),
|
|
74
|
+
// so line numbers from `code` don't match the original .ts file.
|
|
75
|
+
let originalSource = null;
|
|
76
|
+
try {
|
|
77
|
+
originalSource = fs_1.default.readFileSync(id, 'utf-8');
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
// If we can't read the original, we'll use transformed line numbers
|
|
81
|
+
}
|
|
69
82
|
const moduleName = path_1.default.basename(id).replace(/\.[jt]sx?$/, '');
|
|
70
|
-
const transformed = transformEsmSource(code, id, moduleName, backendUrl, debug);
|
|
83
|
+
const transformed = transformEsmSource(code, id, moduleName, backendUrl, debug, traceVars, originalSource);
|
|
71
84
|
if (transformed === code)
|
|
72
85
|
return null;
|
|
73
86
|
if (debug) {
|
|
@@ -132,16 +145,310 @@ function findClosingBrace(source, openBrace) {
|
|
|
132
145
|
return -1;
|
|
133
146
|
}
|
|
134
147
|
/**
|
|
135
|
-
*
|
|
148
|
+
* Find variable declarations in source and return insertions for tracing.
|
|
149
|
+
* Handles: const x = ...; let x = ...; var x = ...;
|
|
150
|
+
* Skips: destructuring, for-loop vars, require() calls, imports, type annotations.
|
|
151
|
+
*/
|
|
152
|
+
function findVarDeclarations(source) {
|
|
153
|
+
const varInsertions = [];
|
|
154
|
+
// Match: const/let/var <identifier> = <something>
|
|
155
|
+
const varRegex = /^([ \t]*)(export\s+)?(const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?::\s*[^=]+?)?\s*=[^=]/gm;
|
|
156
|
+
let vmatch;
|
|
157
|
+
while ((vmatch = varRegex.exec(source)) !== null) {
|
|
158
|
+
const varName = vmatch[4];
|
|
159
|
+
// Skip trickle internals
|
|
160
|
+
if (varName.startsWith('__trickle'))
|
|
161
|
+
continue;
|
|
162
|
+
// Skip TS compiled vars
|
|
163
|
+
if (varName === '_a' || varName === '_b' || varName === '_c')
|
|
164
|
+
continue;
|
|
165
|
+
// Check if this is a require() call or import — skip those
|
|
166
|
+
const restOfLine = source.slice(vmatch.index + vmatch[0].length - 1, vmatch.index + vmatch[0].length + 200);
|
|
167
|
+
if (/^\s*require\s*\(/.test(restOfLine))
|
|
168
|
+
continue;
|
|
169
|
+
// Skip function/class assignments (those are handled by function wrapping)
|
|
170
|
+
if (/^\s*(?:async\s+)?(?:function\s|\([^)]*\)\s*(?::\s*[^=]+?)?\s*=>|\w+\s*=>)/.test(restOfLine))
|
|
171
|
+
continue;
|
|
172
|
+
// Calculate line number
|
|
173
|
+
let lineNo = 1;
|
|
174
|
+
for (let i = 0; i < vmatch.index; i++) {
|
|
175
|
+
if (source[i] === '\n')
|
|
176
|
+
lineNo++;
|
|
177
|
+
}
|
|
178
|
+
// Find the end of this statement
|
|
179
|
+
const startPos = vmatch.index + vmatch[0].length - 1;
|
|
180
|
+
let pos = startPos;
|
|
181
|
+
let depth = 0;
|
|
182
|
+
let foundEnd = -1;
|
|
183
|
+
while (pos < source.length) {
|
|
184
|
+
const ch = source[pos];
|
|
185
|
+
if (ch === '(' || ch === '[' || ch === '{') {
|
|
186
|
+
depth++;
|
|
187
|
+
}
|
|
188
|
+
else if (ch === ')' || ch === ']' || ch === '}') {
|
|
189
|
+
depth--;
|
|
190
|
+
if (depth < 0)
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
else if (ch === ';' && depth === 0) {
|
|
194
|
+
foundEnd = pos;
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
else if (ch === '\n' && depth === 0) {
|
|
198
|
+
const nextNonWs = source.slice(pos + 1).match(/^\s*(\S)/);
|
|
199
|
+
if (nextNonWs && !'.+=-|&?:,'.includes(nextNonWs[1])) {
|
|
200
|
+
foundEnd = pos;
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
else if (ch === '"' || ch === "'" || ch === '`') {
|
|
205
|
+
const quote = ch;
|
|
206
|
+
pos++;
|
|
207
|
+
while (pos < source.length) {
|
|
208
|
+
if (source[pos] === '\\') {
|
|
209
|
+
pos++;
|
|
210
|
+
}
|
|
211
|
+
else if (source[pos] === quote)
|
|
212
|
+
break;
|
|
213
|
+
pos++;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
else if (ch === '/' && pos + 1 < source.length && source[pos + 1] === '/') {
|
|
217
|
+
while (pos < source.length && source[pos] !== '\n')
|
|
218
|
+
pos++;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
else if (ch === '/' && pos + 1 < source.length && source[pos + 1] === '*') {
|
|
222
|
+
pos += 2;
|
|
223
|
+
while (pos < source.length - 1 && !(source[pos] === '*' && source[pos + 1] === '/'))
|
|
224
|
+
pos++;
|
|
225
|
+
pos++;
|
|
226
|
+
}
|
|
227
|
+
pos++;
|
|
228
|
+
}
|
|
229
|
+
if (foundEnd === -1)
|
|
230
|
+
continue;
|
|
231
|
+
varInsertions.push({ lineEnd: foundEnd + 1, varName, lineNo });
|
|
232
|
+
}
|
|
233
|
+
return varInsertions;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Find destructured variable declarations: const { a, b } = ... and const [a, b] = ...
|
|
237
|
+
* Extracts the individual variable names from the destructuring pattern.
|
|
238
|
+
*/
|
|
239
|
+
function findDestructuredDeclarations(source) {
|
|
240
|
+
const results = [];
|
|
241
|
+
// Match: const/let/var { ... } = ... or const/let/var [ ... ] = ...
|
|
242
|
+
const destructRegex = /^[ \t]*(?:export\s+)?(?:const|let|var)\s+(\{[^}]*\}|\[[^\]]*\])\s*(?::\s*[^=]+?)?\s*=[^=]/gm;
|
|
243
|
+
let match;
|
|
244
|
+
while ((match = destructRegex.exec(source)) !== null) {
|
|
245
|
+
const pattern = match[1];
|
|
246
|
+
// Extract variable names from the destructuring pattern
|
|
247
|
+
const varNames = extractDestructuredNames(pattern);
|
|
248
|
+
if (varNames.length === 0)
|
|
249
|
+
continue;
|
|
250
|
+
// Skip if it's a require() call
|
|
251
|
+
const restOfLine = source.slice(match.index + match[0].length - 1, match.index + match[0].length + 200);
|
|
252
|
+
if (/^\s*require\s*\(/.test(restOfLine))
|
|
253
|
+
continue;
|
|
254
|
+
// Calculate line number
|
|
255
|
+
let lineNo = 1;
|
|
256
|
+
for (let i = 0; i < match.index; i++) {
|
|
257
|
+
if (source[i] === '\n')
|
|
258
|
+
lineNo++;
|
|
259
|
+
}
|
|
260
|
+
// Find the end of this statement (same logic as findVarDeclarations)
|
|
261
|
+
const startPos = match.index + match[0].length - 1;
|
|
262
|
+
let pos = startPos;
|
|
263
|
+
let depth = 0;
|
|
264
|
+
let foundEnd = -1;
|
|
265
|
+
while (pos < source.length) {
|
|
266
|
+
const ch = source[pos];
|
|
267
|
+
if (ch === '(' || ch === '[' || ch === '{') {
|
|
268
|
+
depth++;
|
|
269
|
+
}
|
|
270
|
+
else if (ch === ')' || ch === ']' || ch === '}') {
|
|
271
|
+
depth--;
|
|
272
|
+
if (depth < 0)
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
275
|
+
else if (ch === ';' && depth === 0) {
|
|
276
|
+
foundEnd = pos;
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
else if (ch === '\n' && depth === 0) {
|
|
280
|
+
const nextNonWs = source.slice(pos + 1).match(/^\s*(\S)/);
|
|
281
|
+
if (nextNonWs && !'.+=-|&?:,'.includes(nextNonWs[1])) {
|
|
282
|
+
foundEnd = pos;
|
|
283
|
+
break;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
else if (ch === '"' || ch === "'" || ch === '`') {
|
|
287
|
+
const quote = ch;
|
|
288
|
+
pos++;
|
|
289
|
+
while (pos < source.length) {
|
|
290
|
+
if (source[pos] === '\\') {
|
|
291
|
+
pos++;
|
|
292
|
+
}
|
|
293
|
+
else if (source[pos] === quote)
|
|
294
|
+
break;
|
|
295
|
+
pos++;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
else if (ch === '/' && pos + 1 < source.length && source[pos + 1] === '/') {
|
|
299
|
+
while (pos < source.length && source[pos] !== '\n')
|
|
300
|
+
pos++;
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
else if (ch === '/' && pos + 1 < source.length && source[pos + 1] === '*') {
|
|
304
|
+
pos += 2;
|
|
305
|
+
while (pos < source.length - 1 && !(source[pos] === '*' && source[pos + 1] === '/'))
|
|
306
|
+
pos++;
|
|
307
|
+
pos++;
|
|
308
|
+
}
|
|
309
|
+
pos++;
|
|
310
|
+
}
|
|
311
|
+
if (foundEnd === -1)
|
|
312
|
+
continue;
|
|
313
|
+
results.push({ lineEnd: foundEnd + 1, varNames, lineNo });
|
|
314
|
+
}
|
|
315
|
+
return results;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Extract variable names from a destructuring pattern.
|
|
319
|
+
* Handles: { a, b, c: d } → ['a', 'b', 'd'] (renamed vars use the local name)
|
|
320
|
+
* Handles: [a, b, ...rest] → ['a', 'b', 'rest']
|
|
321
|
+
* Handles: { a: { b, c } } → ['b', 'c'] (nested destructuring)
|
|
322
|
+
*/
|
|
323
|
+
function extractDestructuredNames(pattern) {
|
|
324
|
+
const names = [];
|
|
325
|
+
// Remove outer braces/brackets
|
|
326
|
+
const inner = pattern.slice(1, -1).trim();
|
|
327
|
+
if (!inner)
|
|
328
|
+
return names;
|
|
329
|
+
// Split by commas at depth 0
|
|
330
|
+
const parts = [];
|
|
331
|
+
let depth = 0;
|
|
332
|
+
let current = '';
|
|
333
|
+
for (const ch of inner) {
|
|
334
|
+
if (ch === '{' || ch === '[')
|
|
335
|
+
depth++;
|
|
336
|
+
else if (ch === '}' || ch === ']')
|
|
337
|
+
depth--;
|
|
338
|
+
else if (ch === ',' && depth === 0) {
|
|
339
|
+
parts.push(current.trim());
|
|
340
|
+
current = '';
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
current += ch;
|
|
344
|
+
}
|
|
345
|
+
if (current.trim())
|
|
346
|
+
parts.push(current.trim());
|
|
347
|
+
for (let part of parts) {
|
|
348
|
+
// Remove type annotations: `a: Type` vs `a: b` (rename)
|
|
349
|
+
// Skip rest elements for now: ...rest → rest
|
|
350
|
+
if (part.startsWith('...')) {
|
|
351
|
+
const restName = part.slice(3).trim().split(/[\s:]/)[0];
|
|
352
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(restName)) {
|
|
353
|
+
names.push(restName);
|
|
354
|
+
}
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
// Check for rename pattern: key: localName or key: { nested }
|
|
358
|
+
const colonIdx = part.indexOf(':');
|
|
359
|
+
if (colonIdx !== -1) {
|
|
360
|
+
const afterColon = part.slice(colonIdx + 1).trim();
|
|
361
|
+
// Nested destructuring: key: { a, b } or key: [a, b]
|
|
362
|
+
if (afterColon.startsWith('{') || afterColon.startsWith('[')) {
|
|
363
|
+
const nestedNames = extractDestructuredNames(afterColon);
|
|
364
|
+
names.push(...nestedNames);
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
// Rename: key: localName — extract localName (skip if it has another colon for type annotation)
|
|
368
|
+
const localName = afterColon.split(/[\s=]/)[0].trim();
|
|
369
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(localName)) {
|
|
370
|
+
names.push(localName);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
else {
|
|
375
|
+
// Simple: just the identifier (possibly with default: `a = defaultVal`)
|
|
376
|
+
const name = part.split(/[\s=]/)[0].trim();
|
|
377
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {
|
|
378
|
+
names.push(name);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return names;
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Transform ESM source code to wrap function declarations and trace variables.
|
|
136
386
|
*
|
|
137
|
-
* Prepends
|
|
138
|
-
* each function declaration body
|
|
139
|
-
* transformCjsSource but using ESM imports.
|
|
387
|
+
* Prepends imports of the wrap/trace helpers, then inserts wrapper calls after
|
|
388
|
+
* each function declaration body and trace calls after variable declarations.
|
|
140
389
|
*/
|
|
141
|
-
|
|
390
|
+
/**
|
|
391
|
+
* Find the original line number for a simple variable declaration.
|
|
392
|
+
* Searches the original source lines for `const/let/var <varName>` near the expected position.
|
|
393
|
+
* Vite transforms typically remove lines (types, imports), so the original line is usually
|
|
394
|
+
* >= the transformed line. We search forward-biased (up to +80) but also a bit backward (-10).
|
|
395
|
+
*/
|
|
396
|
+
function findOriginalLine(origLines, varName, transformedLine) {
|
|
397
|
+
const pattern = new RegExp(`\\b(const|let|var)\\s+${escapeRegexStr(varName)}\\b`);
|
|
398
|
+
// Search: first try exact, then expand forward (more likely) and a bit backward
|
|
399
|
+
for (let delta = 0; delta <= 80; delta++) {
|
|
400
|
+
// Forward first (original line is usually after transformed line due to removed TS types)
|
|
401
|
+
const fwd = transformedLine - 1 + delta;
|
|
402
|
+
if (fwd >= 0 && fwd < origLines.length && pattern.test(origLines[fwd])) {
|
|
403
|
+
return fwd + 1;
|
|
404
|
+
}
|
|
405
|
+
// Also check backward (small range)
|
|
406
|
+
if (delta > 0 && delta <= 10) {
|
|
407
|
+
const bwd = transformedLine - 1 - delta;
|
|
408
|
+
if (bwd >= 0 && bwd < origLines.length && pattern.test(origLines[bwd])) {
|
|
409
|
+
return bwd + 1;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return -1;
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* Find the original line number for a destructured declaration.
|
|
417
|
+
* Searches for const/let/var { or [ patterns containing at least one of the variable names.
|
|
418
|
+
*/
|
|
419
|
+
function findOriginalLineDestructured(origLines, varNames, transformedLine) {
|
|
420
|
+
// Match names as actual bindings (not renamed property keys).
|
|
421
|
+
// In `{ data: customer }`, 'data' is a key (followed by ':'), 'customer' is the binding.
|
|
422
|
+
// In `{ data, error }`, 'data' is a binding (followed by ',' or '}').
|
|
423
|
+
// We check: name followed by comma, }, ], =, whitespace, or end — NOT followed by ':' (rename).
|
|
424
|
+
const namePatterns = varNames.map(n => new RegExp(`\\b${escapeRegexStr(n)}\\b(?!\\s*:)`));
|
|
425
|
+
for (let delta = 0; delta <= 80; delta++) {
|
|
426
|
+
const fwd = transformedLine - 1 + delta;
|
|
427
|
+
if (fwd >= 0 && fwd < origLines.length) {
|
|
428
|
+
const line = origLines[fwd];
|
|
429
|
+
if (/\b(const|let|var)\s+[\[{]/.test(line) && namePatterns.some(p => p.test(line))) {
|
|
430
|
+
return fwd + 1;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (delta > 0 && delta <= 10) {
|
|
434
|
+
const bwd = transformedLine - 1 - delta;
|
|
435
|
+
if (bwd >= 0 && bwd < origLines.length) {
|
|
436
|
+
const line = origLines[bwd];
|
|
437
|
+
if (/\b(const|let|var)\s+[\[{]/.test(line) && namePatterns.some(p => p.test(line))) {
|
|
438
|
+
return bwd + 1;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return -1;
|
|
444
|
+
}
|
|
445
|
+
function escapeRegexStr(str) {
|
|
446
|
+
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
447
|
+
}
|
|
448
|
+
function transformEsmSource(source, filename, moduleName, backendUrl, debug, traceVars, originalSource) {
|
|
142
449
|
// Match top-level and nested function declarations (including async, export)
|
|
143
450
|
const funcRegex = /^[ \t]*(?:export\s+)?(?:async\s+)?function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/gm;
|
|
144
|
-
const
|
|
451
|
+
const funcInsertions = [];
|
|
145
452
|
let match;
|
|
146
453
|
while ((match = funcRegex.exec(source)) !== null) {
|
|
147
454
|
const name = match[1];
|
|
@@ -164,7 +471,7 @@ function transformEsmSource(source, filename, moduleName, backendUrl, debug) {
|
|
|
164
471
|
const closeBrace = findClosingBrace(source, openBrace);
|
|
165
472
|
if (closeBrace === -1)
|
|
166
473
|
continue;
|
|
167
|
-
|
|
474
|
+
funcInsertions.push({ position: closeBrace + 1, name, paramNames });
|
|
168
475
|
}
|
|
169
476
|
// Also match arrow functions assigned to const/let/var
|
|
170
477
|
const arrowRegex = /^[ \t]*(?:export\s+)?(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[a-zA-Z_$][a-zA-Z0-9_$]*)\s*(?::\s*[^=]+?)?\s*=>\s*\{/gm;
|
|
@@ -173,7 +480,6 @@ function transformEsmSource(source, filename, moduleName, backendUrl, debug) {
|
|
|
173
480
|
const openBrace = source.indexOf('{', match.index + match[0].length - 1);
|
|
174
481
|
if (openBrace === -1)
|
|
175
482
|
continue;
|
|
176
|
-
// Extract param names from the arrow function
|
|
177
483
|
const arrowStr = match[0];
|
|
178
484
|
const arrowParamMatch = arrowStr.match(/=\s*(?:async\s+)?(?:\(([^)]*)\)|([a-zA-Z_$][a-zA-Z0-9_$]*))\s*(?::\s*[^=]+?)?\s*=>/);
|
|
179
485
|
let paramNames = [];
|
|
@@ -191,14 +497,42 @@ function transformEsmSource(source, filename, moduleName, backendUrl, debug) {
|
|
|
191
497
|
const closeBrace = findClosingBrace(source, openBrace);
|
|
192
498
|
if (closeBrace === -1)
|
|
193
499
|
continue;
|
|
194
|
-
|
|
500
|
+
funcInsertions.push({ position: closeBrace + 1, name, paramNames });
|
|
195
501
|
}
|
|
196
|
-
|
|
502
|
+
// Find variable declarations for tracing
|
|
503
|
+
const varInsertions = traceVars ? findVarDeclarations(source) : [];
|
|
504
|
+
// Find destructured variable declarations for tracing
|
|
505
|
+
const destructInsertions = traceVars ? findDestructuredDeclarations(source) : [];
|
|
506
|
+
if (funcInsertions.length === 0 && varInsertions.length === 0 && destructInsertions.length === 0)
|
|
197
507
|
return source;
|
|
198
|
-
//
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
508
|
+
// Fix line numbers: Vite transforms (TypeScript stripping) may change line numbers.
|
|
509
|
+
// Map transformed line numbers to original source line numbers.
|
|
510
|
+
if (originalSource && originalSource !== source) {
|
|
511
|
+
const origLines = originalSource.split('\n');
|
|
512
|
+
// For each variable insertion, find the declaration in the original source
|
|
513
|
+
for (const vi of varInsertions) {
|
|
514
|
+
const origLine = findOriginalLine(origLines, vi.varName, vi.lineNo);
|
|
515
|
+
if (origLine !== -1)
|
|
516
|
+
vi.lineNo = origLine;
|
|
517
|
+
}
|
|
518
|
+
for (const di of destructInsertions) {
|
|
519
|
+
// Use the first variable name to locate the line
|
|
520
|
+
if (di.varNames.length > 0) {
|
|
521
|
+
const origLine = findOriginalLineDestructured(origLines, di.varNames, di.lineNo);
|
|
522
|
+
if (origLine !== -1)
|
|
523
|
+
di.lineNo = origLine;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
// Build prefix — ALL imports first (ESM requires imports before any statements)
|
|
528
|
+
const importLines = [
|
|
529
|
+
`import { wrapFunction as __trickle_wrapFn, configure as __trickle_configure } from 'trickle-observe';`,
|
|
530
|
+
];
|
|
531
|
+
if (varInsertions.length > 0 || destructInsertions.length > 0) {
|
|
532
|
+
importLines.push(`import { mkdirSync as __trickle_mkdirSync, appendFileSync as __trickle_appendFileSync } from 'node:fs';`, `import { join as __trickle_join } from 'node:path';`);
|
|
533
|
+
}
|
|
534
|
+
const prefixLines = [
|
|
535
|
+
...importLines,
|
|
202
536
|
`__trickle_configure({ backendUrl: ${JSON.stringify(backendUrl)}, batchIntervalMs: 2000, debug: ${debug}, enabled: true, environment: 'node' });`,
|
|
203
537
|
`function __trickle_wrap(fn, name, paramNames) {`,
|
|
204
538
|
` const opts = {`,
|
|
@@ -214,15 +548,41 @@ function transformEsmSource(source, filename, moduleName, backendUrl, debug) {
|
|
|
214
548
|
` if (paramNames && paramNames.length) opts.paramNames = paramNames;`,
|
|
215
549
|
` return __trickle_wrapFn(fn, opts);`,
|
|
216
550
|
`}`,
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
//
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
const {
|
|
551
|
+
];
|
|
552
|
+
// Add variable tracing if needed — inlined to avoid import resolution issues in Vite SSR.
|
|
553
|
+
// Uses synchronous writes (appendFileSync) to guarantee data persists even if Vitest
|
|
554
|
+
// kills the worker abruptly without firing exit events.
|
|
555
|
+
if (varInsertions.length > 0 || destructInsertions.length > 0) {
|
|
556
|
+
prefixLines.push(`if (!globalThis.__trickle_var_tracer) {`, ` const _cache = new Set();`, ` let _varsFile = null;`, ` function _inferType(v, d) {`, ` if (d <= 0) return { kind: 'primitive', name: 'unknown' };`, ` if (v === null) return { kind: 'primitive', name: 'null' };`, ` if (v === undefined) return { kind: 'primitive', name: 'undefined' };`, ` const t = typeof v;`, ` if (t === 'string' || t === 'number' || t === 'boolean' || t === 'bigint' || t === 'symbol') return { kind: 'primitive', name: t };`, ` if (t === 'function') return { kind: 'function' };`, ` if (Array.isArray(v)) { return v.length === 0 ? { kind: 'array', element: { kind: 'primitive', name: 'unknown' } } : { kind: 'array', element: _inferType(v[0], d-1) }; }`, ` if (t === 'object') {`, ` if (v instanceof Date) return { kind: 'object', properties: { __date: { kind: 'primitive', name: 'string' } } };`, ` if (v instanceof RegExp) return { kind: 'object', properties: { __regexp: { kind: 'primitive', name: 'string' } } };`, ` if (v instanceof Error) return { kind: 'object', properties: { __error: { kind: 'primitive', name: 'string' } } };`, ` if (v instanceof Promise) return { kind: 'promise', resolved: { kind: 'primitive', name: 'unknown' } };`, ` const props = {}; const keys = Object.keys(v).slice(0, 20);`, ` for (const k of keys) { try { props[k] = _inferType(v[k], d-1); } catch(e) { props[k] = { kind: 'primitive', name: 'unknown' }; } }`, ` return { kind: 'object', properties: props };`, ` }`, ` return { kind: 'primitive', name: 'unknown' };`, ` }`, ` function _sanitize(v, d) {`, ` if (d <= 0) return '[truncated]'; if (v === null || v === undefined) return v; const t = typeof v;`, ` if (t === 'string') return v.length > 100 ? v.substring(0, 100) + '...' : v;`, ` if (t === 'number' || t === 'boolean') return v; if (t === 'bigint') return String(v);`, ` if (t === 'function') return '[Function: ' + (v.name || 'anonymous') + ']';`, ` if (Array.isArray(v)) return v.slice(0, 3).map(i => _sanitize(i, d-1));`, ` if (t === 'object') { if (v instanceof Date) return v.toISOString(); if (v instanceof RegExp) return String(v); if (v instanceof Error) return { error: v.message }; if (v instanceof Promise) return '[Promise]';`, ` const r = {}; const keys = Object.keys(v).slice(0, 10); for (const k of keys) { try { r[k] = _sanitize(v[k], d-1); } catch(e) { r[k] = '[unreadable]'; } } return r; }`, ` return String(v);`, ` }`, ` globalThis.__trickle_var_tracer = function(v, n, l, mod, file) {`, ` try {`, ` if (!_varsFile) {`, ` const dir = process.env.TRICKLE_LOCAL_DIR || __trickle_join(process.cwd(), '.trickle');`, ` try { __trickle_mkdirSync(dir, { recursive: true }); } catch(e) {}`, ` _varsFile = __trickle_join(dir, 'variables.jsonl');`, ` }`, ` const type = _inferType(v, 3);`, ` const th = JSON.stringify(type).substring(0, 32);`, ` const ck = file + ':' + l + ':' + n + ':' + th;`, ` if (_cache.has(ck)) return;`, ` _cache.add(ck);`, ` __trickle_appendFileSync(_varsFile, JSON.stringify({ kind: 'variable', varName: n, line: l, module: mod, file: file, type: type, typeHash: th, sample: _sanitize(v, 2) }) + '\\n');`, ` } catch(e) {}`, ` };`, `}`, `function __trickle_tv(v, n, l) { try { globalThis.__trickle_var_tracer(v, n, l, ${JSON.stringify(moduleName)}, ${JSON.stringify(filename)}); } catch(e) {} }`);
|
|
557
|
+
}
|
|
558
|
+
prefixLines.push('');
|
|
559
|
+
const prefix = prefixLines.join('\n');
|
|
560
|
+
const allInsertions = [];
|
|
561
|
+
for (const { position, name, paramNames } of funcInsertions) {
|
|
223
562
|
const paramNamesArg = paramNames.length > 0 ? JSON.stringify(paramNames) : 'null';
|
|
224
|
-
|
|
225
|
-
|
|
563
|
+
allInsertions.push({
|
|
564
|
+
position,
|
|
565
|
+
code: `\ntry{${name}=__trickle_wrap(${name},'${name}',${paramNamesArg})}catch(__e){}\n`,
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
for (const { lineEnd, varName, lineNo } of varInsertions) {
|
|
569
|
+
allInsertions.push({
|
|
570
|
+
position: lineEnd,
|
|
571
|
+
code: `\n;try{__trickle_tv(${varName},${JSON.stringify(varName)},${lineNo})}catch(__e){}\n`,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
for (const { lineEnd, varNames, lineNo } of destructInsertions) {
|
|
575
|
+
const calls = varNames.map(n => `__trickle_tv(${n},${JSON.stringify(n)},${lineNo})`).join(';');
|
|
576
|
+
allInsertions.push({
|
|
577
|
+
position: lineEnd,
|
|
578
|
+
code: `\n;try{${calls}}catch(__e){}\n`,
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
// Sort by position descending (insert from end to preserve earlier positions)
|
|
582
|
+
allInsertions.sort((a, b) => b.position - a.position);
|
|
583
|
+
let result = source;
|
|
584
|
+
for (const { position, code } of allInsertions) {
|
|
585
|
+
result = result.slice(0, position) + code + result.slice(position);
|
|
226
586
|
}
|
|
227
587
|
return prefix + result;
|
|
228
588
|
}
|
package/dist/wrap.js
CHANGED
|
@@ -4,7 +4,6 @@ exports.typeCache = void 0;
|
|
|
4
4
|
exports.wrapFunction = wrapFunction;
|
|
5
5
|
const type_inference_1 = require("./type-inference");
|
|
6
6
|
const type_hash_1 = require("./type-hash");
|
|
7
|
-
const proxy_tracker_1 = require("./proxy-tracker");
|
|
8
7
|
const cache_1 = require("./cache");
|
|
9
8
|
const transport_1 = require("./transport");
|
|
10
9
|
const typeCache = new cache_1.TypeCache();
|
|
@@ -29,21 +28,14 @@ function wrapFunction(fn, opts) {
|
|
|
29
28
|
if (opts.sampleRate < 1 && Math.random() > opts.sampleRate) {
|
|
30
29
|
return fn.apply(this, args);
|
|
31
30
|
}
|
|
32
|
-
// Set up arg tracking
|
|
33
|
-
const trackers = [];
|
|
34
|
-
const proxiedArgs = args.map((arg, i) => {
|
|
35
|
-
if (arg !== null && arg !== undefined && typeof arg === 'object') {
|
|
36
|
-
const tracker = (0, proxy_tracker_1.createTracker)(arg);
|
|
37
|
-
trackers.push(tracker);
|
|
38
|
-
return tracker.proxy;
|
|
39
|
-
}
|
|
40
|
-
return arg;
|
|
41
|
-
});
|
|
42
31
|
let result;
|
|
43
32
|
let threwError = false;
|
|
44
33
|
let caughtError;
|
|
34
|
+
const trackers = [];
|
|
45
35
|
try {
|
|
46
|
-
|
|
36
|
+
// Always pass ORIGINAL args to the function — never proxied ones.
|
|
37
|
+
// Proxied args can break framework internals (Express Router, DI containers, etc.)
|
|
38
|
+
result = fn.apply(this, args);
|
|
47
39
|
}
|
|
48
40
|
catch (err) {
|
|
49
41
|
threwError = true;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trickle-observe",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "Runtime type observability for JavaScript applications",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
"./auto": "./auto.js",
|
|
13
13
|
"./auto-env": "./auto-env.js",
|
|
14
14
|
"./auto-esm": "./auto-esm.mjs",
|
|
15
|
-
"./vite-plugin": "./dist/vite-plugin.js"
|
|
15
|
+
"./vite-plugin": "./dist/vite-plugin.js",
|
|
16
|
+
"./trace-var": "./dist/trace-var.js"
|
|
16
17
|
},
|
|
17
18
|
"scripts": {
|
|
18
19
|
"build": "tsc",
|
|
@@ -22,6 +23,12 @@
|
|
|
22
23
|
"devDependencies": {
|
|
23
24
|
"typescript": "^5.4.0"
|
|
24
25
|
},
|
|
25
|
-
"keywords": [
|
|
26
|
+
"keywords": [
|
|
27
|
+
"observability",
|
|
28
|
+
"types",
|
|
29
|
+
"runtime",
|
|
30
|
+
"lambda",
|
|
31
|
+
"express"
|
|
32
|
+
],
|
|
26
33
|
"license": "MIT"
|
|
27
34
|
}
|