@babylonjs-toolkit/agent 1.1.66 → 1.1.68

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.
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Turns raw V8 call frames (script id, URL, 0-based line / column) into readable, owned locations:
3
+ * the original file and line (through the script's source map when it has one), the enclosing class
4
+ * (`StandardKartController.update` instead of `update`), and the owner — your project, a project-owned bundle,
5
+ * the toolkit, Babylon, physics, shader translation, React, other vendors, or the browser itself.
6
+ */
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import sourceMap from "source-map-js";
10
+
11
+ /** Owners whose code the user writes and can change. Config owners may add to this (`yours: true`). */
12
+ export const YOUR_OWNERS = new Set(["project"]);
13
+
14
+ /** Built-in owner labels for the report. */
15
+ export const OWNER_LABELS = {
16
+ project: "Your game code",
17
+ toolkit: "Babylon Toolkit runtime",
18
+ babylon: "BabylonJS engine",
19
+ physics: "Havok physics",
20
+ shader: "Shader translation (GLSL → WGSL)",
21
+ react: "React / router",
22
+ vendor: "Other libraries",
23
+ gc: "Garbage collection",
24
+ program: "Browser (parse, compile, layout, GPU IPC)",
25
+ idle: "Idle",
26
+ native: "Browser API",
27
+ };
28
+
29
+ /** Synthetic V8 frames that are never code. */
30
+ const SPECIAL_FRAMES = { "(garbage collector)": "gc", "(program)": "program", "(idle)": "idle", "(root)": "root" };
31
+
32
+ /**
33
+ * Builds a symbolizer for one capture.
34
+ * @param {object} options
35
+ * @param {string} options.scriptsDir - the capture's scripts/ folder (index.json, <id>.js, <id>.map.json)
36
+ * @param {string} options.projectRoot - absolute project root, to resolve dev-server paths to files
37
+ * @param {{match: string, owner: string, label?: string, yours?: boolean, sourceRoots?: string[]}[]} options.owners - config owner rules
38
+ * @returns {{frame: Function, line: Function, ownerOf: Function, labels: object, yours: Set<string>, scripts: Map}} the symbolizer
39
+ */
40
+ export function createSymbolizer({ scriptsDir, projectRoot, owners = [] }) {
41
+ const index = fs.existsSync(path.join(scriptsDir, "index.json")) ? JSON.parse(fs.readFileSync(path.join(scriptsDir, "index.json"), "utf8")) : [];
42
+ const scripts = new Map(index.map((entry) => [entry.scriptId, entry]));
43
+ const ownerRules = owners.map((rule) => ({ ...rule, pattern: new RegExp(rule.match) }));
44
+ const labels = { ...OWNER_LABELS };
45
+ const yours = new Set(YOUR_OWNERS);
46
+ for (const rule of ownerRules) {
47
+ if (rule.label) labels[rule.owner] = rule.label;
48
+ if (rule.yours !== false) yours.add(rule.owner);
49
+ }
50
+ const textCache = new Map();
51
+ const consumerCache = new Map();
52
+ const classSpanCache = new Map();
53
+ const frameCache = new Map();
54
+ const classFileCache = new Map();
55
+
56
+ /** Returns the generated text of a script, or null. */
57
+ const scriptText = (scriptId) => {
58
+ const key = `script:${scriptId}`;
59
+ if (textCache.has(key)) return textCache.get(key);
60
+ const file = path.join(scriptsDir, `${scriptId}.js`);
61
+ const text = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : null;
62
+ textCache.set(key, text);
63
+ return text;
64
+ };
65
+
66
+ /** Returns a source-map consumer for a script, or null. */
67
+ const consumerFor = (scriptId) => {
68
+ if (consumerCache.has(scriptId)) return consumerCache.get(scriptId);
69
+ let consumer = null;
70
+ const file = path.join(scriptsDir, `${scriptId}.map.json`);
71
+ if (fs.existsSync(file)) {
72
+ try { consumer = new sourceMap.SourceMapConsumer(JSON.parse(fs.readFileSync(file, "utf8"))); } catch { consumer = null; }
73
+ }
74
+ consumerCache.set(scriptId, consumer);
75
+ return consumer;
76
+ };
77
+
78
+ /**
79
+ * Maps a dev-server or file URL to a local file path when one exists.
80
+ * @returns {string|null} absolute file path
81
+ */
82
+ const urlToFile = (url) => {
83
+ if (!url) return null;
84
+ let pathname;
85
+ try { pathname = decodeURIComponent(new URL(url).pathname); } catch { pathname = url; }
86
+ if (url.startsWith("file://")) return fs.existsSync(pathname) ? pathname : null;
87
+ if (pathname.startsWith("/@fs/")) {
88
+ const absolute = pathname.slice(4);
89
+ return fs.existsSync(absolute) ? absolute : null;
90
+ }
91
+ if (path.isAbsolute(pathname) && fs.existsSync(pathname) && !pathname.startsWith("/src/") && !pathname.startsWith("/node_modules/")) return pathname;
92
+ const candidates = [path.join(projectRoot, pathname), path.join(projectRoot, "public", pathname)];
93
+ return candidates.find((candidate) => fs.existsSync(candidate)) || null;
94
+ };
95
+
96
+ /** Owner of a script URL by the config rules, then the built-in rules. */
97
+ const ownerOfUrl = (url) => {
98
+ for (const rule of ownerRules) if (rule.pattern.test(url)) return rule.owner;
99
+ if (/glslang|twgsl/i.test(url)) return "shader";
100
+ if (/havok|Physics\/v2\//i.test(url)) return "physics";
101
+ if (/@babylonjs-toolkit|Runtime\/ESM\//.test(url)) return "toolkit";
102
+ if (/node_modules\/@babylonjs\//.test(url)) return "babylon";
103
+ if (/node_modules\/(\.vite\/deps\/)?(react|react-dom|scheduler|react-router|react-router-dom)([/._]|$)/.test(url)) return "react";
104
+ // A pre-bundled dependency served from any optimizer cache folder (`.vite/deps/`, a custom cacheDir's `deps/`).
105
+ if (/\/deps\/(react|react-dom|scheduler|react-router|react-router-dom)[_.]/.test(url)) return "react";
106
+ if (/\/deps\/@babylonjs_/.test(url)) return "babylon";
107
+ if (/node_modules\//.test(url)) return "vendor";
108
+ let pathname = "";
109
+ try { pathname = new URL(url).pathname; } catch { pathname = url; }
110
+ if (pathname.startsWith("/src/") || pathname.startsWith("/@fs/") && pathname.includes(projectRoot)) return "project";
111
+ if (/\.wasm$/.test(pathname)) return "vendor";
112
+ return "vendor";
113
+ };
114
+
115
+ /**
116
+ * Owner of an original source file (a source-mapped frame): the file a bundle was built from names its library even when
117
+ * the bundle's URL does not (a dependency chunk, a custom optimizer cache). Null when the path says nothing.
118
+ */
119
+ const ownerOfSourcePath = (file) => {
120
+ const normalized = file.split(path.sep).join("/");
121
+ if (/glslang|twgsl/i.test(normalized)) return "shader";
122
+ if (/havok|\/Physics\/v2\//i.test(normalized)) return "physics";
123
+ if (/@babylonjs-toolkit\/|\/Runtime\/ESM\//.test(normalized)) return "toolkit";
124
+ if (/node_modules\/@babylonjs\//.test(normalized)) return "babylon";
125
+ if (/node_modules\/(react|react-dom|scheduler|react-router|react-router-dom)\//.test(normalized)) return "react";
126
+ if (/node_modules\//.test(normalized)) return "vendor";
127
+ if (normalized.startsWith(projectRoot.split(path.sep).join("/") + "/")) return "project";
128
+ return null;
129
+ };
130
+
131
+ /** Splits text into line-start offsets (cached with the text). */
132
+ const lineStarts = (text) => {
133
+ const starts = [0];
134
+ for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 10) starts.push(i + 1);
135
+ return starts;
136
+ };
137
+
138
+ /** Finds every `class Name { … }` span in a text (strings, comments and template literals skipped). */
139
+ const classSpans = (cacheKey, text) => {
140
+ if (classSpanCache.has(cacheKey)) return classSpanCache.get(cacheKey);
141
+ const spans = [];
142
+ const stack = [];
143
+ const templateDepths = [];
144
+ let depth = 0;
145
+ let pendingClass = null;
146
+ let i = 0;
147
+ const length = text.length;
148
+ while (i < length) {
149
+ const character = text[i];
150
+ const next = text[i + 1];
151
+ if (character === "/" && next === "/") { const end = text.indexOf("\n", i); i = end < 0 ? length : end; continue; }
152
+ if (character === "/" && next === "*") { const end = text.indexOf("*/", i + 2); i = end < 0 ? length : end + 2; continue; }
153
+ if (character === "'" || character === "\"") {
154
+ i++;
155
+ while (i < length && text[i] !== character) { if (text[i] === "\\") i++; if (text[i] === "\n") break; i++; }
156
+ i++;
157
+ continue;
158
+ }
159
+ if (character === "`") {
160
+ i++;
161
+ while (i < length && text[i] !== "`") {
162
+ if (text[i] === "\\") { i += 2; continue; }
163
+ if (text[i] === "$" && text[i + 1] === "{") { templateDepths.push(depth); depth++; i += 2; break; }
164
+ i++;
165
+ }
166
+ if (text[i] === "`") i++;
167
+ continue;
168
+ }
169
+ if (character === "}" && templateDepths.length > 0 && templateDepths[templateDepths.length - 1] === depth - 1) {
170
+ // End of a ${…} expression: resume the template literal.
171
+ depth--;
172
+ templateDepths.pop();
173
+ i++;
174
+ while (i < length && text[i] !== "`") {
175
+ if (text[i] === "\\") { i += 2; continue; }
176
+ if (text[i] === "$" && text[i + 1] === "{") { templateDepths.push(depth); depth++; i += 2; break; }
177
+ i++;
178
+ }
179
+ if (text[i] === "`") i++;
180
+ continue;
181
+ }
182
+ if (character === "c" && text.startsWith("class", i) && !/[\w$]/.test(text[i - 1] || " ") && /\s/.test(text[i + 5] || "")) {
183
+ const match = /^class\s+([A-Za-z_$][\w$]*)/.exec(text.slice(i, i + 200));
184
+ if (match) pendingClass = { name: match[1], start: i };
185
+ i += 5;
186
+ continue;
187
+ }
188
+ if (character === "{") {
189
+ if (pendingClass) { stack.push({ ...pendingClass, depth }); pendingClass = null; }
190
+ depth++;
191
+ } else if (character === "}") {
192
+ depth--;
193
+ const top = stack[stack.length - 1];
194
+ if (top && top.depth === depth) { spans.push({ name: top.name, start: top.start, end: i }); stack.pop(); }
195
+ }
196
+ i++;
197
+ }
198
+ classSpanCache.set(cacheKey, spans);
199
+ return spans;
200
+ };
201
+
202
+ /** Innermost class whose span contains a 0-based line / column of a text. */
203
+ const enclosingClass = (cacheKey, text, line, column) => {
204
+ if (!text) return null;
205
+ const startsKey = `${cacheKey}:starts`;
206
+ if (!textCache.has(startsKey)) textCache.set(startsKey, lineStarts(text));
207
+ const starts = textCache.get(startsKey);
208
+ const offset = (starts[line] ?? 0) + column;
209
+ let best = null;
210
+ for (const span of classSpans(cacheKey, text)) {
211
+ if (span.start <= offset && offset <= span.end && (!best || span.start > best.start)) best = span;
212
+ }
213
+ return best ? best.name : null;
214
+ };
215
+
216
+ /**
217
+ * Finds the TypeScript / JavaScript file that declares a class under the rule's source roots, and the line of a
218
+ * method in it — for bundles that ship without source maps but keep their class and method names.
219
+ * @returns {{file: string, line: number}|null} 1-based line
220
+ */
221
+ const locateInSourceRoots = (roots, className, methodName) => {
222
+ if (!roots || roots.length === 0 || !className) return null;
223
+ const cacheKey = `${roots.join("|")}:${className}`;
224
+ if (!classFileCache.has(cacheKey)) {
225
+ let found = null;
226
+ const pattern = new RegExp(`\\bclass\\s+${className}\\b`);
227
+ const walk = (directory) => {
228
+ if (found) return;
229
+ let entries = [];
230
+ try { entries = fs.readdirSync(directory, { withFileTypes: true }); } catch { return; }
231
+ for (const entry of entries) {
232
+ if (found) return;
233
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
234
+ const full = path.join(directory, entry.name);
235
+ if (entry.isDirectory()) walk(full);
236
+ else if (/\.(ts|tsx|js|mjs)$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
237
+ const text = fs.readFileSync(full, "utf8");
238
+ if (pattern.test(text)) found = { file: full, text };
239
+ }
240
+ }
241
+ };
242
+ for (const root of roots) walk(root);
243
+ classFileCache.set(cacheKey, found);
244
+ }
245
+ const found = classFileCache.get(cacheKey);
246
+ if (!found) return null;
247
+ const lines = found.text.split("\n");
248
+ const classLine = lines.findIndex((text) => new RegExp(`\\bclass\\s+${className}\\b`).test(text));
249
+ let line = classLine;
250
+ if (methodName) {
251
+ const bare = methodName.replace(/^(get|set|async|static)\s+/, "");
252
+ const methodPattern = new RegExp(`^\\s*(public |protected |private |static |async |readonly |override |get |set )*${bare.replace(/[$]/g, "\\$")}\\s*[(<]`);
253
+ const methodLine = lines.findIndex((text, lineIndex) => lineIndex > classLine && methodPattern.test(text));
254
+ if (methodLine >= 0) line = methodLine;
255
+ }
256
+ return { file: found.file, line: line + 1 };
257
+ };
258
+
259
+ /**
260
+ * Symbolizes one V8 call frame.
261
+ * @param {{functionName: string, scriptId: string, url: string, lineNumber: number, columnNumber: number}} callFrame
262
+ * @returns {{key: string, name: string, owner: string, file: string|null, line: number|null, url: string, native: boolean, special: string|null}}
263
+ */
264
+ const frame = (callFrame) => {
265
+ const cacheKey = `${callFrame.scriptId}:${callFrame.lineNumber}:${callFrame.columnNumber}:${callFrame.functionName}`;
266
+ if (frameCache.has(cacheKey)) return frameCache.get(cacheKey);
267
+ const special = SPECIAL_FRAMES[callFrame.functionName];
268
+ let result;
269
+ if (special && !callFrame.url) {
270
+ result = { key: special, name: callFrame.functionName, owner: special, file: null, line: null, url: "", native: false, special };
271
+ } else if (!callFrame.url) {
272
+ const name = callFrame.functionName || "(native)";
273
+ result = { key: `native|${name}`, name, owner: "native", file: null, line: null, url: "", native: true, special: null };
274
+ } else {
275
+ result = symbolizeScriptFrame(callFrame);
276
+ }
277
+ frameCache.set(cacheKey, result);
278
+ return result;
279
+ };
280
+
281
+ /** Symbolizes a frame that belongs to a script (has a URL). */
282
+ const symbolizeScriptFrame = (callFrame) => {
283
+ const url = callFrame.url;
284
+ let owner = ownerOfUrl(url);
285
+ const rule = ownerRules.find((candidate) => candidate.pattern.test(url));
286
+ const functionName = callFrame.functionName || "";
287
+ let file = urlToFile(url.replace(/\?.*$/, ""));
288
+ let line = callFrame.lineNumber + 1;
289
+ let className = null;
290
+ const consumer = consumerFor(callFrame.scriptId);
291
+ let mapped = false;
292
+ if (consumer && callFrame.lineNumber >= 0) {
293
+ const original = consumer.originalPositionFor({ line: callFrame.lineNumber + 1, column: Math.max(0, callFrame.columnNumber) });
294
+ if (original && original.source) {
295
+ const sourcePath = resolveMappedSource(url, original.source);
296
+ const content = consumer.sourceContentFor(original.source, true);
297
+ if (sourcePath || content) {
298
+ if (sourcePath) file = sourcePath;
299
+ line = original.line;
300
+ mapped = true;
301
+ const text = content || (sourcePath ? safeRead(sourcePath) : null);
302
+ className = enclosingClass(`src:${sourcePath || original.source}`, text, original.line - 1, original.column || 0);
303
+ }
304
+ }
305
+ }
306
+ // Config rules are authoritative; otherwise the mapped original file decides (its URL can be a generic bundle).
307
+ if (mapped && file && !rule) owner = ownerOfSourcePath(file) || owner;
308
+ if (!mapped && callFrame.lineNumber >= 0) {
309
+ className = enclosingClass(`script:${callFrame.scriptId}`, scriptText(callFrame.scriptId), callFrame.lineNumber, Math.max(0, callFrame.columnNumber));
310
+ }
311
+ if (!mapped && rule && rule.sourceRoots) {
312
+ const located = locateInSourceRoots(rule.sourceRoots, className, functionName);
313
+ if (located) { file = located.file; line = located.line; }
314
+ }
315
+ const bareName = functionName || "(anonymous)";
316
+ const name = className && functionName && functionName !== className ? `${className}.${functionName}` : (className && !functionName ? `${className} (anonymous fn)` : bareName);
317
+ const shortUrl = url.replace(/^https?:\/\/[^/]+/, "").replace(/\?.*$/, "");
318
+ const where = file || shortUrl;
319
+ return { key: `${owner}|${where}|${line}|${name}`, name, owner, file, line, url: shortUrl, native: false, special: null, wasm: /\.wasm$/.test(shortUrl) };
320
+ };
321
+
322
+ /** Resolves a source-map `sources` entry to a local file. */
323
+ const resolveMappedSource = (scriptUrl, source) => {
324
+ if (path.isAbsolute(source) && fs.existsSync(source)) return source;
325
+ try {
326
+ const resolved = new URL(source, scriptUrl).href;
327
+ return urlToFile(resolved);
328
+ } catch {
329
+ return null;
330
+ }
331
+ };
332
+
333
+ const safeRead = (file) => {
334
+ const key = `file:${file}`;
335
+ if (textCache.has(key)) return textCache.get(key);
336
+ let text = null;
337
+ try { text = fs.readFileSync(file, "utf8"); } catch { text = null; }
338
+ textCache.set(key, text);
339
+ return text;
340
+ };
341
+
342
+ /**
343
+ * Maps a generated 1-based line of a script (a CPU profile `positionTicks` line) to the original file and line.
344
+ * @returns {{file: string|null, line: number}} the location
345
+ */
346
+ const line = (scriptId, url, generatedLine) => {
347
+ const consumer = consumerFor(scriptId);
348
+ if (consumer) {
349
+ const original = consumer.originalPositionFor({ line: generatedLine, column: 0, bias: sourceMap.SourceMapConsumer.LEAST_UPPER_BOUND });
350
+ if (original && original.source && original.line) return { file: resolveMappedSource(url, original.source), line: original.line };
351
+ }
352
+ return { file: urlToFile(url.replace(/\?.*$/, "")), line: generatedLine };
353
+ };
354
+
355
+ return { frame, line, ownerOf: ownerOfUrl, labels, yours, scripts, readFile: safeRead };
356
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "bt-profile-tools",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "Capture, analysis and report tools for the bt-profile skill. Installed into <project>/.agents/profile/.tools, never into the project's own package.json.",
6
+ "dependencies": {
7
+ "puppeteer-core": "23.11.1",
8
+ "source-map-js": "1.2.1"
9
+ }
10
+ }