@gurulu/cli 0.4.7 → 1.0.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 (190) hide show
  1. package/LICENSE +92 -0
  2. package/README.md +35 -106
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +25751 -0
  6. package/dist/commands/auth.d.ts +23 -20
  7. package/dist/commands/auth.d.ts.map +1 -0
  8. package/dist/commands/doctor.d.ts +20 -6
  9. package/dist/commands/doctor.d.ts.map +1 -0
  10. package/dist/commands/init.d.ts +33 -11
  11. package/dist/commands/init.d.ts.map +1 -0
  12. package/dist/commands/pull.d.ts +13 -0
  13. package/dist/commands/pull.d.ts.map +1 -0
  14. package/dist/commands/push.d.ts +40 -0
  15. package/dist/commands/push.d.ts.map +1 -0
  16. package/dist/commands/validate.d.ts +36 -0
  17. package/dist/commands/validate.d.ts.map +1 -0
  18. package/dist/index.d.ts +4 -1
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +25326 -876
  21. package/dist/lib/api.d.ts +139 -0
  22. package/dist/lib/api.d.ts.map +1 -0
  23. package/dist/lib/codegen.d.ts +4 -0
  24. package/dist/lib/codegen.d.ts.map +1 -0
  25. package/dist/lib/config.d.ts +43 -0
  26. package/dist/lib/config.d.ts.map +1 -0
  27. package/dist/lib/detect.d.ts +27 -0
  28. package/dist/lib/detect.d.ts.map +1 -0
  29. package/dist/lib/detect.js +106 -0
  30. package/dist/lib/exec-install.d.ts +21 -0
  31. package/dist/lib/exec-install.d.ts.map +1 -0
  32. package/dist/lib/install-plan.d.ts +25 -0
  33. package/dist/lib/install-plan.d.ts.map +1 -0
  34. package/dist/lib/install-plan.js +161 -0
  35. package/package.json +51 -20
  36. package/bin/gurulu.js +0 -2
  37. package/dist/api-client.d.ts +0 -33
  38. package/dist/api-client.js +0 -175
  39. package/dist/commands/add-server.d.ts +0 -9
  40. package/dist/commands/add-server.js +0 -162
  41. package/dist/commands/alerts.d.ts +0 -27
  42. package/dist/commands/alerts.js +0 -309
  43. package/dist/commands/api-keys.d.ts +0 -20
  44. package/dist/commands/api-keys.js +0 -130
  45. package/dist/commands/attribution.d.ts +0 -22
  46. package/dist/commands/attribution.js +0 -111
  47. package/dist/commands/audiences.d.ts +0 -23
  48. package/dist/commands/audiences.js +0 -243
  49. package/dist/commands/audit.d.ts +0 -20
  50. package/dist/commands/audit.js +0 -130
  51. package/dist/commands/auth.js +0 -249
  52. package/dist/commands/chat.d.ts +0 -19
  53. package/dist/commands/chat.js +0 -118
  54. package/dist/commands/config.d.ts +0 -10
  55. package/dist/commands/config.js +0 -92
  56. package/dist/commands/consent.d.ts +0 -27
  57. package/dist/commands/consent.js +0 -233
  58. package/dist/commands/conversion-paths.d.ts +0 -19
  59. package/dist/commands/conversion-paths.js +0 -55
  60. package/dist/commands/db.d.ts +0 -25
  61. package/dist/commands/db.js +0 -330
  62. package/dist/commands/destinations.d.ts +0 -20
  63. package/dist/commands/destinations.js +0 -191
  64. package/dist/commands/doctor.js +0 -360
  65. package/dist/commands/errors.d.ts +0 -27
  66. package/dist/commands/errors.js +0 -121
  67. package/dist/commands/events.d.ts +0 -33
  68. package/dist/commands/events.js +0 -371
  69. package/dist/commands/experiments.d.ts +0 -22
  70. package/dist/commands/experiments.js +0 -264
  71. package/dist/commands/funnels.d.ts +0 -17
  72. package/dist/commands/funnels.js +0 -203
  73. package/dist/commands/goals.d.ts +0 -18
  74. package/dist/commands/goals.js +0 -214
  75. package/dist/commands/heatmap.d.ts +0 -27
  76. package/dist/commands/heatmap.js +0 -112
  77. package/dist/commands/identity.d.ts +0 -29
  78. package/dist/commands/identity.js +0 -328
  79. package/dist/commands/init.js +0 -215
  80. package/dist/commands/insights.d.ts +0 -10
  81. package/dist/commands/insights.js +0 -77
  82. package/dist/commands/install.d.ts +0 -259
  83. package/dist/commands/install.js +0 -1590
  84. package/dist/commands/login.d.ts +0 -20
  85. package/dist/commands/login.js +0 -170
  86. package/dist/commands/logout.d.ts +0 -10
  87. package/dist/commands/logout.js +0 -41
  88. package/dist/commands/playground.d.ts +0 -11
  89. package/dist/commands/playground.js +0 -47
  90. package/dist/commands/releases.d.ts +0 -17
  91. package/dist/commands/releases.js +0 -54
  92. package/dist/commands/replay.d.ts +0 -18
  93. package/dist/commands/replay.js +0 -64
  94. package/dist/commands/secrets.d.ts +0 -19
  95. package/dist/commands/secrets.js +0 -145
  96. package/dist/commands/setup.d.ts +0 -21
  97. package/dist/commands/setup.js +0 -67
  98. package/dist/commands/sites.d.ts +0 -18
  99. package/dist/commands/sites.js +0 -139
  100. package/dist/commands/skad.d.ts +0 -18
  101. package/dist/commands/skad.js +0 -53
  102. package/dist/commands/sourcemap.d.ts +0 -33
  103. package/dist/commands/sourcemap.js +0 -204
  104. package/dist/commands/status.d.ts +0 -7
  105. package/dist/commands/status.js +0 -136
  106. package/dist/commands/upgrade.d.ts +0 -21
  107. package/dist/commands/upgrade.js +0 -183
  108. package/dist/commands/warehouse.d.ts +0 -20
  109. package/dist/commands/warehouse.js +0 -65
  110. package/dist/commands/warehouses.d.ts +0 -17
  111. package/dist/commands/warehouses.js +0 -182
  112. package/dist/commands/watch.d.ts +0 -45
  113. package/dist/commands/watch.js +0 -258
  114. package/dist/commands/whoami.d.ts +0 -9
  115. package/dist/commands/whoami.js +0 -50
  116. package/dist/config.d.ts +0 -75
  117. package/dist/config.js +0 -329
  118. package/dist/frameworks/detect.d.ts +0 -8
  119. package/dist/frameworks/detect.js +0 -458
  120. package/dist/install-intent-proposal.d.ts +0 -99
  121. package/dist/install-intent-proposal.js +0 -202
  122. package/dist/utils/api.d.ts +0 -20
  123. package/dist/utils/api.js +0 -47
  124. package/dist/utils/config.d.ts +0 -13
  125. package/dist/utils/config.js +0 -30
  126. package/dist/utils/confirm.d.ts +0 -17
  127. package/dist/utils/confirm.js +0 -40
  128. package/dist/utils/dry-run.d.ts +0 -20
  129. package/dist/utils/dry-run.js +0 -67
  130. package/dist/utils/from-file.d.ts +0 -9
  131. package/dist/utils/from-file.js +0 -72
  132. package/dist/utils/redact.d.ts +0 -14
  133. package/dist/utils/redact.js +0 -48
  134. package/dist/utils/ui.d.ts +0 -14
  135. package/dist/utils/ui.js +0 -59
  136. package/scripts/.gitkeep +0 -0
  137. package/scripts/README-gurulu-agentic-install.md +0 -114
  138. package/scripts/README-gurulu-scan.md +0 -98
  139. package/scripts/audit-cli-scopes.mjs +0 -204
  140. package/scripts/backfill-tenant-id.mjs +0 -172
  141. package/scripts/backfill-tenant-links.ts +0 -252
  142. package/scripts/backup-clickhouse.sh +0 -27
  143. package/scripts/backup-postgres.sh +0 -19
  144. package/scripts/bootstrap-runtime-schema.mjs +0 -87
  145. package/scripts/bootstrap-stripe.mjs +0 -158
  146. package/scripts/gurulu-agentic-install.lib.cjs +0 -762
  147. package/scripts/gurulu-agentic-install.mjs +0 -623
  148. package/scripts/gurulu-scan.lib.cjs +0 -1509
  149. package/scripts/gurulu-scan.mjs +0 -91
  150. package/scripts/gurulu-verify-install.lib.cjs +0 -334
  151. package/scripts/gurulu-verify-install.mjs +0 -59
  152. package/scripts/init-ssl.sh +0 -26
  153. package/scripts/migrate-flow-graph-enums.sh +0 -86
  154. package/scripts/monitor-disk.sh +0 -24
  155. package/scripts/patches/astro.patch.cjs +0 -74
  156. package/scripts/patches/auto-instrument/ast-helper.cjs +0 -480
  157. package/scripts/patches/auto-instrument/astro.cjs +0 -273
  158. package/scripts/patches/auto-instrument/express.cjs +0 -383
  159. package/scripts/patches/auto-instrument/fastify.cjs +0 -262
  160. package/scripts/patches/auto-instrument/hono.cjs +0 -392
  161. package/scripts/patches/auto-instrument/index.cjs +0 -80
  162. package/scripts/patches/auto-instrument/nestjs.cjs +0 -286
  163. package/scripts/patches/auto-instrument/nextjs-app-router.cjs +0 -345
  164. package/scripts/patches/auto-instrument/nextjs-pages.cjs +0 -361
  165. package/scripts/patches/auto-instrument/remix.cjs +0 -168
  166. package/scripts/patches/auto-instrument/sdk-helper-map.cjs +0 -241
  167. package/scripts/patches/auto-instrument/singleton-helper.cjs +0 -193
  168. package/scripts/patches/auto-instrument/sveltekit.cjs +0 -161
  169. package/scripts/patches/auto-instrument/vite-react.cjs +0 -37
  170. package/scripts/patches/auto-instrument/vue.cjs +0 -196
  171. package/scripts/patches/express.patch.cjs +0 -99
  172. package/scripts/patches/fastify.patch.cjs +0 -108
  173. package/scripts/patches/index.cjs +0 -300
  174. package/scripts/patches/nestjs.patch.cjs +0 -112
  175. package/scripts/patches/nextjs-app-router.patch.cjs +0 -97
  176. package/scripts/patches/nextjs-pages.patch.cjs +0 -97
  177. package/scripts/patches/remix.patch.cjs +0 -75
  178. package/scripts/patches/sveltekit.patch.cjs +0 -72
  179. package/scripts/patches/vite-react.patch.cjs +0 -73
  180. package/scripts/patches/vue.patch.cjs +0 -82
  181. package/scripts/renew-ssl.sh +0 -14
  182. package/scripts/resolve-migration.sh +0 -23
  183. package/scripts/seed-cli-dev-keys.mjs +0 -130
  184. package/scripts/seed-test-data.mjs +0 -391
  185. package/scripts/spike-browserless.ts +0 -65
  186. package/scripts/tenant-pivot-consistency-check.mjs +0 -205
  187. package/scripts/tenant-pivot-phase-3-cleanup.lib.cjs +0 -258
  188. package/scripts/tenant-pivot-phase-3-cleanup.mjs +0 -98
  189. package/scripts/test-identity-resolution.ts +0 -804
  190. package/scripts/validate-gurulu-schemas.mjs +0 -79
@@ -1,273 +0,0 @@
1
- // scripts/patches/auto-instrument/astro.cjs — Phase 20 W1 A3.
2
- //
3
- // Astro API endpoints live at `src/pages/api/**.{ts,js}` and export HTTP
4
- // verb functions (`GET`, `POST`, ...). `.astro` components with a server
5
- // frontmatter block (between `---` fences) are also supported: the patcher
6
- // extracts the frontmatter JS/TS, detects server-side fetch/data-loading
7
- // patterns, and injects `gurulu.track()` calls.
8
-
9
- const fs = require('fs');
10
- const path = require('path');
11
-
12
- const ast = require('./ast-helper.cjs');
13
- const singleton = require('./singleton-helper.cjs');
14
-
15
- const NAME = 'auto-instrument-astro';
16
- const SUPPORTED = ['astro'];
17
-
18
- function parseEventRoute(routeStr) {
19
- if (!routeStr || typeof routeStr !== 'string') return null;
20
- const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
21
- if (!m) return null;
22
- return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
23
- }
24
-
25
- function routeToCandidates(urlPath) {
26
- const cleaned = urlPath.replace(/^\//, '').replace(/\/+$/, '');
27
- const segments = cleaned.split('/').filter(Boolean);
28
- const exts = ['ts', 'js', 'mjs'];
29
- const out = [];
30
- for (const ext of exts) {
31
- out.push(path.posix.join('src', 'pages', ...segments) + `.${ext}`);
32
- out.push(path.posix.join('src', 'pages', ...segments, `index.${ext}`));
33
- }
34
- // .astro component files (page routes, not API endpoints)
35
- out.push(path.posix.join('src', 'pages', ...segments) + '.astro');
36
- out.push(path.posix.join('src', 'pages', ...segments, 'index.astro'));
37
- return out;
38
- }
39
-
40
- // ---------------------------------------------------------------------------
41
- // .astro frontmatter support
42
- // ---------------------------------------------------------------------------
43
-
44
- const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
45
-
46
- /**
47
- * Server-side data-loading patterns we look for inside .astro frontmatter.
48
- * If any match, we consider the frontmatter instrumentable.
49
- */
50
- const DATA_LOADING_PATTERNS = [
51
- /\bfetch\s*\(/,
52
- /\bawait\b/,
53
- /\bgetCollection\s*\(/,
54
- /\bgetEntryBySlug\s*\(/,
55
- /\bAstro\s*\.\s*glob\s*\(/,
56
- /\bimport\s*\(/, // dynamic import
57
- /\.findMany\s*\(/,
58
- /\.find\s*\(/,
59
- /\.query\s*\(/,
60
- /\.select\s*\(/,
61
- ];
62
-
63
- function hasDataLoadingPattern(frontmatterSource) {
64
- return DATA_LOADING_PATTERNS.some((re) => re.test(frontmatterSource));
65
- }
66
-
67
- /**
68
- * Instrument an .astro file's frontmatter block. Parses the JS/TS inside the
69
- * `---` fences via the shared AST helper, injects gurulu.track() calls, and
70
- * reconstructs the full .astro file.
71
- */
72
- function astInstrumentFrontmatter(source, events, opts = {}) {
73
- const fmMatch = source.match(FRONTMATTER_RE);
74
- if (!fmMatch) return { ok: false, reason: 'no-frontmatter' };
75
-
76
- const frontmatter = fmMatch[1];
77
- if (!hasDataLoadingPattern(frontmatter)) {
78
- return { ok: false, reason: 'no-data-loading-pattern' };
79
- }
80
-
81
- // Check idempotency — if the frontmatter already has the marker, skip.
82
- if (frontmatter.includes(ast.MARKER)) {
83
- return {
84
- ok: true,
85
- after: source,
86
- instrumented: [],
87
- skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
88
- changed: false,
89
- };
90
- }
91
-
92
- // Parse the frontmatter as a standalone JS/TS module.
93
- const tree = ast.parseSource(frontmatter);
94
-
95
- // Build track statements for all events.
96
- const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
97
-
98
- // Inject before last return or at end of program body.
99
- const body = tree.program;
100
- let lastReturnIdx = -1;
101
- for (let i = body.body.length - 1; i >= 0; i--) {
102
- if (ast.t.isReturnStatement(body.body[i])) {
103
- lastReturnIdx = i;
104
- break;
105
- }
106
- }
107
-
108
- // Add marker comment to first track statement
109
- if (stmts.length > 0) {
110
- // Tag the program itself with a comment (will appear in generated source)
111
- const markerComment = ast.t.addComment(
112
- body.body[0] || stmts[0],
113
- 'leading',
114
- ` @gurulu-instrumented`,
115
- true,
116
- );
117
- }
118
-
119
- if (lastReturnIdx >= 0) {
120
- body.body.splice(lastReturnIdx, 0, ...stmts);
121
- } else {
122
- // Append at end of frontmatter
123
- body.body.push(...stmts);
124
- }
125
-
126
- // Sprint D / D4 — alias-aware import.
127
- const fmSpecifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
128
- ast.ensureGuruluImport(tree, fmSpecifier);
129
- const newFrontmatter = ast.generateSource(tree, frontmatter);
130
-
131
- // Reconstruct the full .astro file
132
- const beforeFm = source.substring(0, fmMatch.index);
133
- const afterFm = source.substring(fmMatch.index + fmMatch[0].length);
134
- const after = `${beforeFm}---\n${newFrontmatter}\n---${afterFm}`;
135
-
136
- return {
137
- ok: true,
138
- after,
139
- instrumented: events.map((e) => e.name),
140
- skipped: [],
141
- changed: true,
142
- };
143
- }
144
-
145
- function astInstrumentFile(source, method, events, opts = {}) {
146
- const tree = ast.parseSource(source);
147
- const fns = ast.findExportedFunction(tree, method);
148
- if (fns.length === 0) return { ok: false, reason: `${method}-not-found` };
149
- const target = fns[0];
150
- if (ast.hasInstrumentedMarker(target.fn)) {
151
- return {
152
- ok: true,
153
- after: source,
154
- instrumented: [],
155
- skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
156
- changed: false,
157
- };
158
- }
159
- const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
160
- ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
161
- // Sprint D / D4 — alias-aware import.
162
- const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
163
- ast.ensureGuruluImport(tree, specifier);
164
- const after = ast.generateSource(tree, source);
165
- return {
166
- ok: true,
167
- after,
168
- instrumented: events.map((e) => e.name),
169
- skipped: [],
170
- changed: true,
171
- };
172
- }
173
-
174
- function instrumentEvents(ctx, events) {
175
- const helper = singleton.ensureSingletonHelper(ctx, 'astro');
176
- const changes = [...helper.changes];
177
- const notes = [...helper.notes];
178
- let eventsInstrumented = 0;
179
- let eventsSkipped = 0;
180
-
181
- if (helper.collision) {
182
- return {
183
- changes: [],
184
- notes,
185
- filesModified: 0,
186
- eventsInstrumented: 0,
187
- eventsSkipped: events ? events.length : 0,
188
- collision: true,
189
- };
190
- }
191
-
192
- const groups = new Map();
193
- for (const e of events || []) {
194
- const parsed = parseEventRoute(e && e.source && e.source.route);
195
- if (!parsed) {
196
- notes.push(`skip:${e && e.name}:no-source-route`);
197
- eventsSkipped++;
198
- continue;
199
- }
200
- const candidates = routeToCandidates(parsed.urlPath);
201
- const found = candidates.find((rel) => fs.existsSync(path.join(ctx.repoRoot, rel)));
202
- if (!found) {
203
- notes.push(`skip:${e.name}:route-file-not-found`);
204
- eventsSkipped++;
205
- continue;
206
- }
207
- const key = `${found}::${parsed.method}`;
208
- if (!groups.has(key)) groups.set(key, { relPath: found, method: parsed.method, events: [] });
209
- groups.get(key).events.push(e);
210
- }
211
-
212
- for (const group of groups.values()) {
213
- const abs = path.join(ctx.repoRoot, group.relPath);
214
- const before = fs.readFileSync(abs, 'utf8');
215
- // Sprint D / D4 — pass repoRoot + relPath to the import resolver.
216
- const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
217
- let res;
218
- try {
219
- const isAstroComponent = group.relPath.endsWith('.astro');
220
- res = isAstroComponent
221
- ? astInstrumentFrontmatter(before, group.events, fileOpts)
222
- : astInstrumentFile(before, group.method, group.events, fileOpts);
223
- } catch (err) {
224
- const msg = (err && err.message) || String(err);
225
- // eslint-disable-next-line no-console
226
- console.warn(`[auto-instrument] patch.fallback ${group.relPath}: ${msg}`);
227
- notes.push(`patch.fallback:${group.relPath}:${msg}`);
228
- continue;
229
- }
230
- if (!res.ok) {
231
- for (const e of group.events) {
232
- notes.push(`skip:${e.name}:${res.reason}`);
233
- eventsSkipped++;
234
- }
235
- continue;
236
- }
237
- for (const s of res.skipped || []) {
238
- notes.push(`skip:${s.event}:${s.reason}`);
239
- eventsSkipped++;
240
- }
241
- if (res.changed) {
242
- changes.push({
243
- relPath: group.relPath,
244
- before,
245
- after: res.after,
246
- reason: `auto-instrument-astro`,
247
- type: 'auto-instrument',
248
- });
249
- eventsInstrumented += (res.instrumented || []).length;
250
- }
251
- }
252
-
253
- const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
254
- return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
255
- }
256
-
257
- function ensureSingletonHelper(ctx) {
258
- return singleton.ensureSingletonHelper(ctx, 'astro');
259
- }
260
-
261
- module.exports = {
262
- name: NAME,
263
- supportedFrameworks: SUPPORTED,
264
- ensureSingletonHelper,
265
- instrumentEvents,
266
- _internals: {
267
- parseEventRoute,
268
- routeToCandidates,
269
- astInstrumentFile,
270
- astInstrumentFrontmatter,
271
- hasDataLoadingPattern,
272
- },
273
- };
@@ -1,383 +0,0 @@
1
- // scripts/patches/auto-instrument/express.cjs — Phase 20 W1 A1.
2
- //
3
- // AST-based auto-instrumentation for Express route files. We walk common
4
- // entry files + `routes/**` and search for `app.<method>('/path', handler)`
5
- // or `router.<method>('/path', handler)` call expressions. Once we locate
6
- // the matching call we inject `gurulu.track(...)` inside the handler body
7
- // (last argument, arrow or function expression).
8
- //
9
- // Regex fallback is retained for graceful degradation on parse failure.
10
-
11
- const fs = require('fs');
12
- const path = require('path');
13
-
14
- const ast = require('./ast-helper.cjs');
15
- const singleton = require('./singleton-helper.cjs');
16
-
17
- const NAME = 'auto-instrument-express';
18
- const SUPPORTED = ['express'];
19
- const MARKER = '// @gurulu-instrumented';
20
- const IMPORT_LINE_ESM = "import { gurulu } from '@/lib/gurulu';";
21
- const IMPORT_LINE_CJS = "const { gurulu } = require('./lib/gurulu');";
22
-
23
- const CANDIDATE_ENTRIES = [
24
- 'app.js',
25
- 'server.js',
26
- 'index.js',
27
- 'src/app.js',
28
- 'src/server.js',
29
- 'src/index.js',
30
- 'src/app.ts',
31
- 'src/server.ts',
32
- 'src/index.ts',
33
- ];
34
-
35
- function walkRoutes(repoRoot) {
36
- const results = [];
37
- const dirs = ['routes', 'src/routes', 'api', 'src/api'];
38
- for (const d of dirs) {
39
- const abs = path.join(repoRoot, d);
40
- if (!fs.existsSync(abs)) continue;
41
- for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
42
- if (entry.isFile() && /\.(js|ts|mjs|cjs)$/.test(entry.name)) {
43
- results.push(path.posix.join(d, entry.name));
44
- }
45
- }
46
- }
47
- return results;
48
- }
49
-
50
- function parseRoute(routeStr) {
51
- if (!routeStr || typeof routeStr !== 'string') return null;
52
- const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
53
- if (!m) return null;
54
- return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
55
- }
56
-
57
- // ---------------------------------------------------------------------------
58
- // AST path
59
- // ---------------------------------------------------------------------------
60
-
61
- /**
62
- * Find all `app.<method>('path', ..., handler)` or `router.<method>(...)`
63
- * call expressions matching the given method + urlPath. Returns an array of
64
- * `{ fn, body }` entries (the handler arrow/function bodies).
65
- */
66
- function findRouteHandlers(tree, method, urlPath) {
67
- const t = ast.t;
68
- const results = [];
69
- const lowerMethod = method.toLowerCase();
70
- ast.traverse(tree, {
71
- CallExpression(p) {
72
- const callee = p.node.callee;
73
- if (!t.isMemberExpression(callee)) return;
74
- if (!t.isIdentifier(callee.property) || callee.property.name !== lowerMethod) return;
75
- if (!t.isIdentifier(callee.object)) return;
76
- const obj = callee.object.name;
77
- if (obj !== 'app' && obj !== 'router') return;
78
- const args = p.node.arguments;
79
- if (args.length < 2) return;
80
- if (!t.isStringLiteral(args[0]) || args[0].value !== urlPath) return;
81
- // The final argument should be the handler function.
82
- const handler = args[args.length - 1];
83
- if (
84
- (t.isArrowFunctionExpression(handler) || t.isFunctionExpression(handler)) &&
85
- t.isBlockStatement(handler.body)
86
- ) {
87
- results.push({ fn: handler, body: handler.body });
88
- }
89
- },
90
- });
91
- return results;
92
- }
93
-
94
- function astInstrumentFile(source, method, urlPath, events, opts = {}) {
95
- const tree = ast.parseSource(source);
96
- const handlers = findRouteHandlers(tree, method, urlPath);
97
- if (handlers.length === 0) {
98
- return { ok: false, reason: 'handler-not-found' };
99
- }
100
- const target = handlers[0];
101
- if (ast.hasInstrumentedMarker(target.fn)) {
102
- return {
103
- ok: true,
104
- after: source,
105
- instrumented: [],
106
- skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
107
- changed: false,
108
- };
109
- }
110
- const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
111
- ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
112
- // Sprint D / D4 — alias-aware import (Express usually has no `@/*` alias).
113
- const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
114
- ast.ensureGuruluImport(tree, specifier);
115
- const after = ast.generateSource(tree, source);
116
- return {
117
- ok: true,
118
- after,
119
- instrumented: events.map((e) => e.name),
120
- skipped: [],
121
- changed: true,
122
- };
123
- }
124
-
125
- // ---------------------------------------------------------------------------
126
- // Regex fallback
127
- // ---------------------------------------------------------------------------
128
-
129
- function regexFindHandlerStart(source, method, urlPath) {
130
- const lower = method.toLowerCase();
131
- const escapedPath = urlPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
132
- const re = new RegExp(
133
- `(?:app|router)\\.${lower}\\s*\\(\\s*['"\`]${escapedPath}['"\`]\\s*,`,
134
- );
135
- const m = re.exec(source);
136
- if (!m) return null;
137
- let i = m.index + m[0].length;
138
- const tail = source.slice(i);
139
- const arrowIdx = tail.search(/=>\s*\{/);
140
- const funcIdx = tail.search(/function\s*[^(]*\([^)]*\)\s*\{/);
141
- let bodyOpen = -1;
142
- if (arrowIdx !== -1 && (funcIdx === -1 || arrowIdx < funcIdx)) {
143
- bodyOpen = i + tail.indexOf('{', arrowIdx);
144
- } else if (funcIdx !== -1) {
145
- bodyOpen = i + tail.indexOf('{', funcIdx);
146
- }
147
- if (bodyOpen === -1) return null;
148
- let depth = 0;
149
- for (let j = bodyOpen; j < source.length; j++) {
150
- const c = source[j];
151
- if (c === '{') depth++;
152
- else if (c === '}') {
153
- depth--;
154
- if (depth === 0) return { start: bodyOpen, end: j };
155
- }
156
- }
157
- return null;
158
- }
159
-
160
- function regexFindLastResponseCall(source, start, end) {
161
- const snippet = source.slice(start, end);
162
- const patterns = [
163
- /res\.status\s*\([^)]*\)\s*\.json\s*\(/g,
164
- /res\.status\s*\([^)]*\)\s*\.send\s*\(/g,
165
- /res\.json\s*\(/g,
166
- /res\.send\s*\(/g,
167
- /res\.sendStatus\s*\(/g,
168
- /res\.end\s*\(/g,
169
- ];
170
- let lastIdx = -1;
171
- for (const re of patterns) {
172
- let m;
173
- while ((m = re.exec(snippet)) !== null) {
174
- if (m.index > lastIdx) lastIdx = m.index;
175
- }
176
- }
177
- if (lastIdx === -1) return null;
178
- const absoluteIdx = start + lastIdx;
179
- let lineStart = absoluteIdx;
180
- while (lineStart > 0 && source[lineStart - 1] !== '\n') lineStart--;
181
- const indentMatch = source.slice(lineStart, absoluteIdx).match(/^(\s*)/);
182
- const indent = (indentMatch && indentMatch[1]) || ' ';
183
- return { insertAt: lineStart, indent };
184
- }
185
-
186
- function regexEnsureImport(source, opts = {}) {
187
- if (source.includes(IMPORT_LINE_ESM) || source.includes(IMPORT_LINE_CJS)) return source;
188
- // Sprint D / D4 — alias-aware specifier. ESM-only branch picks `@/lib/gurulu`
189
- // when tsconfig declares it, otherwise a relative import. The CJS branch
190
- // continues to use `./lib/gurulu` since CommonJS does not honor TS paths.
191
- const isCjs = /\brequire\s*\(/.test(source) && !/^import\s/m.test(source);
192
- let line;
193
- if (isCjs) {
194
- line = IMPORT_LINE_CJS;
195
- } else if (opts.repoRoot) {
196
- const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
197
- line = `import { gurulu } from '${specifier}';`;
198
- } else {
199
- line = IMPORT_LINE_ESM;
200
- }
201
- const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
202
- const requireRegex = /^(?:const\s[\s\S]*?require\([\s\S]*?\);\s*\n)+/m;
203
- const m = source.match(importRegex) || source.match(requireRegex);
204
- if (m) {
205
- const end = m.index + m[0].length;
206
- return source.slice(0, end) + line + '\n' + source.slice(end);
207
- }
208
- return line + '\n' + source;
209
- }
210
-
211
- function regexBuildTrackCall(eventName, indent) {
212
- const safeName = JSON.stringify(eventName);
213
- return `${indent}${MARKER} ${eventName}\n${indent}gurulu.track(${safeName}, {});\n`;
214
- }
215
-
216
- function regexInstrumentFile(before, method, urlPath, events, opts = {}) {
217
- const body = regexFindHandlerStart(before, method, urlPath);
218
- if (!body) return { ok: false, reason: 'handler-not-found' };
219
- const snippet = before.slice(body.start, body.end);
220
- const needed = [];
221
- const skipped = [];
222
- for (const e of events) {
223
- if (snippet.includes(`${MARKER} ${e.name}`)) {
224
- skipped.push({ event: e.name, reason: 'already-instrumented' });
225
- } else {
226
- needed.push(e);
227
- }
228
- }
229
- if (needed.length === 0) return { ok: true, after: before, instrumented: [], skipped, changed: false };
230
- const ret = regexFindLastResponseCall(before, body.start, body.end);
231
- if (!ret) return { ok: false, reason: 'no-response-found' };
232
- const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent)).join('');
233
- let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
234
- after = regexEnsureImport(after, opts);
235
- return {
236
- ok: true,
237
- after,
238
- instrumented: needed.map((e) => e.name),
239
- skipped,
240
- changed: true,
241
- };
242
- }
243
-
244
- // ---------------------------------------------------------------------------
245
- // Glue
246
- // ---------------------------------------------------------------------------
247
-
248
- function resolveRouteFile(ctx, method, urlPath) {
249
- const seen = new Set();
250
- const candidates = [
251
- ...CANDIDATE_ENTRIES,
252
- ...walkRoutes(ctx.repoRoot),
253
- ].filter((rel) => {
254
- if (seen.has(rel)) return false;
255
- seen.add(rel);
256
- return fs.existsSync(path.join(ctx.repoRoot, rel));
257
- });
258
- for (const rel of candidates) {
259
- const src = fs.readFileSync(path.join(ctx.repoRoot, rel), 'utf8');
260
- // Cheap pre-filter: must contain `.${method.toLowerCase()}(`.
261
- if (!src.includes(`.${method.toLowerCase()}(`)) continue;
262
- try {
263
- const tree = ast.parseSource(src);
264
- const handlers = findRouteHandlers(tree, method, urlPath);
265
- if (handlers.length > 0) return { relPath: rel };
266
- } catch (_) {
267
- // Regex check as last-ditch.
268
- if (regexFindHandlerStart(src, method, urlPath)) return { relPath: rel };
269
- }
270
- }
271
- return null;
272
- }
273
-
274
- function instrumentEvents(ctx, events) {
275
- const helper = singleton.ensureSingletonHelper(ctx, 'express');
276
- const changes = [...helper.changes];
277
- const notes = [...helper.notes];
278
- let eventsInstrumented = 0;
279
- let eventsSkipped = 0;
280
-
281
- if (helper.collision) {
282
- return {
283
- changes: [],
284
- notes,
285
- filesModified: 0,
286
- eventsInstrumented: 0,
287
- eventsSkipped: events ? events.length : 0,
288
- collision: true,
289
- };
290
- }
291
-
292
- const groups = new Map();
293
- for (const e of events || []) {
294
- const parsed = parseRoute(e && e.source && e.source.route);
295
- if (!parsed) {
296
- notes.push(`skip:${e && e.name}:no-source-route`);
297
- eventsSkipped++;
298
- continue;
299
- }
300
- const resolved = resolveRouteFile(ctx, parsed.method, parsed.urlPath);
301
- if (!resolved) {
302
- notes.push(`skip:${e.name}:route-not-found`);
303
- eventsSkipped++;
304
- continue;
305
- }
306
- const key = `${resolved.relPath}::${parsed.method}::${parsed.urlPath}`;
307
- if (!groups.has(key)) {
308
- groups.set(key, {
309
- relPath: resolved.relPath,
310
- method: parsed.method,
311
- urlPath: parsed.urlPath,
312
- events: [],
313
- });
314
- }
315
- groups.get(key).events.push(e);
316
- }
317
-
318
- for (const group of groups.values()) {
319
- const abs = path.join(ctx.repoRoot, group.relPath);
320
- const before = fs.readFileSync(abs, 'utf8');
321
- // Sprint D / D4 — thread repoRoot + relPath into the import resolver.
322
- const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
323
- let res;
324
- try {
325
- res = astInstrumentFile(before, group.method, group.urlPath, group.events, fileOpts);
326
- } catch (err) {
327
- const msg = (err && err.message) || String(err);
328
- // eslint-disable-next-line no-console
329
- console.warn(`[auto-instrument] patch.fallback ${group.relPath}: ${msg}`);
330
- notes.push(`patch.fallback:${group.relPath}:${msg}`);
331
- res = regexInstrumentFile(before, group.method, group.urlPath, group.events, fileOpts);
332
- }
333
- if (!res.ok) {
334
- for (const e of group.events) {
335
- notes.push(`skip:${e.name}:${res.reason || 'instrument-failed'}`);
336
- eventsSkipped++;
337
- }
338
- continue;
339
- }
340
- for (const s of res.skipped || []) {
341
- notes.push(`skip:${s.event}:${s.reason}`);
342
- eventsSkipped++;
343
- }
344
- if (!res.changed) continue;
345
- // Merge with earlier staged change to the same file (AST already takes
346
- // care of dedup-by-marker within a single call, so we just overwrite).
347
- const existing = changes.find((c) => c.relPath === group.relPath && c.type === 'auto-instrument');
348
- if (existing) {
349
- existing.after = res.after;
350
- } else {
351
- changes.push({
352
- relPath: group.relPath,
353
- before,
354
- after: res.after,
355
- reason: `auto-instrument-${group.method}`,
356
- type: 'auto-instrument',
357
- });
358
- }
359
- eventsInstrumented += (res.instrumented || []).length;
360
- }
361
-
362
- const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
363
- return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
364
- }
365
-
366
- function ensureSingletonHelper(ctx) {
367
- return singleton.ensureSingletonHelper(ctx, 'express');
368
- }
369
-
370
- module.exports = {
371
- name: NAME,
372
- supportedFrameworks: SUPPORTED,
373
- ensureSingletonHelper,
374
- instrumentEvents,
375
- _internals: {
376
- parseRoute,
377
- resolveRouteFile,
378
- astInstrumentFile,
379
- regexInstrumentFile,
380
- walkRoutes,
381
- findRouteHandlers,
382
- },
383
- };