@gurulu/cli 0.4.0 → 0.4.2

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 (38) hide show
  1. package/dist/commands/add-server.js +13 -6
  2. package/dist/commands/alerts.d.ts +5 -0
  3. package/dist/commands/alerts.js +43 -15
  4. package/dist/commands/audiences.d.ts +3 -0
  5. package/dist/commands/audiences.js +34 -7
  6. package/dist/commands/events.d.ts +6 -0
  7. package/dist/commands/events.js +182 -1
  8. package/dist/commands/experiments.d.ts +4 -0
  9. package/dist/commands/experiments.js +46 -15
  10. package/dist/commands/funnels.d.ts +17 -0
  11. package/dist/commands/funnels.js +203 -0
  12. package/dist/commands/goals.d.ts +18 -0
  13. package/dist/commands/goals.js +214 -0
  14. package/dist/commands/install.d.ts +8 -0
  15. package/dist/commands/install.js +57 -1
  16. package/dist/commands/sourcemap.d.ts +17 -5
  17. package/dist/commands/sourcemap.js +73 -6
  18. package/dist/commands/watch.d.ts +45 -0
  19. package/dist/commands/watch.js +258 -0
  20. package/dist/frameworks/detect.js +29 -7
  21. package/dist/index.js +158 -13
  22. package/package.json +1 -1
  23. package/scripts/gurulu-agentic-install.mjs +275 -3
  24. package/scripts/gurulu-scan.lib.cjs +539 -19
  25. package/scripts/patches/auto-instrument/ast-helper.cjs +158 -10
  26. package/scripts/patches/auto-instrument/astro.cjs +12 -6
  27. package/scripts/patches/auto-instrument/express.cjs +23 -8
  28. package/scripts/patches/auto-instrument/fastify.cjs +7 -3
  29. package/scripts/patches/auto-instrument/hono.cjs +392 -0
  30. package/scripts/patches/auto-instrument/index.cjs +2 -0
  31. package/scripts/patches/auto-instrument/nestjs.cjs +7 -3
  32. package/scripts/patches/auto-instrument/nextjs-app-router.cjs +40 -13
  33. package/scripts/patches/auto-instrument/nextjs-pages.cjs +23 -10
  34. package/scripts/patches/auto-instrument/remix.cjs +7 -3
  35. package/scripts/patches/auto-instrument/sdk-helper-map.cjs +241 -0
  36. package/scripts/patches/auto-instrument/sveltekit.cjs +7 -3
  37. package/scripts/patches/auto-instrument/vue.cjs +7 -3
  38. package/scripts/patches/index.cjs +6 -0
@@ -0,0 +1,392 @@
1
+ // scripts/patches/auto-instrument/hono.cjs — Phase 20 W1 A4.
2
+ //
3
+ // Hono supports several idiomatic route registration shapes:
4
+ //
5
+ // app.get('/users', (c) => { ... });
6
+ // app.post('/orders', async (c) => { ... });
7
+ // const api = new Hono(); api.get('/users', handler);
8
+ // app.get('/health', (c) => c.json({ ok: true })).post('/data', async (c) => { ... });
9
+ //
10
+ // We search the usual server entry files plus `routes/**` for a matching
11
+ // registration, parse the AST, and inject `gurulu.track(...)` into the
12
+ // handler body before the last return.
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const ast = require('./ast-helper.cjs');
18
+ const singleton = require('./singleton-helper.cjs');
19
+
20
+ const NAME = 'auto-instrument-hono';
21
+ const SUPPORTED = ['hono'];
22
+ const MARKER = '// @gurulu-instrumented';
23
+ const IMPORT_LINE_ESM = "import { gurulu } from '@/lib/gurulu';";
24
+
25
+ const CANDIDATE_ENTRIES = [
26
+ 'app.js',
27
+ 'server.js',
28
+ 'index.js',
29
+ 'src/app.js',
30
+ 'src/server.js',
31
+ 'src/index.js',
32
+ 'src/app.ts',
33
+ 'src/server.ts',
34
+ 'src/index.ts',
35
+ 'src/main.ts',
36
+ 'src/main.js',
37
+ ];
38
+
39
+ function parseEventRoute(routeStr) {
40
+ if (!routeStr || typeof routeStr !== 'string') return null;
41
+ const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
42
+ if (!m) return null;
43
+ return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
44
+ }
45
+
46
+ function walkRoutes(repoRoot) {
47
+ const results = [];
48
+ const dirs = ['routes', 'src/routes', 'src/api', 'app', 'src/app'];
49
+ for (const d of dirs) {
50
+ const abs = path.join(repoRoot, d);
51
+ if (!fs.existsSync(abs)) continue;
52
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
53
+ if (entry.isFile() && /\.(js|ts|mjs|cjs)$/.test(entry.name)) {
54
+ results.push(path.posix.join(d, entry.name));
55
+ }
56
+ }
57
+ }
58
+ return results;
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // AST path
63
+ // ---------------------------------------------------------------------------
64
+
65
+ /**
66
+ * Find all `app.<method>('path', ..., handler)` or `api.<method>(...)`
67
+ * or `router.<method>(...)` call expressions matching the given method +
68
+ * urlPath. Hono apps are typically named `app`, `api`, `router`, or
69
+ * `server`. Returns an array of `{ fn, body }` entries.
70
+ */
71
+ function findHonoHandlers(tree, method, urlPath) {
72
+ const t = ast.t;
73
+ const results = [];
74
+ const lowerMethod = method.toLowerCase();
75
+ const HONO_IDENTIFIERS = new Set(['app', 'api', 'router', 'server']);
76
+
77
+ ast.traverse(tree, {
78
+ CallExpression(p) {
79
+ const callee = p.node.callee;
80
+ if (!t.isMemberExpression(callee)) return;
81
+ if (!t.isIdentifier(callee.property) || callee.property.name !== lowerMethod) return;
82
+
83
+ // The object can be a simple identifier (app.get) or a chained call
84
+ // expression (app.get('/a', h).post('/b', h) — the object of `.post`
85
+ // is the preceding CallExpression). We accept identifiers from the
86
+ // known set, and also any CallExpression (chained).
87
+ const obj = callee.object;
88
+ const isKnownIdent = t.isIdentifier(obj) && HONO_IDENTIFIERS.has(obj.name);
89
+ const isChained = t.isCallExpression(obj);
90
+ if (!isKnownIdent && !isChained) return;
91
+
92
+ const args = p.node.arguments;
93
+ if (args.length < 2) return;
94
+ if (!t.isStringLiteral(args[0]) || args[0].value !== urlPath) return;
95
+
96
+ // The final argument should be the handler function.
97
+ const handler = args[args.length - 1];
98
+ if (
99
+ (t.isArrowFunctionExpression(handler) || t.isFunctionExpression(handler)) &&
100
+ t.isBlockStatement(handler.body)
101
+ ) {
102
+ results.push({ fn: handler, body: handler.body });
103
+ }
104
+ },
105
+ });
106
+ return results;
107
+ }
108
+
109
+ function astInstrumentFile(source, method, urlPath, events, opts = {}) {
110
+ const tree = ast.parseSource(source);
111
+ const handlers = findHonoHandlers(tree, method, urlPath);
112
+ if (handlers.length === 0) {
113
+ return { ok: false, reason: 'handler-not-found' };
114
+ }
115
+ const target = handlers[0];
116
+ if (ast.hasInstrumentedMarker(target.fn)) {
117
+ return {
118
+ ok: true,
119
+ after: source,
120
+ instrumented: [],
121
+ skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
122
+ changed: false,
123
+ };
124
+ }
125
+ const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
126
+ ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
127
+ // Sprint D / D4 — alias-aware import.
128
+ const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
129
+ ast.ensureGuruluImport(tree, specifier);
130
+ const after = ast.generateSource(tree, source);
131
+ return {
132
+ ok: true,
133
+ after,
134
+ instrumented: events.map((e) => e.name),
135
+ skipped: [],
136
+ changed: true,
137
+ };
138
+ }
139
+
140
+ // ---------------------------------------------------------------------------
141
+ // Regex fallback
142
+ // ---------------------------------------------------------------------------
143
+
144
+ function regexFindHandlerStart(source, method, urlPath) {
145
+ const lower = method.toLowerCase();
146
+ const escapedPath = urlPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
147
+ const re = new RegExp(
148
+ `(?:app|api|router|server)\\.${lower}\\s*\\(\\s*['"\`]${escapedPath}['"\`]\\s*,`,
149
+ );
150
+ const m = re.exec(source);
151
+ if (!m) return null;
152
+ let i = m.index + m[0].length;
153
+ const tail = source.slice(i);
154
+ const arrowIdx = tail.search(/=>\s*\{/);
155
+ const funcIdx = tail.search(/function\s*[^(]*\([^)]*\)\s*\{/);
156
+ let bodyOpen = -1;
157
+ if (arrowIdx !== -1 && (funcIdx === -1 || arrowIdx < funcIdx)) {
158
+ bodyOpen = i + tail.indexOf('{', arrowIdx);
159
+ } else if (funcIdx !== -1) {
160
+ bodyOpen = i + tail.indexOf('{', funcIdx);
161
+ }
162
+ if (bodyOpen === -1) return null;
163
+ let depth = 0;
164
+ for (let j = bodyOpen; j < source.length; j++) {
165
+ const c = source[j];
166
+ if (c === '{') depth++;
167
+ else if (c === '}') {
168
+ depth--;
169
+ if (depth === 0) return { start: bodyOpen, end: j };
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+
175
+ function regexFindLastResponseCall(source, start, end) {
176
+ const snippet = source.slice(start, end);
177
+ // Hono response patterns: c.json(), c.text(), c.html(), c.body(),
178
+ // c.redirect(), c.notFound()
179
+ const patterns = [
180
+ /c\.json\s*\(/g,
181
+ /c\.text\s*\(/g,
182
+ /c\.html\s*\(/g,
183
+ /c\.body\s*\(/g,
184
+ /c\.redirect\s*\(/g,
185
+ /c\.notFound\s*\(/g,
186
+ /return\s+c\./g,
187
+ ];
188
+ let lastIdx = -1;
189
+ for (const re of patterns) {
190
+ let m;
191
+ while ((m = re.exec(snippet)) !== null) {
192
+ if (m.index > lastIdx) lastIdx = m.index;
193
+ }
194
+ }
195
+ if (lastIdx === -1) return null;
196
+ const absoluteIdx = start + lastIdx;
197
+ let lineStart = absoluteIdx;
198
+ while (lineStart > 0 && source[lineStart - 1] !== '\n') lineStart--;
199
+ const indentMatch = source.slice(lineStart, absoluteIdx).match(/^(\s*)/);
200
+ const indent = (indentMatch && indentMatch[1]) || ' ';
201
+ return { insertAt: lineStart, indent };
202
+ }
203
+
204
+ function regexEnsureImport(source, opts = {}) {
205
+ if (source.includes(IMPORT_LINE_ESM)) return source;
206
+ // Sprint D / D4 — alias-aware specifier.
207
+ const specifier =
208
+ opts.repoRoot
209
+ ? ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath)
210
+ : '@/lib/gurulu';
211
+ const importLine = `import { gurulu } from '${specifier}';`;
212
+ if (source.includes(importLine)) return source;
213
+ const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
214
+ const m = source.match(importRegex);
215
+ if (m) {
216
+ const end = m.index + m[0].length;
217
+ return source.slice(0, end) + importLine + '\n' + source.slice(end);
218
+ }
219
+ return importLine + '\n' + source;
220
+ }
221
+
222
+ function regexBuildTrackCall(eventName, indent) {
223
+ const safeName = JSON.stringify(eventName);
224
+ return `${indent}${MARKER} ${eventName}\n${indent}gurulu.track(${safeName}, {});\n`;
225
+ }
226
+
227
+ function regexInstrumentFile(before, method, urlPath, events, opts = {}) {
228
+ const body = regexFindHandlerStart(before, method, urlPath);
229
+ if (!body) return { ok: false, reason: 'handler-not-found' };
230
+ const snippet = before.slice(body.start, body.end);
231
+ const needed = [];
232
+ const skipped = [];
233
+ for (const e of events) {
234
+ if (snippet.includes(`${MARKER} ${e.name}`)) {
235
+ skipped.push({ event: e.name, reason: 'already-instrumented' });
236
+ } else {
237
+ needed.push(e);
238
+ }
239
+ }
240
+ if (needed.length === 0) return { ok: true, after: before, instrumented: [], skipped, changed: false };
241
+ const ret = regexFindLastResponseCall(before, body.start, body.end);
242
+ if (!ret) return { ok: false, reason: 'no-response-found' };
243
+ const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent)).join('');
244
+ let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
245
+ after = regexEnsureImport(after, opts);
246
+ return {
247
+ ok: true,
248
+ after,
249
+ instrumented: needed.map((e) => e.name),
250
+ skipped,
251
+ changed: true,
252
+ };
253
+ }
254
+
255
+ // ---------------------------------------------------------------------------
256
+ // Glue
257
+ // ---------------------------------------------------------------------------
258
+
259
+ function resolveRouteFile(ctx, method, urlPath) {
260
+ const seen = new Set();
261
+ const candidates = [
262
+ ...CANDIDATE_ENTRIES,
263
+ ...walkRoutes(ctx.repoRoot),
264
+ ].filter((rel) => {
265
+ if (seen.has(rel)) return false;
266
+ seen.add(rel);
267
+ return fs.existsSync(path.join(ctx.repoRoot, rel));
268
+ });
269
+ for (const rel of candidates) {
270
+ const src = fs.readFileSync(path.join(ctx.repoRoot, rel), 'utf8');
271
+ // Cheap pre-filter: must contain `.${method.toLowerCase()}(`.
272
+ if (!src.includes(`.${method.toLowerCase()}(`)) continue;
273
+ try {
274
+ const tree = ast.parseSource(src);
275
+ const handlers = findHonoHandlers(tree, method, urlPath);
276
+ if (handlers.length > 0) return { relPath: rel };
277
+ } catch (_) {
278
+ // Regex check as last-ditch.
279
+ if (regexFindHandlerStart(src, method, urlPath)) return { relPath: rel };
280
+ }
281
+ }
282
+ return null;
283
+ }
284
+
285
+ function instrumentEvents(ctx, events) {
286
+ const helper = singleton.ensureSingletonHelper(ctx, 'hono');
287
+ const changes = [...helper.changes];
288
+ const notes = [...helper.notes];
289
+ let eventsInstrumented = 0;
290
+ let eventsSkipped = 0;
291
+
292
+ if (helper.collision) {
293
+ return {
294
+ changes: [],
295
+ notes,
296
+ filesModified: 0,
297
+ eventsInstrumented: 0,
298
+ eventsSkipped: events ? events.length : 0,
299
+ collision: true,
300
+ };
301
+ }
302
+
303
+ const groups = new Map();
304
+ for (const e of events || []) {
305
+ const parsed = parseEventRoute(e && e.source && e.source.route);
306
+ if (!parsed) {
307
+ notes.push(`skip:${e && e.name}:no-source-route`);
308
+ eventsSkipped++;
309
+ continue;
310
+ }
311
+ const resolved = resolveRouteFile(ctx, parsed.method, parsed.urlPath);
312
+ if (!resolved) {
313
+ notes.push(`skip:${e.name}:route-not-found`);
314
+ eventsSkipped++;
315
+ continue;
316
+ }
317
+ const key = `${resolved.relPath}::${parsed.method}::${parsed.urlPath}`;
318
+ if (!groups.has(key)) {
319
+ groups.set(key, {
320
+ relPath: resolved.relPath,
321
+ method: parsed.method,
322
+ urlPath: parsed.urlPath,
323
+ events: [],
324
+ });
325
+ }
326
+ groups.get(key).events.push(e);
327
+ }
328
+
329
+ for (const group of groups.values()) {
330
+ const abs = path.join(ctx.repoRoot, group.relPath);
331
+ const before = fs.readFileSync(abs, 'utf8');
332
+ // Sprint D / D4 — thread repoRoot + relPath into the import resolver.
333
+ const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
334
+ let res;
335
+ try {
336
+ res = astInstrumentFile(before, group.method, group.urlPath, group.events, fileOpts);
337
+ } catch (err) {
338
+ const msg = (err && err.message) || String(err);
339
+ // eslint-disable-next-line no-console
340
+ console.warn(`[auto-instrument] patch.fallback ${group.relPath}: ${msg}`);
341
+ notes.push(`patch.fallback:${group.relPath}:${msg}`);
342
+ res = regexInstrumentFile(before, group.method, group.urlPath, group.events, fileOpts);
343
+ }
344
+ if (!res.ok) {
345
+ for (const e of group.events) {
346
+ notes.push(`skip:${e.name}:${res.reason || 'instrument-failed'}`);
347
+ eventsSkipped++;
348
+ }
349
+ continue;
350
+ }
351
+ for (const s of res.skipped || []) {
352
+ notes.push(`skip:${s.event}:${s.reason}`);
353
+ eventsSkipped++;
354
+ }
355
+ if (!res.changed) continue;
356
+ const existing = changes.find((c) => c.relPath === group.relPath && c.type === 'auto-instrument');
357
+ if (existing) {
358
+ existing.after = res.after;
359
+ } else {
360
+ changes.push({
361
+ relPath: group.relPath,
362
+ before,
363
+ after: res.after,
364
+ reason: `auto-instrument-${group.method}`,
365
+ type: 'auto-instrument',
366
+ });
367
+ }
368
+ eventsInstrumented += (res.instrumented || []).length;
369
+ }
370
+
371
+ const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
372
+ return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
373
+ }
374
+
375
+ function ensureSingletonHelper(ctx) {
376
+ return singleton.ensureSingletonHelper(ctx, 'hono');
377
+ }
378
+
379
+ module.exports = {
380
+ name: NAME,
381
+ supportedFrameworks: SUPPORTED,
382
+ ensureSingletonHelper,
383
+ instrumentEvents,
384
+ _internals: {
385
+ parseEventRoute,
386
+ resolveRouteFile,
387
+ astInstrumentFile,
388
+ regexInstrumentFile,
389
+ walkRoutes,
390
+ findHonoHandlers,
391
+ },
392
+ };
@@ -16,6 +16,7 @@ const remix = require('./remix.cjs');
16
16
  const sveltekit = require('./sveltekit.cjs');
17
17
  const astro = require('./astro.cjs');
18
18
  const fastify = require('./fastify.cjs');
19
+ const hono = require('./hono.cjs');
19
20
  const vue = require('./vue.cjs');
20
21
  const singleton = require('./singleton-helper.cjs');
21
22
 
@@ -29,6 +30,7 @@ const MODULES = [
29
30
  sveltekit,
30
31
  astro,
31
32
  fastify,
33
+ hono,
32
34
  vue,
33
35
  ];
34
36
 
@@ -119,7 +119,7 @@ function collectControllerMethods(tree) {
119
119
  return results;
120
120
  }
121
121
 
122
- function astInstrumentFile(source, targets) {
122
+ function astInstrumentFile(source, targets, opts = {}) {
123
123
  // targets: [{ httpMethod, urlPath, events: [] }]
124
124
  const tree = ast.parseSource(source);
125
125
  const methods = collectControllerMethods(tree);
@@ -149,7 +149,9 @@ function astInstrumentFile(source, targets) {
149
149
  if (!changed) {
150
150
  return { ok: true, after: source, instrumented: [], skipped, changed: false };
151
151
  }
152
- ast.ensureGuruluImport(tree);
152
+ // Sprint D / D4 — alias-aware import.
153
+ const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
154
+ ast.ensureGuruluImport(tree, specifier);
153
155
  const after = ast.generateSource(tree, source);
154
156
  return { ok: true, after, instrumented: instrumentedNames, skipped, changed: true };
155
157
  }
@@ -223,9 +225,11 @@ function instrumentEvents(ctx, events) {
223
225
  const abs = path.join(ctx.repoRoot, rel);
224
226
  const before = fs.readFileSync(abs, 'utf8');
225
227
  const targets = Array.from(perFile.values());
228
+ // Sprint D / D4 — pass repoRoot + relPath to the import resolver.
229
+ const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: rel };
226
230
  let res;
227
231
  try {
228
- res = astInstrumentFile(before, targets);
232
+ res = astInstrumentFile(before, targets, fileOpts);
229
233
  } catch (err) {
230
234
  const msg = (err && err.message) || String(err);
231
235
  // eslint-disable-next-line no-console
@@ -70,13 +70,16 @@ function astInstrumentFile(source, method, events, opts = {}) {
70
70
  };
71
71
  }
72
72
  const trackStmts = events.map((e) =>
73
- ast.buildTrackStatement(e.name, e.autoProperties || opts.autoProperties && e.extractedProperties),
73
+ ast.buildTrackStatement(e.name, e.extractedProperties || e.autoProperties),
74
74
  );
75
75
  const injected = ast.injectTrackBeforeLastReturn(target.fn, target.body, trackStmts);
76
76
  if (!injected) {
77
77
  return { ok: false, reason: 'inject-failed' };
78
78
  }
79
- ast.ensureGuruluImport(tree);
79
+ // Sprint D / D4 — pick `@/lib/gurulu` only when tsconfig is wired,
80
+ // otherwise fall back to a relative import from the route file.
81
+ const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
82
+ ast.ensureGuruluImport(tree, specifier);
80
83
  const after = ast.generateSource(tree, source);
81
84
  return {
82
85
  ok: true,
@@ -92,15 +95,27 @@ function astInstrumentFile(source, method, events, opts = {}) {
92
95
  // scope for graceful degradation.
93
96
  // ---------------------------------------------------------------------------
94
97
 
95
- function regexEnsureImport(source) {
96
- if (source.includes(IMPORT_LINE)) return { source, added: false };
98
+ function regexEnsureImport(source, opts = {}) {
99
+ // Sprint D / D4 same `@/lib/gurulu` vs relative-path detection as the
100
+ // AST path. Falls back to the alias form for older test fixtures that
101
+ // don't pass a repoRoot.
102
+ const specifier =
103
+ opts.repoRoot
104
+ ? ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath)
105
+ : '@/lib/gurulu';
106
+ const importLine = `import { gurulu } from '${specifier}';`;
107
+ if (source.includes(importLine)) return { source, added: false };
108
+ // Don't double-import: if the legacy alias line exists, leave it alone.
109
+ if (specifier !== '@/lib/gurulu' && source.includes(IMPORT_LINE)) {
110
+ return { source, added: false };
111
+ }
97
112
  const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
98
113
  const m = source.match(importRegex);
99
114
  if (m) {
100
115
  const end = m.index + m[0].length;
101
- return { source: source.slice(0, end) + IMPORT_LINE + '\n' + source.slice(end), added: true };
116
+ return { source: source.slice(0, end) + importLine + '\n' + source.slice(end), added: true };
102
117
  }
103
- return { source: IMPORT_LINE + '\n' + source, added: true };
118
+ return { source: importLine + '\n' + source, added: true };
104
119
  }
105
120
 
106
121
  function regexFindMethodBody(source, method) {
@@ -147,15 +162,24 @@ function regexFindLastReturnInBody(source, start, end) {
147
162
  return { insertAt: lineStart, indent };
148
163
  }
149
164
 
150
- function regexBuildTrackCall(eventName, indent) {
165
+ function regexBuildTrackCall(eventName, indent, extractedProperties) {
151
166
  const safeName = JSON.stringify(eventName);
167
+ let propsStr = '{}';
168
+ if (Array.isArray(extractedProperties) && extractedProperties.length > 0) {
169
+ const entries = extractedProperties
170
+ .filter((p) => p && p.name && p.source)
171
+ .map((p) => `${p.name}: ${p.source}`);
172
+ if (entries.length > 0) {
173
+ propsStr = `{ ${entries.join(', ')} }`;
174
+ }
175
+ }
152
176
  return (
153
177
  `${indent}${MARKER} ${eventName}\n` +
154
- `${indent}gurulu.track(${safeName}, {});\n`
178
+ `${indent}gurulu.track(${safeName}, ${propsStr});\n`
155
179
  );
156
180
  }
157
181
 
158
- function regexInstrumentFile(before, method, events) {
182
+ function regexInstrumentFile(before, method, events, opts = {}) {
159
183
  const body = regexFindMethodBody(before, method);
160
184
  if (!body) {
161
185
  return { ok: false, reason: `method-${method}-not-found` };
@@ -173,9 +197,9 @@ function regexInstrumentFile(before, method, events) {
173
197
  if (needed.length === 0) return { ok: true, after: before, instrumented: [], skipped, changed: false };
174
198
  const ret = regexFindLastReturnInBody(before, body.start, body.end);
175
199
  if (!ret) return { ok: false, reason: 'no-return-found' };
176
- const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent)).join('');
200
+ const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent, e.extractedProperties)).join('');
177
201
  let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
178
- after = regexEnsureImport(after).source;
202
+ after = regexEnsureImport(after, opts).source;
179
203
  return {
180
204
  ok: true,
181
205
  after,
@@ -196,15 +220,18 @@ function instrumentRouteFile(ctx, relPath, method, events) {
196
220
  }
197
221
  const before = fs.readFileSync(abs, 'utf8');
198
222
  const notes = [];
223
+ // Sprint D / D4 — thread repoRoot + relPath through to the import
224
+ // resolver so `@/*` and relative-path setups pick the right specifier.
225
+ const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath };
199
226
  let res;
200
227
  try {
201
- res = astInstrumentFile(before, method, events, ctx || {});
228
+ res = astInstrumentFile(before, method, events, { ...(ctx || {}), ...fileOpts });
202
229
  } catch (err) {
203
230
  const msg = (err && err.message) || String(err);
204
231
  // eslint-disable-next-line no-console
205
232
  console.warn(`[auto-instrument] patch.fallback ${relPath}: ${msg}`);
206
233
  notes.push(`patch.fallback:${relPath}:${msg}`);
207
- res = regexInstrumentFile(before, method, events);
234
+ res = regexInstrumentFile(before, method, events, fileOpts);
208
235
  }
209
236
  if (!res.ok) {
210
237
  return {
@@ -89,7 +89,7 @@ function matchesMethodTest(node, method) {
89
89
  return false;
90
90
  }
91
91
 
92
- function astInstrumentFile(source, method, events) {
92
+ function astInstrumentFile(source, method, events, opts = {}) {
93
93
  const tree = ast.parseSource(source);
94
94
  const fns = ast.findExportedFunction(tree, 'default', { defaultExport: true });
95
95
  if (fns.length === 0) {
@@ -109,7 +109,9 @@ function astInstrumentFile(source, method, events) {
109
109
  const injectBody = branch || target.body;
110
110
  const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
111
111
  ast.injectTrackBeforeLastReturn(target.fn, injectBody, stmts);
112
- ast.ensureGuruluImport(tree);
112
+ // Sprint D / D4 — alias-aware import.
113
+ const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
114
+ ast.ensureGuruluImport(tree, specifier);
113
115
  const after = ast.generateSource(tree, source);
114
116
  return {
115
117
  ok: true,
@@ -124,15 +126,24 @@ function astInstrumentFile(source, method, events) {
124
126
  // Regex fallback
125
127
  // ---------------------------------------------------------------------------
126
128
 
127
- function regexEnsureImport(source) {
128
- if (source.includes(IMPORT_LINE)) return source;
129
+ function regexEnsureImport(source, opts = {}) {
130
+ // Sprint D / D4 — alias-aware specifier.
131
+ const specifier =
132
+ opts.repoRoot
133
+ ? ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath)
134
+ : '@/lib/gurulu';
135
+ const importLine = `import { gurulu } from '${specifier}';`;
136
+ if (source.includes(importLine)) return source;
137
+ if (specifier !== '@/lib/gurulu' && source.includes(IMPORT_LINE)) {
138
+ return source;
139
+ }
129
140
  const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
130
141
  const m = source.match(importRegex);
131
142
  if (m) {
132
143
  const end = m.index + m[0].length;
133
- return source.slice(0, end) + IMPORT_LINE + '\n' + source.slice(end);
144
+ return source.slice(0, end) + importLine + '\n' + source.slice(end);
134
145
  }
135
- return IMPORT_LINE + '\n' + source;
146
+ return importLine + '\n' + source;
136
147
  }
137
148
 
138
149
  function regexFindHandlerBody(source) {
@@ -191,7 +202,7 @@ function regexBuildTrackCall(eventName, indent) {
191
202
  return `${indent}${MARKER} ${eventName}\n${indent}gurulu.track(${safeName}, {});\n`;
192
203
  }
193
204
 
194
- function regexInstrumentFile(before, method, events) {
205
+ function regexInstrumentFile(before, method, events, opts = {}) {
195
206
  const body = regexFindHandlerBody(before);
196
207
  if (!body) return { ok: false, reason: 'handler-not-found' };
197
208
  const snippet = before.slice(body.start, body.end);
@@ -209,7 +220,7 @@ function regexInstrumentFile(before, method, events) {
209
220
  if (!ret) return { ok: false, reason: 'no-response-found' };
210
221
  const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent)).join('');
211
222
  let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
212
- after = regexEnsureImport(after);
223
+ after = regexEnsureImport(after, opts);
213
224
  return {
214
225
  ok: true,
215
226
  after,
@@ -230,15 +241,17 @@ function instrumentRouteFile(ctx, relPath, method, events) {
230
241
  }
231
242
  const before = fs.readFileSync(abs, 'utf8');
232
243
  const notes = [];
244
+ // Sprint D / D4 — thread repoRoot + relPath through to the import resolver.
245
+ const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath };
233
246
  let res;
234
247
  try {
235
- res = astInstrumentFile(before, method, events);
248
+ res = astInstrumentFile(before, method, events, fileOpts);
236
249
  } catch (err) {
237
250
  const msg = (err && err.message) || String(err);
238
251
  // eslint-disable-next-line no-console
239
252
  console.warn(`[auto-instrument] patch.fallback ${relPath}: ${msg}`);
240
253
  notes.push(`patch.fallback:${relPath}:${msg}`);
241
- res = regexInstrumentFile(before, method, events);
254
+ res = regexInstrumentFile(before, method, events, fileOpts);
242
255
  }
243
256
  if (!res.ok) {
244
257
  return {
@@ -40,7 +40,7 @@ function routeToCandidates(urlPath) {
40
40
  return out;
41
41
  }
42
42
 
43
- function astInstrumentFile(source, method, events) {
43
+ function astInstrumentFile(source, method, events, opts = {}) {
44
44
  const tree = ast.parseSource(source);
45
45
  // Reads → `loader`, writes → `action`. Per Remix convention.
46
46
  const exportName = method === 'GET' || method === 'HEAD' ? 'loader' : 'action';
@@ -58,7 +58,9 @@ function astInstrumentFile(source, method, events) {
58
58
  }
59
59
  const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
60
60
  ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
61
- ast.ensureGuruluImport(tree);
61
+ // Sprint D / D4 — alias-aware import.
62
+ const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
63
+ ast.ensureGuruluImport(tree, specifier);
62
64
  const after = ast.generateSource(tree, source);
63
65
  return {
64
66
  ok: true,
@@ -110,9 +112,11 @@ function instrumentEvents(ctx, events) {
110
112
  for (const group of groups.values()) {
111
113
  const abs = path.join(ctx.repoRoot, group.relPath);
112
114
  const before = fs.readFileSync(abs, 'utf8');
115
+ // Sprint D / D4 — pass repoRoot + relPath to the import resolver.
116
+ const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
113
117
  let res;
114
118
  try {
115
- res = astInstrumentFile(before, group.method, group.events);
119
+ res = astInstrumentFile(before, group.method, group.events, fileOpts);
116
120
  } catch (err) {
117
121
  const msg = (err && err.message) || String(err);
118
122
  // eslint-disable-next-line no-console