@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,262 +0,0 @@
1
- // scripts/patches/auto-instrument/fastify.cjs — Phase 20 W1 A3.
2
- //
3
- // Fastify supports two idiomatic route registration shapes:
4
- //
5
- // fastify.get('/users', async (req, reply) => { ... });
6
- // fastify.route({ method: 'GET', url: '/users', handler: async (req, reply) => { ... } });
7
- //
8
- // We search the usual server entry files plus `routes/**` for a matching
9
- // registration, parse the AST, and inject `gurulu.track(...)` into the
10
- // handler body before the last return.
11
-
12
- const fs = require('fs');
13
- const path = require('path');
14
-
15
- const ast = require('./ast-helper.cjs');
16
- const singleton = require('./singleton-helper.cjs');
17
-
18
- const NAME = 'auto-instrument-fastify';
19
- const SUPPORTED = ['fastify'];
20
-
21
- const CANDIDATE_ENTRIES = [
22
- 'app.js',
23
- 'server.js',
24
- 'index.js',
25
- 'src/app.js',
26
- 'src/server.js',
27
- 'src/index.js',
28
- 'src/app.ts',
29
- 'src/server.ts',
30
- 'src/index.ts',
31
- ];
32
-
33
- function parseEventRoute(routeStr) {
34
- if (!routeStr || typeof routeStr !== 'string') return null;
35
- const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
36
- if (!m) return null;
37
- return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
38
- }
39
-
40
- function walkRoutes(repoRoot) {
41
- const results = [];
42
- const dirs = ['routes', 'src/routes', 'plugins', 'src/plugins'];
43
- for (const d of dirs) {
44
- const abs = path.join(repoRoot, d);
45
- if (!fs.existsSync(abs)) continue;
46
- for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
47
- if (entry.isFile() && /\.(js|ts|mjs|cjs)$/.test(entry.name)) {
48
- results.push(path.posix.join(d, entry.name));
49
- }
50
- }
51
- }
52
- return results;
53
- }
54
-
55
- function findFastifyHandlers(tree, method, urlPath) {
56
- const t = ast.t;
57
- const results = [];
58
- const lowerMethod = method.toLowerCase();
59
-
60
- ast.traverse(tree, {
61
- CallExpression(p) {
62
- const callee = p.node.callee;
63
- // Shape 1: fastify.get('/users', handler) / app.get(...) — identifier may
64
- // be any local name bound to the fastify instance.
65
- if (t.isMemberExpression(callee) && t.isIdentifier(callee.property)) {
66
- if (callee.property.name === lowerMethod) {
67
- const args = p.node.arguments;
68
- if (args.length >= 2 && t.isStringLiteral(args[0]) && args[0].value === urlPath) {
69
- const handler = args[args.length - 1];
70
- if (
71
- (t.isArrowFunctionExpression(handler) || t.isFunctionExpression(handler)) &&
72
- t.isBlockStatement(handler.body)
73
- ) {
74
- results.push({ fn: handler, body: handler.body });
75
- }
76
- }
77
- }
78
- // Shape 2: fastify.route({ method, url, handler })
79
- if (callee.property.name === 'route') {
80
- const arg0 = p.node.arguments[0];
81
- if (t.isObjectExpression(arg0)) {
82
- let m, u, handlerNode;
83
- for (const prop of arg0.properties) {
84
- if (!t.isObjectProperty(prop)) continue;
85
- const key = t.isIdentifier(prop.key) ? prop.key.name : (t.isStringLiteral(prop.key) ? prop.key.value : null);
86
- if (!key) continue;
87
- if (key === 'method' && t.isStringLiteral(prop.value)) m = prop.value.value.toUpperCase();
88
- else if (key === 'url' && t.isStringLiteral(prop.value)) u = prop.value.value;
89
- else if (key === 'handler') handlerNode = prop.value;
90
- }
91
- if (m === method && u === urlPath && handlerNode) {
92
- if (
93
- (t.isArrowFunctionExpression(handlerNode) || t.isFunctionExpression(handlerNode)) &&
94
- t.isBlockStatement(handlerNode.body)
95
- ) {
96
- results.push({ fn: handlerNode, body: handlerNode.body });
97
- }
98
- }
99
- }
100
- }
101
- }
102
- },
103
- });
104
- return results;
105
- }
106
-
107
- function astInstrumentFile(source, method, urlPath, events, opts = {}) {
108
- const tree = ast.parseSource(source);
109
- const handlers = findFastifyHandlers(tree, method, urlPath);
110
- if (handlers.length === 0) return { ok: false, reason: 'handler-not-found' };
111
- const target = handlers[0];
112
- if (ast.hasInstrumentedMarker(target.fn)) {
113
- return {
114
- ok: true,
115
- after: source,
116
- instrumented: [],
117
- skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
118
- changed: false,
119
- };
120
- }
121
- const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
122
- ast.injectTrackBeforeLastReturn(target.fn, target.body, stmts);
123
- // Sprint D / D4 — alias-aware import.
124
- const specifier = ast.resolveGuruluImportSpecifier(opts.repoRoot, opts.relPath);
125
- ast.ensureGuruluImport(tree, specifier);
126
- const after = ast.generateSource(tree, source);
127
- return {
128
- ok: true,
129
- after,
130
- instrumented: events.map((e) => e.name),
131
- skipped: [],
132
- changed: true,
133
- };
134
- }
135
-
136
- function resolveRouteFile(ctx, method, urlPath) {
137
- const seen = new Set();
138
- const candidates = [
139
- ...CANDIDATE_ENTRIES,
140
- ...walkRoutes(ctx.repoRoot),
141
- ].filter((rel) => {
142
- if (seen.has(rel)) return false;
143
- seen.add(rel);
144
- return fs.existsSync(path.join(ctx.repoRoot, rel));
145
- });
146
- for (const rel of candidates) {
147
- const src = fs.readFileSync(path.join(ctx.repoRoot, rel), 'utf8');
148
- if (!src.includes(urlPath)) continue;
149
- try {
150
- const tree = ast.parseSource(src);
151
- const h = findFastifyHandlers(tree, method, urlPath);
152
- if (h.length > 0) return rel;
153
- } catch (_) {
154
- // ignore
155
- }
156
- }
157
- return null;
158
- }
159
-
160
- function instrumentEvents(ctx, events) {
161
- const helper = singleton.ensureSingletonHelper(ctx, 'fastify');
162
- const changes = [...helper.changes];
163
- const notes = [...helper.notes];
164
- let eventsInstrumented = 0;
165
- let eventsSkipped = 0;
166
-
167
- if (helper.collision) {
168
- return {
169
- changes: [],
170
- notes,
171
- filesModified: 0,
172
- eventsInstrumented: 0,
173
- eventsSkipped: events ? events.length : 0,
174
- collision: true,
175
- };
176
- }
177
-
178
- const groups = new Map();
179
- for (const e of events || []) {
180
- const parsed = parseEventRoute(e && e.source && e.source.route);
181
- if (!parsed) {
182
- notes.push(`skip:${e && e.name}:no-source-route`);
183
- eventsSkipped++;
184
- continue;
185
- }
186
- const rel = resolveRouteFile(ctx, parsed.method, parsed.urlPath);
187
- if (!rel) {
188
- notes.push(`skip:${e.name}:route-not-found`);
189
- eventsSkipped++;
190
- continue;
191
- }
192
- const key = `${rel}::${parsed.method}::${parsed.urlPath}`;
193
- if (!groups.has(key)) {
194
- groups.set(key, { relPath: rel, method: parsed.method, urlPath: parsed.urlPath, events: [] });
195
- }
196
- groups.get(key).events.push(e);
197
- }
198
-
199
- for (const group of groups.values()) {
200
- const abs = path.join(ctx.repoRoot, group.relPath);
201
- const before = fs.readFileSync(abs, 'utf8');
202
- // Sprint D / D4 — pass repoRoot + relPath to the import resolver.
203
- const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath: group.relPath };
204
- let res;
205
- try {
206
- res = astInstrumentFile(before, group.method, group.urlPath, group.events, fileOpts);
207
- } catch (err) {
208
- const msg = (err && err.message) || String(err);
209
- // eslint-disable-next-line no-console
210
- console.warn(`[auto-instrument] patch.fallback ${group.relPath}: ${msg}`);
211
- notes.push(`patch.fallback:${group.relPath}:${msg}`);
212
- continue;
213
- }
214
- if (!res.ok) {
215
- for (const e of group.events) {
216
- notes.push(`skip:${e.name}:${res.reason}`);
217
- eventsSkipped++;
218
- }
219
- continue;
220
- }
221
- for (const s of res.skipped || []) {
222
- notes.push(`skip:${s.event}:${s.reason}`);
223
- eventsSkipped++;
224
- }
225
- if (res.changed) {
226
- const existing = changes.find((c) => c.relPath === group.relPath && c.type === 'auto-instrument');
227
- if (existing) {
228
- existing.after = res.after;
229
- } else {
230
- changes.push({
231
- relPath: group.relPath,
232
- before,
233
- after: res.after,
234
- reason: `auto-instrument-fastify`,
235
- type: 'auto-instrument',
236
- });
237
- }
238
- eventsInstrumented += (res.instrumented || []).length;
239
- }
240
- }
241
-
242
- const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
243
- return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
244
- }
245
-
246
- function ensureSingletonHelper(ctx) {
247
- return singleton.ensureSingletonHelper(ctx, 'fastify');
248
- }
249
-
250
- module.exports = {
251
- name: NAME,
252
- supportedFrameworks: SUPPORTED,
253
- ensureSingletonHelper,
254
- instrumentEvents,
255
- _internals: {
256
- parseEventRoute,
257
- walkRoutes,
258
- findFastifyHandlers,
259
- astInstrumentFile,
260
- resolveRouteFile,
261
- },
262
- };
@@ -1,392 +0,0 @@
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
- };