@gurulu/cli 0.4.7 → 1.0.0

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 (182) 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 +25410 -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 +25 -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 +24985 -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/package.json +40 -20
  28. package/bin/gurulu.js +0 -2
  29. package/dist/api-client.d.ts +0 -33
  30. package/dist/api-client.js +0 -175
  31. package/dist/commands/add-server.d.ts +0 -9
  32. package/dist/commands/add-server.js +0 -162
  33. package/dist/commands/alerts.d.ts +0 -27
  34. package/dist/commands/alerts.js +0 -309
  35. package/dist/commands/api-keys.d.ts +0 -20
  36. package/dist/commands/api-keys.js +0 -130
  37. package/dist/commands/attribution.d.ts +0 -22
  38. package/dist/commands/attribution.js +0 -111
  39. package/dist/commands/audiences.d.ts +0 -23
  40. package/dist/commands/audiences.js +0 -243
  41. package/dist/commands/audit.d.ts +0 -20
  42. package/dist/commands/audit.js +0 -130
  43. package/dist/commands/auth.js +0 -249
  44. package/dist/commands/chat.d.ts +0 -19
  45. package/dist/commands/chat.js +0 -118
  46. package/dist/commands/config.d.ts +0 -10
  47. package/dist/commands/config.js +0 -92
  48. package/dist/commands/consent.d.ts +0 -27
  49. package/dist/commands/consent.js +0 -233
  50. package/dist/commands/conversion-paths.d.ts +0 -19
  51. package/dist/commands/conversion-paths.js +0 -55
  52. package/dist/commands/db.d.ts +0 -25
  53. package/dist/commands/db.js +0 -330
  54. package/dist/commands/destinations.d.ts +0 -20
  55. package/dist/commands/destinations.js +0 -191
  56. package/dist/commands/doctor.js +0 -360
  57. package/dist/commands/errors.d.ts +0 -27
  58. package/dist/commands/errors.js +0 -121
  59. package/dist/commands/events.d.ts +0 -33
  60. package/dist/commands/events.js +0 -371
  61. package/dist/commands/experiments.d.ts +0 -22
  62. package/dist/commands/experiments.js +0 -264
  63. package/dist/commands/funnels.d.ts +0 -17
  64. package/dist/commands/funnels.js +0 -203
  65. package/dist/commands/goals.d.ts +0 -18
  66. package/dist/commands/goals.js +0 -214
  67. package/dist/commands/heatmap.d.ts +0 -27
  68. package/dist/commands/heatmap.js +0 -112
  69. package/dist/commands/identity.d.ts +0 -29
  70. package/dist/commands/identity.js +0 -328
  71. package/dist/commands/init.js +0 -215
  72. package/dist/commands/insights.d.ts +0 -10
  73. package/dist/commands/insights.js +0 -77
  74. package/dist/commands/install.d.ts +0 -259
  75. package/dist/commands/install.js +0 -1590
  76. package/dist/commands/login.d.ts +0 -20
  77. package/dist/commands/login.js +0 -170
  78. package/dist/commands/logout.d.ts +0 -10
  79. package/dist/commands/logout.js +0 -41
  80. package/dist/commands/playground.d.ts +0 -11
  81. package/dist/commands/playground.js +0 -47
  82. package/dist/commands/releases.d.ts +0 -17
  83. package/dist/commands/releases.js +0 -54
  84. package/dist/commands/replay.d.ts +0 -18
  85. package/dist/commands/replay.js +0 -64
  86. package/dist/commands/secrets.d.ts +0 -19
  87. package/dist/commands/secrets.js +0 -145
  88. package/dist/commands/setup.d.ts +0 -21
  89. package/dist/commands/setup.js +0 -67
  90. package/dist/commands/sites.d.ts +0 -18
  91. package/dist/commands/sites.js +0 -139
  92. package/dist/commands/skad.d.ts +0 -18
  93. package/dist/commands/skad.js +0 -53
  94. package/dist/commands/sourcemap.d.ts +0 -33
  95. package/dist/commands/sourcemap.js +0 -204
  96. package/dist/commands/status.d.ts +0 -7
  97. package/dist/commands/status.js +0 -136
  98. package/dist/commands/upgrade.d.ts +0 -21
  99. package/dist/commands/upgrade.js +0 -183
  100. package/dist/commands/warehouse.d.ts +0 -20
  101. package/dist/commands/warehouse.js +0 -65
  102. package/dist/commands/warehouses.d.ts +0 -17
  103. package/dist/commands/warehouses.js +0 -182
  104. package/dist/commands/watch.d.ts +0 -45
  105. package/dist/commands/watch.js +0 -258
  106. package/dist/commands/whoami.d.ts +0 -9
  107. package/dist/commands/whoami.js +0 -50
  108. package/dist/config.d.ts +0 -75
  109. package/dist/config.js +0 -329
  110. package/dist/frameworks/detect.d.ts +0 -8
  111. package/dist/frameworks/detect.js +0 -458
  112. package/dist/install-intent-proposal.d.ts +0 -99
  113. package/dist/install-intent-proposal.js +0 -202
  114. package/dist/utils/api.d.ts +0 -20
  115. package/dist/utils/api.js +0 -47
  116. package/dist/utils/config.d.ts +0 -13
  117. package/dist/utils/config.js +0 -30
  118. package/dist/utils/confirm.d.ts +0 -17
  119. package/dist/utils/confirm.js +0 -40
  120. package/dist/utils/dry-run.d.ts +0 -20
  121. package/dist/utils/dry-run.js +0 -67
  122. package/dist/utils/from-file.d.ts +0 -9
  123. package/dist/utils/from-file.js +0 -72
  124. package/dist/utils/redact.d.ts +0 -14
  125. package/dist/utils/redact.js +0 -48
  126. package/dist/utils/ui.d.ts +0 -14
  127. package/dist/utils/ui.js +0 -59
  128. package/scripts/.gitkeep +0 -0
  129. package/scripts/README-gurulu-agentic-install.md +0 -114
  130. package/scripts/README-gurulu-scan.md +0 -98
  131. package/scripts/audit-cli-scopes.mjs +0 -204
  132. package/scripts/backfill-tenant-id.mjs +0 -172
  133. package/scripts/backfill-tenant-links.ts +0 -252
  134. package/scripts/backup-clickhouse.sh +0 -27
  135. package/scripts/backup-postgres.sh +0 -19
  136. package/scripts/bootstrap-runtime-schema.mjs +0 -87
  137. package/scripts/bootstrap-stripe.mjs +0 -158
  138. package/scripts/gurulu-agentic-install.lib.cjs +0 -762
  139. package/scripts/gurulu-agentic-install.mjs +0 -623
  140. package/scripts/gurulu-scan.lib.cjs +0 -1509
  141. package/scripts/gurulu-scan.mjs +0 -91
  142. package/scripts/gurulu-verify-install.lib.cjs +0 -334
  143. package/scripts/gurulu-verify-install.mjs +0 -59
  144. package/scripts/init-ssl.sh +0 -26
  145. package/scripts/migrate-flow-graph-enums.sh +0 -86
  146. package/scripts/monitor-disk.sh +0 -24
  147. package/scripts/patches/astro.patch.cjs +0 -74
  148. package/scripts/patches/auto-instrument/ast-helper.cjs +0 -480
  149. package/scripts/patches/auto-instrument/astro.cjs +0 -273
  150. package/scripts/patches/auto-instrument/express.cjs +0 -383
  151. package/scripts/patches/auto-instrument/fastify.cjs +0 -262
  152. package/scripts/patches/auto-instrument/hono.cjs +0 -392
  153. package/scripts/patches/auto-instrument/index.cjs +0 -80
  154. package/scripts/patches/auto-instrument/nestjs.cjs +0 -286
  155. package/scripts/patches/auto-instrument/nextjs-app-router.cjs +0 -345
  156. package/scripts/patches/auto-instrument/nextjs-pages.cjs +0 -361
  157. package/scripts/patches/auto-instrument/remix.cjs +0 -168
  158. package/scripts/patches/auto-instrument/sdk-helper-map.cjs +0 -241
  159. package/scripts/patches/auto-instrument/singleton-helper.cjs +0 -193
  160. package/scripts/patches/auto-instrument/sveltekit.cjs +0 -161
  161. package/scripts/patches/auto-instrument/vite-react.cjs +0 -37
  162. package/scripts/patches/auto-instrument/vue.cjs +0 -196
  163. package/scripts/patches/express.patch.cjs +0 -99
  164. package/scripts/patches/fastify.patch.cjs +0 -108
  165. package/scripts/patches/index.cjs +0 -300
  166. package/scripts/patches/nestjs.patch.cjs +0 -112
  167. package/scripts/patches/nextjs-app-router.patch.cjs +0 -97
  168. package/scripts/patches/nextjs-pages.patch.cjs +0 -97
  169. package/scripts/patches/remix.patch.cjs +0 -75
  170. package/scripts/patches/sveltekit.patch.cjs +0 -72
  171. package/scripts/patches/vite-react.patch.cjs +0 -73
  172. package/scripts/patches/vue.patch.cjs +0 -82
  173. package/scripts/renew-ssl.sh +0 -14
  174. package/scripts/resolve-migration.sh +0 -23
  175. package/scripts/seed-cli-dev-keys.mjs +0 -130
  176. package/scripts/seed-test-data.mjs +0 -391
  177. package/scripts/spike-browserless.ts +0 -65
  178. package/scripts/tenant-pivot-consistency-check.mjs +0 -205
  179. package/scripts/tenant-pivot-phase-3-cleanup.lib.cjs +0 -258
  180. package/scripts/tenant-pivot-phase-3-cleanup.mjs +0 -98
  181. package/scripts/test-identity-resolution.ts +0 -804
  182. package/scripts/validate-gurulu-schemas.mjs +0 -79
@@ -1,345 +0,0 @@
1
- // scripts/patches/auto-instrument/nextjs-app-router.cjs — Phase 20 W1 A1.
2
- //
3
- // AST-based auto-instrumentation for Next.js App Router route files. Each
4
- // `ProposedEvent` whose `source.route` looks like "POST /api/foo" is mapped
5
- // to its `app/api/foo/route.ts` file, parsed with Babel, and the matching
6
- // HTTP method export gets a `gurulu.track('eventName', {})` call injected
7
- // before its last top-level `return`.
8
- //
9
- // Idempotency is enforced by tagging each instrumented function with a
10
- // leading `@gurulu-instrumented` comment. Running the patcher twice is a
11
- // no-op.
12
- //
13
- // If Babel fails to parse the file (exotic TS syntax not yet supported, or
14
- // a malformed source), we fall back to the original regex-based pathway and
15
- // emit a `patch.fallback` note so operators can investigate. The regex
16
- // implementation is kept inline at the bottom of this file for that reason.
17
-
18
- const fs = require('fs');
19
- const path = require('path');
20
-
21
- const ast = require('./ast-helper.cjs');
22
- const singleton = require('./singleton-helper.cjs');
23
-
24
- const NAME = 'auto-instrument-nextjs-app-router';
25
- const SUPPORTED = ['nextjs-app-router', 'nextjs-app', 'nextjs'];
26
- const MARKER = '// @gurulu-instrumented';
27
- const IMPORT_LINE = "import { gurulu } from '@/lib/gurulu';";
28
- const METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
29
-
30
- function resolveRouteFileCandidates(routeStr) {
31
- if (!routeStr || typeof routeStr !== 'string') return null;
32
- const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
33
- if (!m) return null;
34
- const method = m[1].toUpperCase();
35
- const urlPath = m[2].replace(/\/+$/, '').split('?')[0];
36
- const segments = urlPath.split('/').filter(Boolean);
37
- const relA = path.posix.join('src', 'app', ...segments, 'route.ts');
38
- const relB = path.posix.join('app', ...segments, 'route.ts');
39
- const relAx = path.posix.join('src', 'app', ...segments, 'route.tsx');
40
- const relBx = path.posix.join('app', ...segments, 'route.tsx');
41
- return { method, candidates: [relA, relB, relAx, relBx] };
42
- }
43
-
44
- // ---------------------------------------------------------------------------
45
- // AST path
46
- // ---------------------------------------------------------------------------
47
-
48
- /**
49
- * Instrument a single file with a set of events. `events` is expected to all
50
- * target the same HTTP method export. Returns a unified result with the
51
- * serialized `after` source and the list of event names that were actually
52
- * instrumented (vs. already-instrumented skipped).
53
- */
54
- function astInstrumentFile(source, method, events, opts = {}) {
55
- const tree = ast.parseSource(source);
56
- const fns = ast.findExportedFunction(tree, method);
57
- if (fns.length === 0) {
58
- return { ok: false, reason: `method-${method}-not-found` };
59
- }
60
- // Use the first matching function — multiple same-name exports are a
61
- // user error, not something we try to be clever about.
62
- const target = fns[0];
63
- if (ast.hasInstrumentedMarker(target.fn)) {
64
- return {
65
- ok: true,
66
- after: source,
67
- instrumented: [],
68
- skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
69
- changed: false,
70
- };
71
- }
72
- const trackStmts = events.map((e) =>
73
- ast.buildTrackStatement(e.name, e.extractedProperties || e.autoProperties),
74
- );
75
- const injected = ast.injectTrackBeforeLastReturn(target.fn, target.body, trackStmts);
76
- if (!injected) {
77
- return { ok: false, reason: 'inject-failed' };
78
- }
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);
83
- const after = ast.generateSource(tree, source);
84
- return {
85
- ok: true,
86
- after,
87
- instrumented: events.map((e) => e.name),
88
- skipped: [],
89
- changed: true,
90
- };
91
- }
92
-
93
- // ---------------------------------------------------------------------------
94
- // Regex fallback (legacy Phase 18.7 pathway) — unchanged behaviour, kept in
95
- // scope for graceful degradation.
96
- // ---------------------------------------------------------------------------
97
-
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
- }
112
- const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
113
- const m = source.match(importRegex);
114
- if (m) {
115
- const end = m.index + m[0].length;
116
- return { source: source.slice(0, end) + importLine + '\n' + source.slice(end), added: true };
117
- }
118
- return { source: importLine + '\n' + source, added: true };
119
- }
120
-
121
- function regexFindMethodBody(source, method) {
122
- const re = new RegExp(
123
- `export\\s+async\\s+function\\s+${method}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`,
124
- 'm',
125
- );
126
- const m = re.exec(source);
127
- if (!m) return null;
128
- const openIdx = m.index + m[0].length - 1;
129
- let depth = 0;
130
- for (let i = openIdx; i < source.length; i++) {
131
- const c = source[i];
132
- if (c === '{') depth++;
133
- else if (c === '}') {
134
- depth--;
135
- if (depth === 0) return { start: openIdx, end: i };
136
- }
137
- }
138
- return null;
139
- }
140
-
141
- function regexFindLastReturnInBody(source, start, end) {
142
- const snippet = source.slice(start, end);
143
- const patterns = [
144
- /return\s+NextResponse\.json\s*\(/g,
145
- /return\s+Response\.json\s*\(/g,
146
- /return\s+new\s+Response\s*\(/g,
147
- /return\s+NextResponse\s*\./g,
148
- ];
149
- let lastIdx = -1;
150
- for (const re of patterns) {
151
- let m;
152
- while ((m = re.exec(snippet)) !== null) {
153
- if (m.index > lastIdx) lastIdx = m.index;
154
- }
155
- }
156
- if (lastIdx === -1) return null;
157
- const absoluteReturnIdx = start + lastIdx;
158
- let lineStart = absoluteReturnIdx;
159
- while (lineStart > 0 && source[lineStart - 1] !== '\n') lineStart--;
160
- const indentMatch = source.slice(lineStart, absoluteReturnIdx).match(/^(\s*)/);
161
- const indent = (indentMatch && indentMatch[1]) || ' ';
162
- return { insertAt: lineStart, indent };
163
- }
164
-
165
- function regexBuildTrackCall(eventName, indent, extractedProperties) {
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
- }
176
- return (
177
- `${indent}${MARKER} ${eventName}\n` +
178
- `${indent}gurulu.track(${safeName}, ${propsStr});\n`
179
- );
180
- }
181
-
182
- function regexInstrumentFile(before, method, events, opts = {}) {
183
- const body = regexFindMethodBody(before, method);
184
- if (!body) {
185
- return { ok: false, reason: `method-${method}-not-found` };
186
- }
187
- const bodySnippet = before.slice(body.start, body.end);
188
- const needed = [];
189
- const skipped = [];
190
- for (const e of events) {
191
- if (bodySnippet.includes(`${MARKER} ${e.name}`)) {
192
- skipped.push({ event: e.name, reason: 'already-instrumented' });
193
- } else {
194
- needed.push(e);
195
- }
196
- }
197
- if (needed.length === 0) return { ok: true, after: before, instrumented: [], skipped, changed: false };
198
- const ret = regexFindLastReturnInBody(before, body.start, body.end);
199
- if (!ret) return { ok: false, reason: 'no-return-found' };
200
- const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent, e.extractedProperties)).join('');
201
- let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
202
- after = regexEnsureImport(after, opts).source;
203
- return {
204
- ok: true,
205
- after,
206
- instrumented: needed.map((e) => e.name),
207
- skipped,
208
- changed: true,
209
- };
210
- }
211
-
212
- // ---------------------------------------------------------------------------
213
- // Dispatcher plumbing
214
- // ---------------------------------------------------------------------------
215
-
216
- function instrumentRouteFile(ctx, relPath, method, events) {
217
- const abs = path.join(ctx.repoRoot, relPath);
218
- if (!fs.existsSync(abs)) {
219
- return { change: null, skipped: events.map((e) => ({ event: e.name, reason: 'route-file-missing' })), notes: [] };
220
- }
221
- const before = fs.readFileSync(abs, 'utf8');
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 };
226
- let res;
227
- try {
228
- res = astInstrumentFile(before, method, events, { ...(ctx || {}), ...fileOpts });
229
- } catch (err) {
230
- const msg = (err && err.message) || String(err);
231
- // eslint-disable-next-line no-console
232
- console.warn(`[auto-instrument] patch.fallback ${relPath}: ${msg}`);
233
- notes.push(`patch.fallback:${relPath}:${msg}`);
234
- res = regexInstrumentFile(before, method, events, fileOpts);
235
- }
236
- if (!res.ok) {
237
- return {
238
- change: null,
239
- skipped: events.map((e) => ({ event: e.name, reason: res.reason || 'instrument-failed' })),
240
- notes,
241
- };
242
- }
243
- if (!res.changed) {
244
- return { change: null, skipped: res.skipped, notes };
245
- }
246
- return {
247
- change: {
248
- relPath,
249
- before,
250
- after: res.after,
251
- reason: `auto-instrument-${method}`,
252
- type: 'auto-instrument',
253
- },
254
- skipped: res.skipped,
255
- instrumented: res.instrumented,
256
- notes,
257
- };
258
- }
259
-
260
- function groupEventsByRoute(ctx, events) {
261
- const groups = new Map();
262
- const unresolved = [];
263
- for (const e of events || []) {
264
- const routeStr = (e && e.source && e.source.route) || null;
265
- if (!routeStr) {
266
- unresolved.push({ event: e && e.name, reason: 'no-source-route' });
267
- continue;
268
- }
269
- const parsed = resolveRouteFileCandidates(routeStr);
270
- if (!parsed) {
271
- unresolved.push({ event: e.name, reason: `unparseable-route:${routeStr}` });
272
- continue;
273
- }
274
- const found = parsed.candidates.find((rel) =>
275
- fs.existsSync(path.join(ctx.repoRoot, rel)),
276
- );
277
- if (!found) {
278
- unresolved.push({ event: e.name, reason: 'route-file-not-found' });
279
- continue;
280
- }
281
- const key = `${found}::${parsed.method}`;
282
- if (!groups.has(key)) groups.set(key, { relPath: found, method: parsed.method, events: [] });
283
- groups.get(key).events.push(e);
284
- }
285
- return { groups: Array.from(groups.values()), unresolved };
286
- }
287
-
288
- function instrumentEvents(ctx, events) {
289
- const helper = singleton.ensureSingletonHelper(ctx, 'nextjs-app-router');
290
- const changes = [...helper.changes];
291
- const notes = [...helper.notes];
292
- let eventsInstrumented = 0;
293
- let eventsSkipped = 0;
294
-
295
- if (helper.collision) {
296
- return {
297
- changes: [],
298
- notes,
299
- filesModified: 0,
300
- eventsInstrumented: 0,
301
- eventsSkipped: events ? events.length : 0,
302
- collision: true,
303
- };
304
- }
305
-
306
- const { groups, unresolved } = groupEventsByRoute(ctx, events || []);
307
- for (const u of unresolved) {
308
- notes.push(`skip:${u.event || '(unknown)'}:${u.reason}`);
309
- eventsSkipped++;
310
- }
311
- for (const group of groups) {
312
- const res = instrumentRouteFile(ctx, group.relPath, group.method, group.events);
313
- if (res.notes && res.notes.length) notes.push(...res.notes);
314
- if (res.change) {
315
- changes.push(res.change);
316
- eventsInstrumented += (res.instrumented || []).length;
317
- }
318
- for (const s of res.skipped || []) {
319
- notes.push(`skip:${s.event}:${s.reason}`);
320
- eventsSkipped++;
321
- }
322
- }
323
-
324
- const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
325
- return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
326
- }
327
-
328
- function ensureSingletonHelper(ctx) {
329
- return singleton.ensureSingletonHelper(ctx, 'nextjs-app-router');
330
- }
331
-
332
- module.exports = {
333
- name: NAME,
334
- supportedFrameworks: SUPPORTED,
335
- ensureSingletonHelper,
336
- instrumentEvents,
337
- _internals: {
338
- resolveRouteFileCandidates,
339
- astInstrumentFile,
340
- regexInstrumentFile,
341
- groupEventsByRoute,
342
- instrumentRouteFile,
343
- METHODS,
344
- },
345
- };
@@ -1,361 +0,0 @@
1
- // scripts/patches/auto-instrument/nextjs-pages.cjs — Phase 20 W1 A1.
2
- //
3
- // AST-based auto-instrumentation for Next.js Pages Router handlers. The
4
- // default export is the handler. We parse with Babel, find the exported
5
- // handler (default export function or arrow), locate a method branch if the
6
- // handler switches on `req.method`, and inject `gurulu.track(...)` before
7
- // the final `return` inside that branch (or the handler body when no branch
8
- // exists).
9
- //
10
- // Regex fallback is preserved for malformed sources.
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-nextjs-pages';
19
- const SUPPORTED = ['nextjs-pages'];
20
- const MARKER = '// @gurulu-instrumented';
21
- const IMPORT_LINE = "import { gurulu } from '@/lib/gurulu';";
22
-
23
- function resolveRouteFileCandidates(routeStr) {
24
- if (!routeStr || typeof routeStr !== 'string') return null;
25
- const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
26
- if (!m) return null;
27
- const method = m[1].toUpperCase();
28
- const urlPath = m[2].replace(/^\//, '').replace(/\/+$/, '');
29
- const exts = ['ts', 'tsx', 'js', 'jsx'];
30
- const prefixes = ['pages', 'src/pages'];
31
- const candidates = [];
32
- for (const p of prefixes) {
33
- for (const ext of exts) {
34
- candidates.push(path.posix.join(p, `${urlPath}.${ext}`));
35
- candidates.push(path.posix.join(p, urlPath, `index.${ext}`));
36
- }
37
- }
38
- return { method, candidates };
39
- }
40
-
41
- // ---------------------------------------------------------------------------
42
- // AST path
43
- // ---------------------------------------------------------------------------
44
-
45
- /**
46
- * Given a handler body and a method string, return the BlockStatement of
47
- * `if (req.method === 'POST') { ... }` or null if no method branch is found.
48
- */
49
- function findMethodBranchBody(handlerBody, method) {
50
- if (!handlerBody || !Array.isArray(handlerBody.body)) return null;
51
- const t = ast.t;
52
- for (const stmt of handlerBody.body) {
53
- if (!t.isIfStatement(stmt)) continue;
54
- if (!matchesMethodTest(stmt.test, method)) continue;
55
- if (t.isBlockStatement(stmt.consequent)) return stmt.consequent;
56
- }
57
- // Recurse into else-if chains.
58
- for (const stmt of handlerBody.body) {
59
- if (!t.isIfStatement(stmt)) continue;
60
- let cursor = stmt.alternate;
61
- while (cursor) {
62
- if (t.isIfStatement(cursor)) {
63
- if (matchesMethodTest(cursor.test, method) && t.isBlockStatement(cursor.consequent)) {
64
- return cursor.consequent;
65
- }
66
- cursor = cursor.alternate;
67
- } else {
68
- break;
69
- }
70
- }
71
- }
72
- return null;
73
- }
74
-
75
- function matchesMethodTest(node, method) {
76
- const t = ast.t;
77
- if (!node) return false;
78
- if (t.isBinaryExpression(node) && (node.operator === '===' || node.operator === '==')) {
79
- const isMethod = (n) =>
80
- t.isMemberExpression(n) &&
81
- t.isIdentifier(n.object) &&
82
- n.object.name === 'req' &&
83
- t.isIdentifier(n.property) &&
84
- n.property.name === 'method';
85
- const isMethodLiteral = (n) => t.isStringLiteral(n) && n.value.toUpperCase() === method;
86
- if (isMethod(node.left) && isMethodLiteral(node.right)) return true;
87
- if (isMethod(node.right) && isMethodLiteral(node.left)) return true;
88
- }
89
- return false;
90
- }
91
-
92
- function astInstrumentFile(source, method, events, opts = {}) {
93
- const tree = ast.parseSource(source);
94
- const fns = ast.findExportedFunction(tree, 'default', { defaultExport: true });
95
- if (fns.length === 0) {
96
- return { ok: false, reason: 'handler-not-found' };
97
- }
98
- const target = fns[0];
99
- if (ast.hasInstrumentedMarker(target.fn)) {
100
- return {
101
- ok: true,
102
- after: source,
103
- instrumented: [],
104
- skipped: events.map((e) => ({ event: e.name, reason: 'already-instrumented' })),
105
- changed: false,
106
- };
107
- }
108
- const branch = findMethodBranchBody(target.body, method);
109
- const injectBody = branch || target.body;
110
- const stmts = events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
111
- ast.injectTrackBeforeLastReturn(target.fn, injectBody, stmts);
112
- // Sprint D / D4 — alias-aware import.
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 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
- }
140
- const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
141
- const m = source.match(importRegex);
142
- if (m) {
143
- const end = m.index + m[0].length;
144
- return source.slice(0, end) + importLine + '\n' + source.slice(end);
145
- }
146
- return importLine + '\n' + source;
147
- }
148
-
149
- function regexFindHandlerBody(source) {
150
- const patterns = [
151
- /export\s+default\s+async\s+function\s+\w+\s*\([^)]*\)\s*\{/,
152
- /export\s+default\s+function\s+\w+\s*\([^)]*\)\s*\{/,
153
- /export\s+default\s+async\s*\([^)]*\)\s*=>\s*\{/,
154
- /export\s+default\s*\([^)]*\)\s*=>\s*\{/,
155
- ];
156
- for (const re of patterns) {
157
- const m = re.exec(source);
158
- if (m) {
159
- const openIdx = m.index + m[0].length - 1;
160
- let depth = 0;
161
- for (let i = openIdx; i < source.length; i++) {
162
- const c = source[i];
163
- if (c === '{') depth++;
164
- else if (c === '}') {
165
- depth--;
166
- if (depth === 0) return { start: openIdx, end: i };
167
- }
168
- }
169
- }
170
- }
171
- return null;
172
- }
173
-
174
- function regexFindLastResponseCall(source, start, end) {
175
- const snippet = source.slice(start, end);
176
- const patterns = [
177
- /res\.status\s*\([^)]*\)\s*\.json\s*\(/g,
178
- /res\.status\s*\([^)]*\)\s*\.send\s*\(/g,
179
- /res\.json\s*\(/g,
180
- /res\.send\s*\(/g,
181
- /res\.sendStatus\s*\(/g,
182
- /res\.end\s*\(/g,
183
- ];
184
- let lastIdx = -1;
185
- for (const re of patterns) {
186
- let m;
187
- while ((m = re.exec(snippet)) !== null) {
188
- if (m.index > lastIdx) lastIdx = m.index;
189
- }
190
- }
191
- if (lastIdx === -1) return null;
192
- const absoluteIdx = start + lastIdx;
193
- let lineStart = absoluteIdx;
194
- while (lineStart > 0 && source[lineStart - 1] !== '\n') lineStart--;
195
- const indentMatch = source.slice(lineStart, absoluteIdx).match(/^(\s*)/);
196
- const indent = (indentMatch && indentMatch[1]) || ' ';
197
- return { insertAt: lineStart, indent };
198
- }
199
-
200
- function regexBuildTrackCall(eventName, indent) {
201
- const safeName = JSON.stringify(eventName);
202
- return `${indent}${MARKER} ${eventName}\n${indent}gurulu.track(${safeName}, {});\n`;
203
- }
204
-
205
- function regexInstrumentFile(before, method, events, opts = {}) {
206
- const body = regexFindHandlerBody(before);
207
- if (!body) return { ok: false, reason: 'handler-not-found' };
208
- const snippet = before.slice(body.start, body.end);
209
- const needed = [];
210
- const skipped = [];
211
- for (const e of events) {
212
- if (snippet.includes(`${MARKER} ${e.name}`)) {
213
- skipped.push({ event: e.name, reason: 'already-instrumented' });
214
- } else {
215
- needed.push(e);
216
- }
217
- }
218
- if (needed.length === 0) return { ok: true, after: before, instrumented: [], skipped, changed: false };
219
- const ret = regexFindLastResponseCall(before, body.start, body.end);
220
- if (!ret) return { ok: false, reason: 'no-response-found' };
221
- const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent)).join('');
222
- let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
223
- after = regexEnsureImport(after, opts);
224
- return {
225
- ok: true,
226
- after,
227
- instrumented: needed.map((e) => e.name),
228
- skipped,
229
- changed: true,
230
- };
231
- }
232
-
233
- // ---------------------------------------------------------------------------
234
- // Glue
235
- // ---------------------------------------------------------------------------
236
-
237
- function instrumentRouteFile(ctx, relPath, method, events) {
238
- const abs = path.join(ctx.repoRoot, relPath);
239
- if (!fs.existsSync(abs)) {
240
- return { change: null, skipped: events.map((e) => ({ event: e.name, reason: 'route-file-missing' })), notes: [] };
241
- }
242
- const before = fs.readFileSync(abs, 'utf8');
243
- const notes = [];
244
- // Sprint D / D4 — thread repoRoot + relPath through to the import resolver.
245
- const fileOpts = { repoRoot: (ctx && ctx.repoRoot) || null, relPath };
246
- let res;
247
- try {
248
- res = astInstrumentFile(before, method, events, fileOpts);
249
- } catch (err) {
250
- const msg = (err && err.message) || String(err);
251
- // eslint-disable-next-line no-console
252
- console.warn(`[auto-instrument] patch.fallback ${relPath}: ${msg}`);
253
- notes.push(`patch.fallback:${relPath}:${msg}`);
254
- res = regexInstrumentFile(before, method, events, fileOpts);
255
- }
256
- if (!res.ok) {
257
- return {
258
- change: null,
259
- skipped: events.map((e) => ({ event: e.name, reason: res.reason || 'instrument-failed' })),
260
- notes,
261
- };
262
- }
263
- if (!res.changed) return { change: null, skipped: res.skipped, notes };
264
- return {
265
- change: {
266
- relPath,
267
- before,
268
- after: res.after,
269
- reason: `auto-instrument-${method}`,
270
- type: 'auto-instrument',
271
- },
272
- skipped: res.skipped,
273
- instrumented: res.instrumented,
274
- notes,
275
- };
276
- }
277
-
278
- function groupEventsByRoute(ctx, events) {
279
- const groups = new Map();
280
- const unresolved = [];
281
- for (const e of events || []) {
282
- const routeStr = e && e.source && e.source.route;
283
- if (!routeStr) {
284
- unresolved.push({ event: e && e.name, reason: 'no-source-route' });
285
- continue;
286
- }
287
- const parsed = resolveRouteFileCandidates(routeStr);
288
- if (!parsed) {
289
- unresolved.push({ event: e.name, reason: `unparseable-route:${routeStr}` });
290
- continue;
291
- }
292
- const found = parsed.candidates.find((rel) =>
293
- fs.existsSync(path.join(ctx.repoRoot, rel)),
294
- );
295
- if (!found) {
296
- unresolved.push({ event: e.name, reason: 'route-file-not-found' });
297
- continue;
298
- }
299
- const key = `${found}::${parsed.method}`;
300
- if (!groups.has(key)) groups.set(key, { relPath: found, method: parsed.method, events: [] });
301
- groups.get(key).events.push(e);
302
- }
303
- return { groups: Array.from(groups.values()), unresolved };
304
- }
305
-
306
- function instrumentEvents(ctx, events) {
307
- const helper = singleton.ensureSingletonHelper(ctx, 'nextjs-pages');
308
- const changes = [...helper.changes];
309
- const notes = [...helper.notes];
310
- let eventsInstrumented = 0;
311
- let eventsSkipped = 0;
312
-
313
- if (helper.collision) {
314
- return {
315
- changes: [],
316
- notes,
317
- filesModified: 0,
318
- eventsInstrumented: 0,
319
- eventsSkipped: events ? events.length : 0,
320
- collision: true,
321
- };
322
- }
323
-
324
- const { groups, unresolved } = groupEventsByRoute(ctx, events || []);
325
- for (const u of unresolved) {
326
- notes.push(`skip:${u.event || '(unknown)'}:${u.reason}`);
327
- eventsSkipped++;
328
- }
329
- for (const group of groups) {
330
- const res = instrumentRouteFile(ctx, group.relPath, group.method, group.events);
331
- if (res.notes && res.notes.length) notes.push(...res.notes);
332
- if (res.change) {
333
- changes.push(res.change);
334
- eventsInstrumented += (res.instrumented || []).length;
335
- }
336
- for (const s of res.skipped || []) {
337
- notes.push(`skip:${s.event}:${s.reason}`);
338
- eventsSkipped++;
339
- }
340
- }
341
- const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
342
- return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
343
- }
344
-
345
- function ensureSingletonHelper(ctx) {
346
- return singleton.ensureSingletonHelper(ctx, 'nextjs-pages');
347
- }
348
-
349
- module.exports = {
350
- name: NAME,
351
- supportedFrameworks: SUPPORTED,
352
- ensureSingletonHelper,
353
- instrumentEvents,
354
- _internals: {
355
- resolveRouteFileCandidates,
356
- astInstrumentFile,
357
- regexInstrumentFile,
358
- groupEventsByRoute,
359
- instrumentRouteFile,
360
- },
361
- };