@gurulu/cli 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -2
- package/scripts/.gitkeep +0 -0
- package/scripts/README-gurulu-agentic-install.md +114 -0
- package/scripts/README-gurulu-scan.md +98 -0
- package/scripts/audit-cli-scopes.mjs +204 -0
- package/scripts/backfill-tenant-id.mjs +172 -0
- package/scripts/backfill-tenant-links.ts +252 -0
- package/scripts/backup-clickhouse.sh +27 -0
- package/scripts/backup-postgres.sh +19 -0
- package/scripts/bootstrap-runtime-schema.mjs +105 -0
- package/scripts/bootstrap-stripe.mjs +158 -0
- package/scripts/gurulu-agentic-install.lib.cjs +734 -0
- package/scripts/gurulu-agentic-install.mjs +343 -0
- package/scripts/gurulu-scan.lib.cjs +989 -0
- package/scripts/gurulu-scan.mjs +91 -0
- package/scripts/gurulu-verify-install.lib.cjs +334 -0
- package/scripts/gurulu-verify-install.mjs +59 -0
- package/scripts/init-ssl.sh +26 -0
- package/scripts/migrate-flow-graph-enums.sh +86 -0
- package/scripts/monitor-disk.sh +24 -0
- package/scripts/patches/astro.patch.cjs +73 -0
- package/scripts/patches/auto-instrument/ast-helper.cjs +332 -0
- package/scripts/patches/auto-instrument/astro.cjs +267 -0
- package/scripts/patches/auto-instrument/express.cjs +368 -0
- package/scripts/patches/auto-instrument/fastify.cjs +258 -0
- package/scripts/patches/auto-instrument/index.cjs +78 -0
- package/scripts/patches/auto-instrument/nestjs.cjs +282 -0
- package/scripts/patches/auto-instrument/nextjs-app-router.cjs +318 -0
- package/scripts/patches/auto-instrument/nextjs-pages.cjs +348 -0
- package/scripts/patches/auto-instrument/remix.cjs +164 -0
- package/scripts/patches/auto-instrument/singleton-helper.cjs +193 -0
- package/scripts/patches/auto-instrument/sveltekit.cjs +157 -0
- package/scripts/patches/auto-instrument/vite-react.cjs +37 -0
- package/scripts/patches/auto-instrument/vue.cjs +192 -0
- package/scripts/patches/express.patch.cjs +99 -0
- package/scripts/patches/fastify.patch.cjs +107 -0
- package/scripts/patches/index.cjs +294 -0
- package/scripts/patches/nestjs.patch.cjs +111 -0
- package/scripts/patches/nextjs-app-router.patch.cjs +95 -0
- package/scripts/patches/nextjs-pages.patch.cjs +96 -0
- package/scripts/patches/remix.patch.cjs +74 -0
- package/scripts/patches/sveltekit.patch.cjs +71 -0
- package/scripts/patches/vite-react.patch.cjs +72 -0
- package/scripts/patches/vue.patch.cjs +81 -0
- package/scripts/renew-ssl.sh +14 -0
- package/scripts/resolve-migration.sh +23 -0
- package/scripts/seed-cli-dev-keys.mjs +130 -0
- package/scripts/seed-test-data.mjs +391 -0
- package/scripts/spike-browserless.ts +65 -0
- package/scripts/tenant-pivot-consistency-check.mjs +205 -0
- package/scripts/tenant-pivot-phase-3-cleanup.lib.cjs +258 -0
- package/scripts/tenant-pivot-phase-3-cleanup.mjs +98 -0
- package/scripts/test-identity-resolution.ts +804 -0
- package/scripts/validate-gurulu-schemas.mjs +79 -0
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
// scripts/patches/auto-instrument/nestjs.cjs — Phase 20 W1 A3.
|
|
2
|
+
//
|
|
3
|
+
// AST-based auto-instrumentation for NestJS controllers. We parse every
|
|
4
|
+
// controller file under `src/**` and look for class methods decorated with
|
|
5
|
+
// `@Get`, `@Post`, etc. whose enclosing class carries a `@Controller('...')`
|
|
6
|
+
// decorator. Matching methods get a `gurulu.track(...)` call inserted
|
|
7
|
+
// before the last top-level return.
|
|
8
|
+
//
|
|
9
|
+
// Route matching: given a ProposedEvent with `source.route = 'POST /users'`
|
|
10
|
+
// we match against `<controllerBase>/<methodPath>` where `controllerBase`
|
|
11
|
+
// comes from the `@Controller('path')` argument and `methodPath` comes from
|
|
12
|
+
// the method decorator argument (optional, defaults to '/').
|
|
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-nestjs';
|
|
21
|
+
const SUPPORTED = ['nestjs'];
|
|
22
|
+
|
|
23
|
+
const HTTP_DECORATORS = new Set([
|
|
24
|
+
'Get', 'Post', 'Put', 'Patch', 'Delete', 'Options', 'Head', 'All',
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
function parseEventRoute(routeStr) {
|
|
28
|
+
if (!routeStr || typeof routeStr !== 'string') return null;
|
|
29
|
+
const m = routeStr.trim().match(/^([A-Z]+)\s+(\/.*)$/);
|
|
30
|
+
if (!m) return null;
|
|
31
|
+
return { method: m[1].toUpperCase(), urlPath: m[2].replace(/\/+$/, '') || '/' };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function walkSourceFiles(repoRoot) {
|
|
35
|
+
const results = [];
|
|
36
|
+
const stack = ['src'];
|
|
37
|
+
while (stack.length > 0) {
|
|
38
|
+
const rel = stack.pop();
|
|
39
|
+
const abs = path.join(repoRoot, rel);
|
|
40
|
+
if (!fs.existsSync(abs)) continue;
|
|
41
|
+
let entries = [];
|
|
42
|
+
try {
|
|
43
|
+
entries = fs.readdirSync(abs, { withFileTypes: true });
|
|
44
|
+
} catch (_) {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
|
|
49
|
+
const childRel = path.posix.join(rel, entry.name);
|
|
50
|
+
if (entry.isDirectory()) {
|
|
51
|
+
stack.push(childRel);
|
|
52
|
+
} else if (/\.(ts|js)$/.test(entry.name) && !entry.name.endsWith('.d.ts')) {
|
|
53
|
+
results.push(childRel);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return results;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Normalize a base + method route into the "/base/method" form (no trailing
|
|
62
|
+
* slash, no duplicate slashes). Leading slash enforced.
|
|
63
|
+
*/
|
|
64
|
+
function joinRoute(base, method) {
|
|
65
|
+
const a = String(base || '').replace(/^\//, '').replace(/\/+$/, '');
|
|
66
|
+
const b = String(method || '').replace(/^\//, '').replace(/\/+$/, '');
|
|
67
|
+
let joined = [a, b].filter(Boolean).join('/');
|
|
68
|
+
joined = '/' + joined;
|
|
69
|
+
return joined.replace(/\/+/g, '/').replace(/\/$/, '') || '/';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Scan an AST for controller class methods and collect
|
|
74
|
+
* `{ classNode, methodNode, method, urlPath }` entries.
|
|
75
|
+
*/
|
|
76
|
+
function collectControllerMethods(tree) {
|
|
77
|
+
const t = ast.t;
|
|
78
|
+
const results = [];
|
|
79
|
+
ast.traverse(tree, {
|
|
80
|
+
ClassDeclaration(p) {
|
|
81
|
+
const decorators = p.node.decorators || [];
|
|
82
|
+
let controllerBase = '';
|
|
83
|
+
let isController = false;
|
|
84
|
+
for (const d of decorators) {
|
|
85
|
+
if (!t.isDecorator(d)) continue;
|
|
86
|
+
const expr = d.expression;
|
|
87
|
+
if (t.isCallExpression(expr) && t.isIdentifier(expr.callee) && expr.callee.name === 'Controller') {
|
|
88
|
+
isController = true;
|
|
89
|
+
const arg0 = expr.arguments[0];
|
|
90
|
+
if (t.isStringLiteral(arg0)) controllerBase = arg0.value;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (!isController) return;
|
|
94
|
+
for (const member of p.node.body.body) {
|
|
95
|
+
if (!t.isClassMethod(member) && !t.isClassProperty(member)) continue;
|
|
96
|
+
const mDecorators = member.decorators || [];
|
|
97
|
+
for (const dec of mDecorators) {
|
|
98
|
+
if (!t.isDecorator(dec)) continue;
|
|
99
|
+
const expr = dec.expression;
|
|
100
|
+
if (!t.isCallExpression(expr)) continue;
|
|
101
|
+
if (!t.isIdentifier(expr.callee)) continue;
|
|
102
|
+
if (!HTTP_DECORATORS.has(expr.callee.name)) continue;
|
|
103
|
+
const httpMethod = expr.callee.name.toUpperCase();
|
|
104
|
+
const arg0 = expr.arguments[0];
|
|
105
|
+
const methodPath = t.isStringLiteral(arg0) ? arg0.value : '';
|
|
106
|
+
const fullPath = joinRoute(controllerBase, methodPath);
|
|
107
|
+
// Only support class methods with block bodies.
|
|
108
|
+
if (!t.isClassMethod(member) || !t.isBlockStatement(member.body)) continue;
|
|
109
|
+
results.push({
|
|
110
|
+
methodNode: member,
|
|
111
|
+
body: member.body,
|
|
112
|
+
httpMethod,
|
|
113
|
+
urlPath: fullPath,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
return results;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function astInstrumentFile(source, targets) {
|
|
123
|
+
// targets: [{ httpMethod, urlPath, events: [] }]
|
|
124
|
+
const tree = ast.parseSource(source);
|
|
125
|
+
const methods = collectControllerMethods(tree);
|
|
126
|
+
if (methods.length === 0) return { ok: false, reason: 'no-controllers' };
|
|
127
|
+
let changed = false;
|
|
128
|
+
const instrumentedNames = [];
|
|
129
|
+
const skipped = [];
|
|
130
|
+
for (const target of targets) {
|
|
131
|
+
const match = methods.find(
|
|
132
|
+
(m) => m.httpMethod === target.httpMethod && m.urlPath === target.urlPath,
|
|
133
|
+
);
|
|
134
|
+
if (!match) {
|
|
135
|
+
for (const e of target.events) {
|
|
136
|
+
skipped.push({ event: e.name, reason: 'controller-method-not-found' });
|
|
137
|
+
}
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (ast.hasInstrumentedMarker(match.methodNode)) {
|
|
141
|
+
for (const e of target.events) skipped.push({ event: e.name, reason: 'already-instrumented' });
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const stmts = target.events.map((e) => ast.buildTrackStatement(e.name, e.autoProperties));
|
|
145
|
+
ast.injectTrackBeforeLastReturn(match.methodNode, match.body, stmts);
|
|
146
|
+
changed = true;
|
|
147
|
+
for (const e of target.events) instrumentedNames.push(e.name);
|
|
148
|
+
}
|
|
149
|
+
if (!changed) {
|
|
150
|
+
return { ok: true, after: source, instrumented: [], skipped, changed: false };
|
|
151
|
+
}
|
|
152
|
+
ast.ensureGuruluImport(tree);
|
|
153
|
+
const after = ast.generateSource(tree, source);
|
|
154
|
+
return { ok: true, after, instrumented: instrumentedNames, skipped, changed: true };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function resolveControllerFileForEvent(ctx, httpMethod, urlPath) {
|
|
158
|
+
const files = walkSourceFiles(ctx.repoRoot);
|
|
159
|
+
for (const rel of files) {
|
|
160
|
+
if (!/\.controller\.(ts|js)$/.test(rel) && !rel.includes('controller')) continue;
|
|
161
|
+
const abs = path.join(ctx.repoRoot, rel);
|
|
162
|
+
let src;
|
|
163
|
+
try {
|
|
164
|
+
src = fs.readFileSync(abs, 'utf8');
|
|
165
|
+
} catch (_) {
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (!src.includes('@Controller')) continue;
|
|
169
|
+
try {
|
|
170
|
+
const tree = ast.parseSource(src);
|
|
171
|
+
const methods = collectControllerMethods(tree);
|
|
172
|
+
if (methods.some((m) => m.httpMethod === httpMethod && m.urlPath === urlPath)) {
|
|
173
|
+
return rel;
|
|
174
|
+
}
|
|
175
|
+
} catch (_) {
|
|
176
|
+
// Skip malformed files.
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function instrumentEvents(ctx, events) {
|
|
183
|
+
const helper = singleton.ensureSingletonHelper(ctx, 'nestjs');
|
|
184
|
+
const changes = [...helper.changes];
|
|
185
|
+
const notes = [...helper.notes];
|
|
186
|
+
let eventsInstrumented = 0;
|
|
187
|
+
let eventsSkipped = 0;
|
|
188
|
+
|
|
189
|
+
if (helper.collision) {
|
|
190
|
+
return {
|
|
191
|
+
changes: [],
|
|
192
|
+
notes,
|
|
193
|
+
filesModified: 0,
|
|
194
|
+
eventsInstrumented: 0,
|
|
195
|
+
eventsSkipped: events ? events.length : 0,
|
|
196
|
+
collision: true,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Group events by (file, httpMethod, urlPath).
|
|
201
|
+
const fileGroups = new Map();
|
|
202
|
+
for (const e of events || []) {
|
|
203
|
+
const parsed = parseEventRoute(e && e.source && e.source.route);
|
|
204
|
+
if (!parsed) {
|
|
205
|
+
notes.push(`skip:${e && e.name}:no-source-route`);
|
|
206
|
+
eventsSkipped++;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const rel = resolveControllerFileForEvent(ctx, parsed.method, parsed.urlPath);
|
|
210
|
+
if (!rel) {
|
|
211
|
+
notes.push(`skip:${e.name}:controller-not-found`);
|
|
212
|
+
eventsSkipped++;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (!fileGroups.has(rel)) fileGroups.set(rel, new Map());
|
|
216
|
+
const perFile = fileGroups.get(rel);
|
|
217
|
+
const key = `${parsed.method}::${parsed.urlPath}`;
|
|
218
|
+
if (!perFile.has(key)) perFile.set(key, { httpMethod: parsed.method, urlPath: parsed.urlPath, events: [] });
|
|
219
|
+
perFile.get(key).events.push(e);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
for (const [rel, perFile] of fileGroups.entries()) {
|
|
223
|
+
const abs = path.join(ctx.repoRoot, rel);
|
|
224
|
+
const before = fs.readFileSync(abs, 'utf8');
|
|
225
|
+
const targets = Array.from(perFile.values());
|
|
226
|
+
let res;
|
|
227
|
+
try {
|
|
228
|
+
res = astInstrumentFile(before, targets);
|
|
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 ${rel}: ${msg}`);
|
|
233
|
+
notes.push(`patch.fallback:${rel}:${msg}`);
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (!res.ok) {
|
|
237
|
+
for (const t of targets) {
|
|
238
|
+
for (const e of t.events) {
|
|
239
|
+
notes.push(`skip:${e.name}:${res.reason}`);
|
|
240
|
+
eventsSkipped++;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
for (const s of res.skipped || []) {
|
|
246
|
+
notes.push(`skip:${s.event}:${s.reason}`);
|
|
247
|
+
eventsSkipped++;
|
|
248
|
+
}
|
|
249
|
+
if (res.changed) {
|
|
250
|
+
changes.push({
|
|
251
|
+
relPath: rel,
|
|
252
|
+
before,
|
|
253
|
+
after: res.after,
|
|
254
|
+
reason: `auto-instrument-nestjs`,
|
|
255
|
+
type: 'auto-instrument',
|
|
256
|
+
});
|
|
257
|
+
eventsInstrumented += (res.instrumented || []).length;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
|
|
262
|
+
return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function ensureSingletonHelper(ctx) {
|
|
266
|
+
return singleton.ensureSingletonHelper(ctx, 'nestjs');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
module.exports = {
|
|
270
|
+
name: NAME,
|
|
271
|
+
supportedFrameworks: SUPPORTED,
|
|
272
|
+
ensureSingletonHelper,
|
|
273
|
+
instrumentEvents,
|
|
274
|
+
_internals: {
|
|
275
|
+
parseEventRoute,
|
|
276
|
+
walkSourceFiles,
|
|
277
|
+
collectControllerMethods,
|
|
278
|
+
astInstrumentFile,
|
|
279
|
+
resolveControllerFileForEvent,
|
|
280
|
+
joinRoute,
|
|
281
|
+
},
|
|
282
|
+
};
|
|
@@ -0,0 +1,318 @@
|
|
|
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.autoProperties || opts.autoProperties && e.extractedProperties),
|
|
74
|
+
);
|
|
75
|
+
const injected = ast.injectTrackBeforeLastReturn(target.fn, target.body, trackStmts);
|
|
76
|
+
if (!injected) {
|
|
77
|
+
return { ok: false, reason: 'inject-failed' };
|
|
78
|
+
}
|
|
79
|
+
ast.ensureGuruluImport(tree);
|
|
80
|
+
const after = ast.generateSource(tree, source);
|
|
81
|
+
return {
|
|
82
|
+
ok: true,
|
|
83
|
+
after,
|
|
84
|
+
instrumented: events.map((e) => e.name),
|
|
85
|
+
skipped: [],
|
|
86
|
+
changed: true,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// ---------------------------------------------------------------------------
|
|
91
|
+
// Regex fallback (legacy Phase 18.7 pathway) — unchanged behaviour, kept in
|
|
92
|
+
// scope for graceful degradation.
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
|
|
95
|
+
function regexEnsureImport(source) {
|
|
96
|
+
if (source.includes(IMPORT_LINE)) return { source, added: false };
|
|
97
|
+
const importRegex = /^(?:import[\s\S]*?;\s*\n)+/m;
|
|
98
|
+
const m = source.match(importRegex);
|
|
99
|
+
if (m) {
|
|
100
|
+
const end = m.index + m[0].length;
|
|
101
|
+
return { source: source.slice(0, end) + IMPORT_LINE + '\n' + source.slice(end), added: true };
|
|
102
|
+
}
|
|
103
|
+
return { source: IMPORT_LINE + '\n' + source, added: true };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function regexFindMethodBody(source, method) {
|
|
107
|
+
const re = new RegExp(
|
|
108
|
+
`export\\s+async\\s+function\\s+${method}\\s*\\([^)]*\\)\\s*(?::\\s*[^\\{]+)?\\{`,
|
|
109
|
+
'm',
|
|
110
|
+
);
|
|
111
|
+
const m = re.exec(source);
|
|
112
|
+
if (!m) return null;
|
|
113
|
+
const openIdx = m.index + m[0].length - 1;
|
|
114
|
+
let depth = 0;
|
|
115
|
+
for (let i = openIdx; i < source.length; i++) {
|
|
116
|
+
const c = source[i];
|
|
117
|
+
if (c === '{') depth++;
|
|
118
|
+
else if (c === '}') {
|
|
119
|
+
depth--;
|
|
120
|
+
if (depth === 0) return { start: openIdx, end: i };
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function regexFindLastReturnInBody(source, start, end) {
|
|
127
|
+
const snippet = source.slice(start, end);
|
|
128
|
+
const patterns = [
|
|
129
|
+
/return\s+NextResponse\.json\s*\(/g,
|
|
130
|
+
/return\s+Response\.json\s*\(/g,
|
|
131
|
+
/return\s+new\s+Response\s*\(/g,
|
|
132
|
+
/return\s+NextResponse\s*\./g,
|
|
133
|
+
];
|
|
134
|
+
let lastIdx = -1;
|
|
135
|
+
for (const re of patterns) {
|
|
136
|
+
let m;
|
|
137
|
+
while ((m = re.exec(snippet)) !== null) {
|
|
138
|
+
if (m.index > lastIdx) lastIdx = m.index;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (lastIdx === -1) return null;
|
|
142
|
+
const absoluteReturnIdx = start + lastIdx;
|
|
143
|
+
let lineStart = absoluteReturnIdx;
|
|
144
|
+
while (lineStart > 0 && source[lineStart - 1] !== '\n') lineStart--;
|
|
145
|
+
const indentMatch = source.slice(lineStart, absoluteReturnIdx).match(/^(\s*)/);
|
|
146
|
+
const indent = (indentMatch && indentMatch[1]) || ' ';
|
|
147
|
+
return { insertAt: lineStart, indent };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function regexBuildTrackCall(eventName, indent) {
|
|
151
|
+
const safeName = JSON.stringify(eventName);
|
|
152
|
+
return (
|
|
153
|
+
`${indent}${MARKER} ${eventName}\n` +
|
|
154
|
+
`${indent}gurulu.track(${safeName}, {});\n`
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function regexInstrumentFile(before, method, events) {
|
|
159
|
+
const body = regexFindMethodBody(before, method);
|
|
160
|
+
if (!body) {
|
|
161
|
+
return { ok: false, reason: `method-${method}-not-found` };
|
|
162
|
+
}
|
|
163
|
+
const bodySnippet = before.slice(body.start, body.end);
|
|
164
|
+
const needed = [];
|
|
165
|
+
const skipped = [];
|
|
166
|
+
for (const e of events) {
|
|
167
|
+
if (bodySnippet.includes(`${MARKER} ${e.name}`)) {
|
|
168
|
+
skipped.push({ event: e.name, reason: 'already-instrumented' });
|
|
169
|
+
} else {
|
|
170
|
+
needed.push(e);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (needed.length === 0) return { ok: true, after: before, instrumented: [], skipped, changed: false };
|
|
174
|
+
const ret = regexFindLastReturnInBody(before, body.start, body.end);
|
|
175
|
+
if (!ret) return { ok: false, reason: 'no-return-found' };
|
|
176
|
+
const block = needed.map((e) => regexBuildTrackCall(e.name, ret.indent)).join('');
|
|
177
|
+
let after = before.slice(0, ret.insertAt) + block + before.slice(ret.insertAt);
|
|
178
|
+
after = regexEnsureImport(after).source;
|
|
179
|
+
return {
|
|
180
|
+
ok: true,
|
|
181
|
+
after,
|
|
182
|
+
instrumented: needed.map((e) => e.name),
|
|
183
|
+
skipped,
|
|
184
|
+
changed: true,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// ---------------------------------------------------------------------------
|
|
189
|
+
// Dispatcher plumbing
|
|
190
|
+
// ---------------------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
function instrumentRouteFile(ctx, relPath, method, events) {
|
|
193
|
+
const abs = path.join(ctx.repoRoot, relPath);
|
|
194
|
+
if (!fs.existsSync(abs)) {
|
|
195
|
+
return { change: null, skipped: events.map((e) => ({ event: e.name, reason: 'route-file-missing' })), notes: [] };
|
|
196
|
+
}
|
|
197
|
+
const before = fs.readFileSync(abs, 'utf8');
|
|
198
|
+
const notes = [];
|
|
199
|
+
let res;
|
|
200
|
+
try {
|
|
201
|
+
res = astInstrumentFile(before, method, events, ctx || {});
|
|
202
|
+
} catch (err) {
|
|
203
|
+
const msg = (err && err.message) || String(err);
|
|
204
|
+
// eslint-disable-next-line no-console
|
|
205
|
+
console.warn(`[auto-instrument] patch.fallback ${relPath}: ${msg}`);
|
|
206
|
+
notes.push(`patch.fallback:${relPath}:${msg}`);
|
|
207
|
+
res = regexInstrumentFile(before, method, events);
|
|
208
|
+
}
|
|
209
|
+
if (!res.ok) {
|
|
210
|
+
return {
|
|
211
|
+
change: null,
|
|
212
|
+
skipped: events.map((e) => ({ event: e.name, reason: res.reason || 'instrument-failed' })),
|
|
213
|
+
notes,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
if (!res.changed) {
|
|
217
|
+
return { change: null, skipped: res.skipped, notes };
|
|
218
|
+
}
|
|
219
|
+
return {
|
|
220
|
+
change: {
|
|
221
|
+
relPath,
|
|
222
|
+
before,
|
|
223
|
+
after: res.after,
|
|
224
|
+
reason: `auto-instrument-${method}`,
|
|
225
|
+
type: 'auto-instrument',
|
|
226
|
+
},
|
|
227
|
+
skipped: res.skipped,
|
|
228
|
+
instrumented: res.instrumented,
|
|
229
|
+
notes,
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function groupEventsByRoute(ctx, events) {
|
|
234
|
+
const groups = new Map();
|
|
235
|
+
const unresolved = [];
|
|
236
|
+
for (const e of events || []) {
|
|
237
|
+
const routeStr = (e && e.source && e.source.route) || null;
|
|
238
|
+
if (!routeStr) {
|
|
239
|
+
unresolved.push({ event: e && e.name, reason: 'no-source-route' });
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const parsed = resolveRouteFileCandidates(routeStr);
|
|
243
|
+
if (!parsed) {
|
|
244
|
+
unresolved.push({ event: e.name, reason: `unparseable-route:${routeStr}` });
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
const found = parsed.candidates.find((rel) =>
|
|
248
|
+
fs.existsSync(path.join(ctx.repoRoot, rel)),
|
|
249
|
+
);
|
|
250
|
+
if (!found) {
|
|
251
|
+
unresolved.push({ event: e.name, reason: 'route-file-not-found' });
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
const key = `${found}::${parsed.method}`;
|
|
255
|
+
if (!groups.has(key)) groups.set(key, { relPath: found, method: parsed.method, events: [] });
|
|
256
|
+
groups.get(key).events.push(e);
|
|
257
|
+
}
|
|
258
|
+
return { groups: Array.from(groups.values()), unresolved };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function instrumentEvents(ctx, events) {
|
|
262
|
+
const helper = singleton.ensureSingletonHelper(ctx, 'nextjs-app-router');
|
|
263
|
+
const changes = [...helper.changes];
|
|
264
|
+
const notes = [...helper.notes];
|
|
265
|
+
let eventsInstrumented = 0;
|
|
266
|
+
let eventsSkipped = 0;
|
|
267
|
+
|
|
268
|
+
if (helper.collision) {
|
|
269
|
+
return {
|
|
270
|
+
changes: [],
|
|
271
|
+
notes,
|
|
272
|
+
filesModified: 0,
|
|
273
|
+
eventsInstrumented: 0,
|
|
274
|
+
eventsSkipped: events ? events.length : 0,
|
|
275
|
+
collision: true,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const { groups, unresolved } = groupEventsByRoute(ctx, events || []);
|
|
280
|
+
for (const u of unresolved) {
|
|
281
|
+
notes.push(`skip:${u.event || '(unknown)'}:${u.reason}`);
|
|
282
|
+
eventsSkipped++;
|
|
283
|
+
}
|
|
284
|
+
for (const group of groups) {
|
|
285
|
+
const res = instrumentRouteFile(ctx, group.relPath, group.method, group.events);
|
|
286
|
+
if (res.notes && res.notes.length) notes.push(...res.notes);
|
|
287
|
+
if (res.change) {
|
|
288
|
+
changes.push(res.change);
|
|
289
|
+
eventsInstrumented += (res.instrumented || []).length;
|
|
290
|
+
}
|
|
291
|
+
for (const s of res.skipped || []) {
|
|
292
|
+
notes.push(`skip:${s.event}:${s.reason}`);
|
|
293
|
+
eventsSkipped++;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const filesModified = changes.filter((c) => c.type === 'auto-instrument').length;
|
|
298
|
+
return { changes, notes, filesModified, eventsInstrumented, eventsSkipped, collision: false };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function ensureSingletonHelper(ctx) {
|
|
302
|
+
return singleton.ensureSingletonHelper(ctx, 'nextjs-app-router');
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
module.exports = {
|
|
306
|
+
name: NAME,
|
|
307
|
+
supportedFrameworks: SUPPORTED,
|
|
308
|
+
ensureSingletonHelper,
|
|
309
|
+
instrumentEvents,
|
|
310
|
+
_internals: {
|
|
311
|
+
resolveRouteFileCandidates,
|
|
312
|
+
astInstrumentFile,
|
|
313
|
+
regexInstrumentFile,
|
|
314
|
+
groupEventsByRoute,
|
|
315
|
+
instrumentRouteFile,
|
|
316
|
+
METHODS,
|
|
317
|
+
},
|
|
318
|
+
};
|