profiler-md 0.2.0 → 0.3.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.
- package/dist/cli/index.mjs +1923 -1485
- package/dist/index.d.mts +256 -23
- package/dist/index.js +2 -2
- package/docs/formats/jsc-heap-snapshot.md +13 -0
- package/docs/formats/webkit-timeline-recording.md +9 -0
- package/docs/languages/c.md +1 -1
- package/docs/languages/go.md +2 -2
- package/docs/languages/javascript.md +34 -0
- package/examples/bun.cpuprofile.md +67 -89
- package/examples/deno.cpuprofile.md +2 -9
- package/examples/jsc-heap-snapshot.json.md +509 -0
- package/examples/node.cpuprofile.md +59 -73
- package/examples/node.heapprofile.md +174 -219
- package/examples/node.heapsnapshot.md +250 -248
- package/examples/node.pprof.md +33 -42
- package/examples/node.speedscope.json.md +57 -65
- package/examples/{rust1.pprof.md → rust.pprof.md} +31 -34
- package/examples/webkit-timeline-recording.json.md +434 -0
- package/package.json +13 -4
- package/readme.md +132 -70
- package/examples/rust2.pprof.md +0 -480
package/dist/cli/index.mjs
CHANGED
|
@@ -1,21 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
2
|
+
import { formatDocPage, getDocPage } from "@optique/core";
|
|
3
|
+
import { object, or } from "@optique/core/constructs";
|
|
4
|
+
import { message, text } from "@optique/core/message";
|
|
5
|
+
import { map, multiple, optional, withDefault } from "@optique/core/modifiers";
|
|
6
|
+
import { argument, flag, option } from "@optique/core/primitives";
|
|
7
|
+
import { defineProgram } from "@optique/core/program";
|
|
8
|
+
import { choice, integer, string } from "@optique/core/valueparser";
|
|
9
|
+
import { path, run } from "@optique/run";
|
|
4
10
|
import { SourceMapConsumer } from "source-map-js";
|
|
11
|
+
import globals from "globals";
|
|
5
12
|
import plur from "plur";
|
|
6
13
|
import prettyBytes from "pretty-bytes";
|
|
7
14
|
import prettyMilliseconds from "pretty-ms";
|
|
15
|
+
import { JumboJSON } from "jumbo-json";
|
|
16
|
+
import { Profile } from "pprof-format";
|
|
8
17
|
import { glob, readFile } from "node:fs/promises";
|
|
9
18
|
import { Ansis } from "ansis";
|
|
10
|
-
import { createWriteStream } from "node:fs";
|
|
19
|
+
import { createWriteStream, openAsBlob } from "node:fs";
|
|
11
20
|
import { spawn } from "node:child_process";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
21
|
+
import { blob } from "node:stream/consumers";
|
|
22
|
+
import { pipeline } from "node:stream/promises";
|
|
23
|
+
import { createBrotliDecompress, createGunzip } from "node:zlib";
|
|
14
24
|
import { dirname, resolve } from "node:path";
|
|
15
25
|
import { pathToFileURL } from "node:url";
|
|
16
26
|
import convertSourceMap from "convert-source-map";
|
|
17
27
|
import picomatch from "picomatch";
|
|
18
28
|
|
|
29
|
+
//#region package.json
|
|
30
|
+
var name = "profiler-md";
|
|
31
|
+
var version = "0.3.0";
|
|
32
|
+
var description = "Converts performance profiles to human and LLM friendly Markdown.";
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
19
35
|
//#region src/helpers/array.ts
|
|
20
36
|
/**
|
|
21
37
|
* A {@link TypedArray} wrapper that's growable.
|
|
@@ -161,18 +177,29 @@ const sourceMapProfileLocation = (location, { cwd, sourceMaps }) => {
|
|
|
161
177
|
|
|
162
178
|
//#endregion
|
|
163
179
|
//#region src/options.ts
|
|
164
|
-
const normalizeProfileToMdOptions = ({ topN = 20,
|
|
180
|
+
const normalizeProfileToMdOptions = ({ topN = 20, categorizeEntry = defaultCategorizeEntry, showEntry = defaultShowEntry, cwd, sourceMaps } = {}) => {
|
|
165
181
|
if (cwd === void 0 && typeof process !== `undefined`) cwd = process.cwd();
|
|
166
182
|
if (cwd != null && !cwd.endsWith(`/`)) cwd = `${cwd}/`;
|
|
167
183
|
return {
|
|
168
184
|
topN,
|
|
169
|
-
|
|
170
|
-
|
|
185
|
+
categorizeEntry: cacheEntryFunction(categorizeEntry),
|
|
186
|
+
showEntry: cacheEntryPredicate(showEntry),
|
|
171
187
|
cwd: cwd ?? void 0,
|
|
172
188
|
sourceMaps: normalizeSourceMaps(sourceMaps ?? [])
|
|
173
189
|
};
|
|
174
190
|
};
|
|
175
191
|
const cacheEntryFunction = (func) => {
|
|
192
|
+
const cache = [];
|
|
193
|
+
return (entry) => {
|
|
194
|
+
const { id } = entry;
|
|
195
|
+
const cached = cache[id];
|
|
196
|
+
if (cached !== void 0) return cached;
|
|
197
|
+
const result = func(entry);
|
|
198
|
+
cache[id] = result;
|
|
199
|
+
return result;
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
const cacheEntryPredicate = (func) => {
|
|
176
203
|
const cache = new DynamicTypedArray(new Uint8Array(256));
|
|
177
204
|
return (entry) => {
|
|
178
205
|
const { id } = entry;
|
|
@@ -185,31 +212,59 @@ const cacheEntryFunction = (func) => {
|
|
|
185
212
|
};
|
|
186
213
|
};
|
|
187
214
|
/**
|
|
188
|
-
* Returns
|
|
215
|
+
* Returns an arbitrary category string for this entry.
|
|
189
216
|
*
|
|
190
|
-
*
|
|
217
|
+
* Categorizes into `ours`, `stdlib`, `third-party`, and a few other categories
|
|
218
|
+
* by default.
|
|
191
219
|
*/
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
if (
|
|
195
|
-
return
|
|
220
|
+
const defaultCategorizeEntry = (entry) => {
|
|
221
|
+
const { name, location } = entry;
|
|
222
|
+
if (name?.startsWith(`(`) && name.endsWith(`)`) && !name.startsWith(`(anonymous`)) return name.slice(1, -1);
|
|
223
|
+
if (name === `Garbage Collection`) return `garbage collector`;
|
|
224
|
+
else if (name?.startsWith(`RegExp: `)) return `regexp`;
|
|
225
|
+
if (!location || location.url.protocol === `node:`) return `stdlib`;
|
|
226
|
+
if (location.url.pathname.includes(`/node_modules/`)) return `third-party`;
|
|
227
|
+
return `ours`;
|
|
196
228
|
};
|
|
197
229
|
/**
|
|
198
|
-
* Returns whether the given entry
|
|
230
|
+
* Returns whether to include the given entry in the Markdown output.
|
|
231
|
+
*
|
|
232
|
+
* Excludes synthetic and external-private entries.
|
|
233
|
+
*/
|
|
234
|
+
const defaultShowEntry = (entry) => !isSyntheticEntry(entry) && !isExternalPrivateEntry(entry);
|
|
235
|
+
/**
|
|
236
|
+
* Returns true if the entry is a synthetic artifacts.
|
|
237
|
+
*
|
|
238
|
+
* These entries are artifacts generated by the profiler and don't correspond to
|
|
239
|
+
* something that actually exists in code or at runtime. For example, a
|
|
240
|
+
* synthetic `(root)` node is typically created for heap snapshots.
|
|
241
|
+
*/
|
|
242
|
+
const isSyntheticEntry = ({ name }) => name === `(root)` || name === `<root>` || name === `(module)`;
|
|
243
|
+
/**
|
|
244
|
+
* Returns true if the entry corresponds to an external function (`stdlib` or
|
|
245
|
+
* `third-party`) that's never directly called by `ours` code.
|
|
199
246
|
*
|
|
200
|
-
*
|
|
247
|
+
* These entries are typically implementation details of external code that your
|
|
248
|
+
* own code cannot directly call. Excluding these entries from the Markdown
|
|
249
|
+
* leaves only your code and the public API surface of stdlib and third-pary
|
|
250
|
+
* code.
|
|
201
251
|
*/
|
|
202
|
-
const
|
|
252
|
+
const isExternalPrivateEntry = (entry) => {
|
|
253
|
+
if (entry.type !== `function`) return false;
|
|
254
|
+
if (entry.category !== `stdlib` && entry.category !== `third-party`) return false;
|
|
255
|
+
for (const { caller } of entry.callerIdToMetrics.values()) if (caller.category === `ours`) return false;
|
|
256
|
+
return true;
|
|
257
|
+
};
|
|
203
258
|
|
|
204
259
|
//#endregion
|
|
205
260
|
//#region src/helpers/format.ts
|
|
206
261
|
const formatCount = (count, unit) => count.toLocaleString(`en-US`) + (unit ? ` ${plur(unit, count)}` : ``);
|
|
262
|
+
const formatMicroseconds = (microseconds) => microseconds >= 1e3 ? formatMilliseconds(microseconds / 1e3) : `${microseconds.toFixed(1)}µs`;
|
|
207
263
|
const formatMilliseconds = (milliseconds) => prettyMilliseconds(milliseconds, {
|
|
208
264
|
secondsDecimalDigits: 2,
|
|
209
265
|
millisecondsDecimalDigits: 1,
|
|
210
266
|
unitCount: 2
|
|
211
267
|
});
|
|
212
|
-
const formatMicrosecondsExact = (microseconds) => `${microseconds.toFixed(1)}µs`;
|
|
213
268
|
const formatBytes = (bytes) => prettyBytes(bytes, { nonBreakingSpace: true });
|
|
214
269
|
const formatPercent = (fraction) => `${(fraction * 100).toFixed(1)}%`;
|
|
215
270
|
const formatConjunction = (strings) => (conjunctionFormatter ??= new Intl.ListFormat(`en`, {
|
|
@@ -278,588 +333,1474 @@ const selectTopN = (values, topN, select) => {
|
|
|
278
333
|
};
|
|
279
334
|
|
|
280
335
|
//#endregion
|
|
281
|
-
//#region src/
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
#functionKey;
|
|
285
|
-
#functionInput;
|
|
286
|
-
#options;
|
|
287
|
-
#totalSampleCount;
|
|
288
|
-
#totalValues;
|
|
289
|
-
#categoryToMetrics;
|
|
290
|
-
#keyToCallStack;
|
|
291
|
-
#keyToFunction;
|
|
292
|
-
#idToFunction;
|
|
293
|
-
#functionIdToLastSeenSampleCount;
|
|
294
|
-
#frameIndexToFramePairKey;
|
|
295
|
-
constructor({ metrics, functionKey, functionInput }, options) {
|
|
296
|
-
this.#metrics = metrics;
|
|
297
|
-
this.#functionKey = functionKey;
|
|
298
|
-
this.#functionInput = functionInput;
|
|
299
|
-
this.#options = options;
|
|
300
|
-
this.#totalSampleCount = 0;
|
|
301
|
-
this.#totalValues = new Float64Array(this.#metrics.length);
|
|
302
|
-
this.#categoryToMetrics = /* @__PURE__ */ new Map();
|
|
303
|
-
this.#keyToCallStack = /* @__PURE__ */ new Map();
|
|
304
|
-
this.#keyToFunction = /* @__PURE__ */ new Map();
|
|
305
|
-
this.#idToFunction = [];
|
|
306
|
-
this.#functionIdToLastSeenSampleCount = new DynamicTypedArray(new Uint32Array(1));
|
|
307
|
-
this.#frameIndexToFramePairKey = new DynamicTypedArray(new Int32Array(64));
|
|
308
|
-
}
|
|
309
|
-
/** Adds a single profile sample. */
|
|
310
|
-
addSample({ values, nodes, line }) {
|
|
311
|
-
if (nodes.length === 0) return;
|
|
312
|
-
const callStack = this.#getOrCreateCallStack(nodes);
|
|
313
|
-
const callee = callStack.frames[0];
|
|
314
|
-
const caller = callStack.frames[1];
|
|
315
|
-
let categoryMetrics = this.#categoryToMetrics.get(callee.category);
|
|
316
|
-
if (!categoryMetrics) {
|
|
317
|
-
categoryMetrics = {
|
|
318
|
-
sampleCount: 0,
|
|
319
|
-
values: new Float64Array(this.#metrics.length)
|
|
320
|
-
};
|
|
321
|
-
this.#categoryToMetrics.set(callee.category, categoryMetrics);
|
|
322
|
-
}
|
|
323
|
-
let callerMetrics;
|
|
324
|
-
if (caller) {
|
|
325
|
-
callerMetrics = callee.callerIdToMetrics.get(caller.id);
|
|
326
|
-
if (!callerMetrics) {
|
|
327
|
-
callerMetrics = {
|
|
328
|
-
caller,
|
|
329
|
-
selfSampleCount: 0,
|
|
330
|
-
selfValues: new Float64Array(this.#metrics.length)
|
|
331
|
-
};
|
|
332
|
-
callee.callerIdToMetrics.set(caller.id, callerMetrics);
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
let lineMetrics;
|
|
336
|
-
if (line !== void 0) {
|
|
337
|
-
lineMetrics = callee.lineToMetrics.get(line);
|
|
338
|
-
if (!lineMetrics) {
|
|
339
|
-
lineMetrics = {
|
|
340
|
-
sampleCount: 0,
|
|
341
|
-
values: new Float64Array(this.#metrics.length)
|
|
342
|
-
};
|
|
343
|
-
callee.lineToMetrics.set(line, lineMetrics);
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
this.#totalSampleCount++;
|
|
347
|
-
categoryMetrics.sampleCount++;
|
|
348
|
-
callStack.selfSampleCount++;
|
|
349
|
-
callee.selfSampleCount++;
|
|
350
|
-
if (callerMetrics) callerMetrics.selfSampleCount++;
|
|
351
|
-
if (lineMetrics) lineMetrics.sampleCount++;
|
|
352
|
-
for (let i = 0; i < values.length; i++) {
|
|
353
|
-
this.#totalValues[i] += values[i];
|
|
354
|
-
categoryMetrics.values[i] += values[i];
|
|
355
|
-
callStack.selfValues[i] += values[i];
|
|
356
|
-
callee.selfValues[i] += values[i];
|
|
357
|
-
if (callerMetrics) callerMetrics.selfValues[i] += values[i];
|
|
358
|
-
if (lineMetrics) lineMetrics.values[i] += values[i];
|
|
359
|
-
}
|
|
360
|
-
const funcCount = this.#keyToFunction.size;
|
|
361
|
-
const functionIdToLastSeenSampleCount = this.#functionIdToLastSeenSampleCount.ensureCapacity(funcCount);
|
|
362
|
-
for (const func of callStack.frames) {
|
|
363
|
-
if (functionIdToLastSeenSampleCount[func.id] === this.#totalSampleCount) continue;
|
|
364
|
-
functionIdToLastSeenSampleCount[func.id] = this.#totalSampleCount;
|
|
365
|
-
func.totalSampleCount++;
|
|
366
|
-
for (let i = 0; i < values.length; i++) func.totalValues[i] += values[i];
|
|
367
|
-
}
|
|
368
|
-
const maxFramePairCount = callStack.frames.length - 1;
|
|
369
|
-
const frameIndexToFramePairKey = this.#frameIndexToFramePairKey.ensureCapacity(maxFramePairCount);
|
|
370
|
-
let seenFramePairCount = 0;
|
|
371
|
-
for (let i = 0; i < maxFramePairCount; i++) {
|
|
372
|
-
const callee = callStack.frames[i];
|
|
373
|
-
const caller = callStack.frames[i + 1];
|
|
374
|
-
const pairKey = caller.id * funcCount + callee.id;
|
|
375
|
-
let pairAlreadySeen = false;
|
|
376
|
-
for (let j = 0; j < seenFramePairCount; j++) if (frameIndexToFramePairKey[j] === pairKey) {
|
|
377
|
-
pairAlreadySeen = true;
|
|
378
|
-
break;
|
|
379
|
-
}
|
|
380
|
-
if (pairAlreadySeen) continue;
|
|
381
|
-
frameIndexToFramePairKey[seenFramePairCount++] = pairKey;
|
|
382
|
-
let calleeMetrics = caller.calleeIdToMetrics.get(callee.id);
|
|
383
|
-
if (!calleeMetrics) {
|
|
384
|
-
calleeMetrics = {
|
|
385
|
-
callee,
|
|
386
|
-
totalSampleCount: 0,
|
|
387
|
-
totalValues: new Float64Array(this.#metrics.length)
|
|
388
|
-
};
|
|
389
|
-
caller.calleeIdToMetrics.set(callee.id, calleeMetrics);
|
|
390
|
-
}
|
|
391
|
-
calleeMetrics.totalSampleCount++;
|
|
392
|
-
for (let i = 0; i < values.length; i++) calleeMetrics.totalValues[i] += values[i];
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
addLineMetrics({ node, lines }) {
|
|
396
|
-
const func = this.#getOrCreateFunction(node);
|
|
397
|
-
for (const { line, sampleCount, values } of lines) {
|
|
398
|
-
let lineMetrics = func.lineToMetrics.get(line);
|
|
399
|
-
if (!lineMetrics) {
|
|
400
|
-
lineMetrics = {
|
|
401
|
-
sampleCount: 0,
|
|
402
|
-
values: new Float64Array(this.#metrics.length)
|
|
403
|
-
};
|
|
404
|
-
func.lineToMetrics.set(line, lineMetrics);
|
|
405
|
-
}
|
|
406
|
-
lineMetrics.sampleCount += sampleCount;
|
|
407
|
-
for (let i = 0; i < values.length; i++) lineMetrics.values[i] += values[i];
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
#getOrCreateCallStack(nodes) {
|
|
411
|
-
const frames = nodes.map((node) => this.#getOrCreateFunction(node));
|
|
412
|
-
const key = frames.map((frame) => frame.id).join(`,`);
|
|
413
|
-
let callStack = this.#keyToCallStack.get(key);
|
|
414
|
-
if (callStack) return callStack;
|
|
415
|
-
callStack = {
|
|
416
|
-
frames,
|
|
417
|
-
selfSampleCount: 0,
|
|
418
|
-
selfValues: new Float64Array(this.#metrics.length)
|
|
419
|
-
};
|
|
420
|
-
this.#keyToCallStack.set(key, callStack);
|
|
421
|
-
return callStack;
|
|
422
|
-
}
|
|
423
|
-
#getOrCreateFunction(node) {
|
|
424
|
-
let func = this.#idToFunction[node.id];
|
|
425
|
-
if (func) return func;
|
|
426
|
-
const key = this.#functionKey(node);
|
|
427
|
-
func = this.#keyToFunction.get(key);
|
|
428
|
-
if (func) {
|
|
429
|
-
this.#idToFunction[node.id] = func;
|
|
430
|
-
return func;
|
|
431
|
-
}
|
|
432
|
-
const { name: nameInput, location: locationInput } = this.#functionInput(node);
|
|
433
|
-
const entry = {
|
|
434
|
-
id: this.#keyToFunction.size,
|
|
435
|
-
name: nameInput || `(anonymous)`,
|
|
436
|
-
location: locationInput ? makeProfileLocation(locationInput) : void 0
|
|
437
|
-
};
|
|
438
|
-
func = {
|
|
439
|
-
...entry,
|
|
440
|
-
category: categorizeFunction(entry, this.#options),
|
|
441
|
-
selfSampleCount: 0,
|
|
442
|
-
totalSampleCount: 0,
|
|
443
|
-
selfValues: new Float64Array(this.#metrics.length),
|
|
444
|
-
totalValues: new Float64Array(this.#metrics.length),
|
|
445
|
-
lineToMetrics: /* @__PURE__ */ new Map(),
|
|
446
|
-
callerIdToMetrics: /* @__PURE__ */ new Map(),
|
|
447
|
-
calleeIdToMetrics: /* @__PURE__ */ new Map()
|
|
448
|
-
};
|
|
449
|
-
this.#idToFunction[node.id] = func;
|
|
450
|
-
this.#keyToFunction.set(key, func);
|
|
451
|
-
return func;
|
|
452
|
-
}
|
|
453
|
-
build() {
|
|
454
|
-
const samplingIntervals = new Float64Array(this.#metrics.length);
|
|
455
|
-
for (let i = 0; i < samplingIntervals.length; i++) samplingIntervals[i] = this.#totalValues[i] / this.#totalSampleCount;
|
|
456
|
-
const functions = [...this.#keyToFunction.values()];
|
|
457
|
-
const callStacks = [...this.#keyToCallStack.values()];
|
|
458
|
-
return {
|
|
459
|
-
metrics: this.#metrics,
|
|
460
|
-
totalSampleCount: this.#totalSampleCount,
|
|
461
|
-
totalValues: this.#totalValues,
|
|
462
|
-
samplingIntervals,
|
|
463
|
-
categoryToMetrics: this.#categoryToMetrics,
|
|
464
|
-
functions,
|
|
465
|
-
callStacks
|
|
466
|
-
};
|
|
467
|
-
}
|
|
468
|
-
};
|
|
469
|
-
const categorizeFunction = (entry, { isThirdPartyEntry }) => {
|
|
470
|
-
const { name, location } = entry;
|
|
471
|
-
if (name.startsWith(`(`) && name.endsWith(`)`) && !name.startsWith(`(anonymous`)) return name.slice(1, -1);
|
|
472
|
-
if (name.startsWith(`RegExp: `)) return `regexp`;
|
|
473
|
-
if (!location || location.url.protocol === `node:`) return `native`;
|
|
474
|
-
return isThirdPartyEntry(entry) ? `third-party` : `ours`;
|
|
475
|
-
};
|
|
476
|
-
/**
|
|
477
|
-
* Returns the list of callers of {@link callStacks} that is the longest common
|
|
478
|
-
* suffix of their frames, except it never returns a call stack as long as one
|
|
479
|
-
* of the input call stacks.
|
|
480
|
-
*
|
|
481
|
-
* This behavior is so that it's safe to remove that suffix from any of the call
|
|
482
|
-
* stacks and end up with a non-empty call stack to render.
|
|
483
|
-
*/
|
|
484
|
-
const findCommonCallStack = (callStacks) => {
|
|
485
|
-
if (callStacks.length <= 1) return [];
|
|
486
|
-
const minLength = Math.min(...callStacks.map((cs) => cs.frames.length));
|
|
487
|
-
const firstFrames = callStacks[0].frames;
|
|
488
|
-
let suffixLength = 0;
|
|
489
|
-
for (let i = 1; i < minLength; i++) {
|
|
490
|
-
const suffix = firstFrames.slice(-i).map((frame) => frame.id);
|
|
491
|
-
if (callStacks.every((callStack) => callStack.frames.slice(-i).every((frame, j) => frame.id === suffix[j]))) suffixLength = i;
|
|
492
|
-
else break;
|
|
493
|
-
}
|
|
494
|
-
return suffixLength > 0 ? firstFrames.slice(-suffixLength) : [];
|
|
495
|
-
};
|
|
496
|
-
|
|
497
|
-
//#endregion
|
|
498
|
-
//#region src/profile/format.ts
|
|
499
|
-
const formatProfile = (profile, options) => {
|
|
500
|
-
const headingLevel = 1;
|
|
336
|
+
//#region src/snapshot/format.ts
|
|
337
|
+
const formatHeapSnapshot = (snapshot, options) => {
|
|
338
|
+
const hasLocation = snapshot.constructors.some((constructor) => constructor.location) || snapshot.closures.some((closure) => closure.location);
|
|
501
339
|
return `${[
|
|
502
|
-
formatHeading(
|
|
503
|
-
formatOverallSummary$1(
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
})
|
|
340
|
+
formatHeading(1, `Heap snapshot`),
|
|
341
|
+
...formatOverallSummary$1(snapshot),
|
|
342
|
+
...formatLargestConstructors(snapshot, hasLocation, options),
|
|
343
|
+
...formatLargestClosures(snapshot, hasLocation, options),
|
|
344
|
+
...formatLargestStrings(snapshot, options)
|
|
508
345
|
].join(`\n\n`)}\n`;
|
|
509
346
|
};
|
|
510
|
-
const
|
|
511
|
-
const
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
case `size`: return `heap`;
|
|
515
|
-
case `custom`: return metric.name;
|
|
516
|
-
}
|
|
517
|
-
};
|
|
518
|
-
const formatOverallSummary$1 = (profile) => `${formatSummaryLine(profile)}\n\n${formatCategoryTable(profile)}`;
|
|
519
|
-
const formatSummaryLine = ({ metrics, totalSampleCount, totalValues, samplingIntervals }) => {
|
|
520
|
-
const totalsSummary = capitalizeFirst(formatConjunction(metrics.map((metric, index) => `${metricPastTenseVerb(metric)} ${formatValue(totalValues[index], metric)}`)));
|
|
521
|
-
const samplingIntervalsSummary = `(${formatConjunction(Array.from(samplingIntervals, (interval, index) => formatSamplingInterval(interval, metrics[index])))} per sample)`;
|
|
522
|
-
return `${totalsSummary} over ${formatCount(totalSampleCount, `sample`)} ${samplingIntervalsSummary}.`;
|
|
523
|
-
};
|
|
524
|
-
const formatCategoryTable = ({ metrics, totalValues, categoryToMetrics }) => {
|
|
525
|
-
const hottestCategories = [...categoryToMetrics].sort(([, metrics1], [, metrics2]) => metrics2.values[0] - metrics1.values[0]);
|
|
526
|
-
return formatTable([
|
|
347
|
+
const formatOverallSummary$1 = ({ totalSize, nodeCount, edgeCount, nodeCategoryToStats }) => {
|
|
348
|
+
const hottestObjectCategories = [...nodeCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
|
|
349
|
+
if (hottestObjectCategories.length === 0) return [];
|
|
350
|
+
return [`Allocated ${formatBytes(totalSize)} across ${formatCount(nodeCount)} nodes and ${formatCount(edgeCount)} edges.`, formatTable([
|
|
527
351
|
`Category`,
|
|
528
352
|
{
|
|
529
353
|
content: `%`,
|
|
530
354
|
align: `right`
|
|
531
355
|
},
|
|
532
|
-
|
|
533
|
-
content:
|
|
356
|
+
{
|
|
357
|
+
content: `Size`,
|
|
534
358
|
align: `right`
|
|
535
|
-
}
|
|
359
|
+
},
|
|
536
360
|
{
|
|
537
|
-
content: `
|
|
361
|
+
content: `Nodes`,
|
|
538
362
|
align: `right`
|
|
539
363
|
}
|
|
540
|
-
],
|
|
364
|
+
], hottestObjectCategories.map(([category, { size, nodeCount: objectCount }]) => [
|
|
541
365
|
category,
|
|
542
|
-
formatPercent(
|
|
543
|
-
|
|
544
|
-
formatCount(
|
|
545
|
-
]));
|
|
546
|
-
};
|
|
547
|
-
const metricPastTenseVerb = (metric) => {
|
|
548
|
-
switch (metric.type) {
|
|
549
|
-
case `time`: return `took`;
|
|
550
|
-
case `size`: return `allocated`;
|
|
551
|
-
case `custom`: return `recorded`;
|
|
552
|
-
}
|
|
366
|
+
formatPercent(size / totalSize),
|
|
367
|
+
formatBytes(size),
|
|
368
|
+
formatCount(objectCount)
|
|
369
|
+
]))];
|
|
553
370
|
};
|
|
554
|
-
const
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
case `custom`: return formatCount(samplingInterval, metric.unit);
|
|
559
|
-
}
|
|
371
|
+
const formatLargestConstructors = (snapshot, hasLocation, options) => {
|
|
372
|
+
const largestConstructorsSections = [...formatLargestSelfSizeConstructors(snapshot, hasLocation, options), ...formatLargestRetainedSizeConstructors(snapshot, hasLocation, options)];
|
|
373
|
+
if (largestConstructorsSections.length === 0) return [];
|
|
374
|
+
return [formatHeading(2, `Largest constructors`), ...largestConstructorsSections];
|
|
560
375
|
};
|
|
561
|
-
const
|
|
562
|
-
const
|
|
563
|
-
|
|
564
|
-
if (
|
|
565
|
-
|
|
566
|
-
sectionOptions = {
|
|
567
|
-
...options,
|
|
568
|
-
headingLevel: options.headingLevel + 1
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
const callStacksSection = formatHottestCallStacks(index, profile, sectionOptions);
|
|
572
|
-
return [
|
|
573
|
-
...sections,
|
|
574
|
-
formatHottestFunctions(index, profile, sectionOptions),
|
|
575
|
-
...callStacksSection === void 0 ? [] : [callStacksSection]
|
|
576
|
-
];
|
|
577
|
-
}).join(`\n\n`);
|
|
578
|
-
const formatHottestFunctions = (metricIndex, profile, options) => {
|
|
579
|
-
const subsectionOptions = {
|
|
580
|
-
...options,
|
|
581
|
-
headingLevel: options.headingLevel + 1
|
|
582
|
-
};
|
|
583
|
-
return [
|
|
584
|
-
formatHeading(options.headingLevel, `Hottest functions`),
|
|
585
|
-
formatHottestSelfFunctions(metricIndex, profile, subsectionOptions),
|
|
586
|
-
formatHottestTotalFunctions(metricIndex, profile, subsectionOptions)
|
|
587
|
-
].join(`\n\n`);
|
|
588
|
-
};
|
|
589
|
-
const formatHottestSelfFunctions = (metricIndex, profile, options) => {
|
|
590
|
-
const hottestFunctions = selectTopN(profile.functions.filter((func) => options.includeEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (func) => func.selfValues[metricIndex]);
|
|
591
|
-
const subsectionOptions = {
|
|
592
|
-
...options,
|
|
593
|
-
headingLevel: options.headingLevel + 2
|
|
594
|
-
};
|
|
595
|
-
const hottestLinesSections = hottestFunctions.filter((func) => func.lineToMetrics.size > 0).map((func) => formatHottestLines(metricIndex, func, profile, subsectionOptions));
|
|
596
|
-
const hottestCallersSections = hottestFunctions.map((func) => formatHottestCallers(metricIndex, func, profile, subsectionOptions)).filter((section) => section !== void 0);
|
|
597
|
-
const metric = profile.metrics[metricIndex];
|
|
598
|
-
const metricName = metricDisplayName(metric);
|
|
376
|
+
const formatLargestSelfSizeConstructors = (snapshot, hasLocation, options) => {
|
|
377
|
+
const { totalSize, constructors } = snapshot;
|
|
378
|
+
const largestConstructors = selectTopN(constructors.filter(options.showEntry), options.topN, (constructor) => constructor.selfSize);
|
|
379
|
+
if (largestConstructors.length === 0) return [];
|
|
380
|
+
const largestInstanceSections = largestConstructors.flatMap((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, hasLocation, options));
|
|
599
381
|
return [
|
|
600
|
-
formatHeading(
|
|
601
|
-
`
|
|
382
|
+
formatHeading(3, `Self size`),
|
|
383
|
+
`Constructors ranked by bytes allocated for their instances, excluding nodes kept reachable by them.`,
|
|
602
384
|
formatTable([
|
|
603
385
|
{
|
|
604
386
|
content: `%`,
|
|
605
387
|
align: `right`
|
|
606
388
|
},
|
|
607
389
|
{
|
|
608
|
-
content:
|
|
390
|
+
content: `Size`,
|
|
609
391
|
align: `right`
|
|
610
392
|
},
|
|
611
393
|
{
|
|
612
|
-
content: `
|
|
394
|
+
content: `Instances`,
|
|
613
395
|
align: `right`
|
|
614
396
|
},
|
|
615
|
-
`
|
|
616
|
-
`Location`
|
|
617
|
-
],
|
|
618
|
-
formatPercent(
|
|
619
|
-
|
|
620
|
-
formatCount(
|
|
621
|
-
inlineCode(
|
|
622
|
-
formatProfileLocation(
|
|
397
|
+
`Constructor`,
|
|
398
|
+
...hasLocation ? [`Location`] : []
|
|
399
|
+
], largestConstructors.map((constructor) => [
|
|
400
|
+
formatPercent(constructor.selfSize / totalSize),
|
|
401
|
+
formatBytes(constructor.selfSize),
|
|
402
|
+
formatCount(constructor.instances.length),
|
|
403
|
+
inlineCode(constructor.name),
|
|
404
|
+
...hasLocation ? [formatProfileLocation(constructor.location, options)] : []
|
|
623
405
|
])),
|
|
624
|
-
...
|
|
625
|
-
...
|
|
626
|
-
|
|
627
|
-
...hottestCallersSections
|
|
628
|
-
].join(`\n\n`);
|
|
406
|
+
...largestInstanceSections.length > 0 ? [formatHeading(4, `Instances`), `Instances ranked by contribution to each constructor's self size.`] : [],
|
|
407
|
+
...largestInstanceSections
|
|
408
|
+
];
|
|
629
409
|
};
|
|
630
|
-
const
|
|
631
|
-
const
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
|
|
410
|
+
const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, hasLocation, options) => {
|
|
411
|
+
const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.selfSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.selfSize - group1.selfSize);
|
|
412
|
+
if (largestInstanceGroups.length === 0) return [];
|
|
413
|
+
return [formatHeading(5, `${inlineCode(constructor.name)}${hasLocation ? ` (${formatProfileLocation(constructor.location, options)})` : ``}`), formatTable([
|
|
635
414
|
{
|
|
636
415
|
content: `%`,
|
|
637
416
|
align: `right`
|
|
638
417
|
},
|
|
639
418
|
{
|
|
640
|
-
content:
|
|
419
|
+
content: `Size`,
|
|
641
420
|
align: `right`
|
|
642
421
|
},
|
|
643
422
|
{
|
|
644
|
-
content: `
|
|
423
|
+
content: `Instances`,
|
|
645
424
|
align: `right`
|
|
646
425
|
},
|
|
647
|
-
`
|
|
648
|
-
],
|
|
649
|
-
formatPercent(
|
|
650
|
-
|
|
651
|
-
formatCount(
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
line,
|
|
655
|
-
column: void 0
|
|
656
|
-
}, options) : String(line)
|
|
657
|
-
]))].join(`\n\n`);
|
|
426
|
+
`Path`
|
|
427
|
+
], largestInstanceGroups.map((group) => [
|
|
428
|
+
formatPercent(group.selfSize / constructor.selfSize),
|
|
429
|
+
formatBytes(group.selfSize),
|
|
430
|
+
formatCount(group.instanceCount),
|
|
431
|
+
inlineCode(group.retainerPath)
|
|
432
|
+
]))];
|
|
658
433
|
};
|
|
659
|
-
const
|
|
660
|
-
const
|
|
661
|
-
const
|
|
662
|
-
if (
|
|
663
|
-
const
|
|
664
|
-
return [
|
|
434
|
+
const formatLargestRetainedSizeConstructors = (snapshot, hasLocation, options) => {
|
|
435
|
+
const { totalSize, constructors } = snapshot;
|
|
436
|
+
const largestConstructors = selectTopN(constructors.filter(options.showEntry), options.topN, (constructor) => constructor.retainedSize);
|
|
437
|
+
if (largestConstructors.length === 0) return [];
|
|
438
|
+
const largestInstanceSections = largestConstructors.flatMap((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, hasLocation, options));
|
|
439
|
+
return [
|
|
440
|
+
formatHeading(3, `Retained size`),
|
|
441
|
+
`Constructors ranked by bytes allocated for their instances and all nodes that would be freed if their instances were garbage collected.`,
|
|
442
|
+
formatTable([
|
|
443
|
+
{
|
|
444
|
+
content: `%`,
|
|
445
|
+
align: `right`
|
|
446
|
+
},
|
|
447
|
+
{
|
|
448
|
+
content: `Size`,
|
|
449
|
+
align: `right`
|
|
450
|
+
},
|
|
451
|
+
{
|
|
452
|
+
content: `Instances`,
|
|
453
|
+
align: `right`
|
|
454
|
+
},
|
|
455
|
+
`Constructor`,
|
|
456
|
+
...hasLocation ? [`Location`] : []
|
|
457
|
+
], largestConstructors.map((constructor) => [
|
|
458
|
+
formatPercent(constructor.retainedSize / totalSize),
|
|
459
|
+
formatBytes(constructor.retainedSize),
|
|
460
|
+
formatCount(constructor.instances.length),
|
|
461
|
+
inlineCode(constructor.name),
|
|
462
|
+
...hasLocation ? [formatProfileLocation(constructor.location, options)] : []
|
|
463
|
+
])),
|
|
464
|
+
...largestInstanceSections.length > 0 ? [formatHeading(4, `Instances`), `Instances ranked by contribution to each constructor's retained size.`] : [],
|
|
465
|
+
...largestInstanceSections
|
|
466
|
+
];
|
|
467
|
+
};
|
|
468
|
+
const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, hasLocation, options) => {
|
|
469
|
+
const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.retainedSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.retainedSize - group1.retainedSize);
|
|
470
|
+
if (largestInstanceGroups.length === 0) return [];
|
|
471
|
+
return [formatHeading(5, `${inlineCode(constructor.name)}${hasLocation ? ` (${formatProfileLocation(constructor.location, options)})` : ``}`), formatTable([
|
|
665
472
|
{
|
|
666
473
|
content: `%`,
|
|
667
474
|
align: `right`
|
|
668
475
|
},
|
|
669
476
|
{
|
|
670
|
-
content:
|
|
477
|
+
content: `Size`,
|
|
671
478
|
align: `right`
|
|
672
479
|
},
|
|
673
480
|
{
|
|
674
|
-
content: `
|
|
481
|
+
content: `Instances`,
|
|
675
482
|
align: `right`
|
|
676
483
|
},
|
|
677
|
-
`
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
formatProfileLocation(caller.location, options)
|
|
685
|
-
]))].join(`\n\n`);
|
|
484
|
+
`Path`
|
|
485
|
+
], largestInstanceGroups.map((group) => [
|
|
486
|
+
formatPercent(group.retainedSize / constructor.retainedSize),
|
|
487
|
+
formatBytes(group.retainedSize),
|
|
488
|
+
formatCount(group.instanceCount),
|
|
489
|
+
inlineCode(group.retainerPath)
|
|
490
|
+
]))];
|
|
686
491
|
};
|
|
687
|
-
const
|
|
688
|
-
const
|
|
689
|
-
const
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
492
|
+
const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
|
|
493
|
+
const heap = new MaxHeap(instances, sizeOf);
|
|
494
|
+
const pathToGroup = /* @__PURE__ */ new Map();
|
|
495
|
+
while (heap.length > 0 && pathToGroup.size < topN) {
|
|
496
|
+
const instance = heap.pop();
|
|
497
|
+
const retainerPath = retainerPathOf(instance.id);
|
|
498
|
+
let group = pathToGroup.get(retainerPath);
|
|
499
|
+
if (!group) {
|
|
500
|
+
group = {
|
|
501
|
+
retainerPath,
|
|
502
|
+
instanceCount: 0,
|
|
503
|
+
selfSize: 0,
|
|
504
|
+
retainedSize: 0
|
|
505
|
+
};
|
|
506
|
+
pathToGroup.set(retainerPath, group);
|
|
507
|
+
}
|
|
508
|
+
group.instanceCount++;
|
|
509
|
+
group.selfSize += instance.selfSize;
|
|
510
|
+
group.retainedSize += instance.retainedSize;
|
|
511
|
+
}
|
|
512
|
+
return [...pathToGroup.values()];
|
|
513
|
+
};
|
|
514
|
+
const formatLargestClosures = (snapshot, hasLocation, options) => {
|
|
515
|
+
const { totalSize, closures, retainerPathOf } = snapshot;
|
|
516
|
+
const largestClosures = selectTopN(closures.filter((closure) => options.showEntry({
|
|
517
|
+
...closure,
|
|
518
|
+
id: closure.largestInstanceId
|
|
519
|
+
})), options.topN, (closure) => closure.retainedSize);
|
|
520
|
+
if (largestClosures.length === 0) return [];
|
|
521
|
+
const retainedSections = largestClosures.flatMap((closure) => formatClosureRetainedObjects(closure, snapshot, hasLocation, options));
|
|
697
522
|
return [
|
|
698
|
-
formatHeading(
|
|
699
|
-
`
|
|
523
|
+
formatHeading(2, `Largest closures`),
|
|
524
|
+
`Closures ranked by bytes that would be freed if the closure were garbage collected.`,
|
|
700
525
|
formatTable([
|
|
701
526
|
{
|
|
702
527
|
content: `%`,
|
|
703
528
|
align: `right`
|
|
704
529
|
},
|
|
705
530
|
{
|
|
706
|
-
content:
|
|
531
|
+
content: `Retained`,
|
|
707
532
|
align: `right`
|
|
708
533
|
},
|
|
709
534
|
{
|
|
710
|
-
content: `
|
|
535
|
+
content: `Instances`,
|
|
711
536
|
align: `right`
|
|
712
537
|
},
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
538
|
+
{
|
|
539
|
+
content: `Paths`,
|
|
540
|
+
align: `right`
|
|
541
|
+
},
|
|
542
|
+
`Name`,
|
|
543
|
+
...hasLocation ? [`Location`] : [],
|
|
544
|
+
`Example path`
|
|
545
|
+
], largestClosures.map((closure) => [
|
|
546
|
+
formatPercent(closure.retainedSize / totalSize),
|
|
547
|
+
formatBytes(closure.retainedSize),
|
|
548
|
+
formatCount(closure.instanceIds.length),
|
|
549
|
+
formatCount(new Set(closure.instanceIds.map(retainerPathOf)).size),
|
|
550
|
+
inlineCode(closure.name),
|
|
551
|
+
...hasLocation ? [formatProfileLocation(closure.location, options)] : [],
|
|
552
|
+
inlineCode(retainerPathOf(closure.largestInstanceId))
|
|
721
553
|
])),
|
|
722
|
-
...
|
|
723
|
-
...
|
|
724
|
-
]
|
|
554
|
+
...retainedSections.length > 0 ? [formatHeading(3, `Retained`), `Nodes ranked by contribution to each closure's retained size.`] : [],
|
|
555
|
+
...retainedSections
|
|
556
|
+
];
|
|
725
557
|
};
|
|
726
|
-
const
|
|
727
|
-
const
|
|
728
|
-
const
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
558
|
+
const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, hasLocation, options) => {
|
|
559
|
+
const instanceIdToSeen = new DynamicTypedArray(new Uint8Array(256));
|
|
560
|
+
const allRetainedNodes = [];
|
|
561
|
+
for (const instanceId of closure.instanceIds) for (const node of retainedNodesOf(instanceId)) {
|
|
562
|
+
const seen = instanceIdToSeen.ensureCapacity(node.id + 1);
|
|
563
|
+
if (seen[node.id]) continue;
|
|
564
|
+
seen[node.id] = 1;
|
|
565
|
+
if (options.showEntry(node)) allRetainedNodes.push(node);
|
|
566
|
+
}
|
|
567
|
+
const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node) => node.selfSize);
|
|
568
|
+
if (retainedNodes.length === 0) return [];
|
|
569
|
+
return [formatHeading(4, `${inlineCode(closure.name)}${hasLocation ? ` (${formatProfileLocation(closure.location, options)})` : ``}`), formatTable([
|
|
733
570
|
{
|
|
734
571
|
content: `%`,
|
|
735
572
|
align: `right`
|
|
736
573
|
},
|
|
737
574
|
{
|
|
738
|
-
content:
|
|
739
|
-
align: `right`
|
|
740
|
-
},
|
|
741
|
-
{
|
|
742
|
-
content: `Samples`,
|
|
575
|
+
content: `Self`,
|
|
743
576
|
align: `right`
|
|
744
577
|
},
|
|
745
|
-
`
|
|
746
|
-
`
|
|
747
|
-
],
|
|
748
|
-
formatPercent(
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
inlineCode(
|
|
752
|
-
|
|
753
|
-
]))].join(`\n\n`);
|
|
578
|
+
`Name`,
|
|
579
|
+
`Path`
|
|
580
|
+
], retainedNodes.map((node) => [
|
|
581
|
+
formatPercent(node.selfSize / closure.retainedSize),
|
|
582
|
+
formatBytes(node.selfSize),
|
|
583
|
+
inlineCode(node.name || `(unknown)`),
|
|
584
|
+
inlineCode(retainerPathOf(node.id))
|
|
585
|
+
]))];
|
|
754
586
|
};
|
|
755
|
-
const
|
|
756
|
-
const
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
frames: callStack.frames.filter(options.includeEntry)
|
|
760
|
-
})).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack) => callStack.selfValues[metricIndex]);
|
|
761
|
-
if (hottestCallStacks.length === 0) return;
|
|
762
|
-
const metric = profile.metrics[metricIndex];
|
|
763
|
-
const metricName = metricDisplayName(metric);
|
|
764
|
-
const commonCallStack = findCommonCallStack(hottestCallStacks);
|
|
587
|
+
const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) => {
|
|
588
|
+
const largestStrings = selectTopN(strings, options.topN, (string) => string.selfSize);
|
|
589
|
+
if (largestStrings.length === 0) return [];
|
|
590
|
+
const hasValues = largestStrings.some((string) => string.name !== void 0);
|
|
765
591
|
return [
|
|
766
|
-
formatHeading(
|
|
767
|
-
`
|
|
768
|
-
...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack, options)}`] : [],
|
|
592
|
+
formatHeading(2, `Largest strings`),
|
|
593
|
+
`Strings ranked by bytes allocated for them.`,
|
|
769
594
|
formatTable([
|
|
770
595
|
{
|
|
771
596
|
content: `%`,
|
|
772
597
|
align: `right`
|
|
773
598
|
},
|
|
774
599
|
{
|
|
775
|
-
content:
|
|
776
|
-
align: `right`
|
|
777
|
-
},
|
|
778
|
-
{
|
|
779
|
-
content: `Samples`,
|
|
600
|
+
content: `Size`,
|
|
780
601
|
align: `right`
|
|
781
602
|
},
|
|
782
|
-
`
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
603
|
+
...hasValues ? [`Value`] : [],
|
|
604
|
+
`Path`
|
|
605
|
+
], largestStrings.map((string) => [
|
|
606
|
+
formatPercent(string.selfSize / totalSize),
|
|
607
|
+
formatBytes(string.selfSize),
|
|
608
|
+
...hasValues ? [inlineCode(string.name ?? `(unknown)`)] : [],
|
|
609
|
+
inlineCode(retainerPathOf(string.id))
|
|
788
610
|
]))
|
|
789
|
-
]
|
|
790
|
-
};
|
|
791
|
-
const formatCallStack = (nodes, options) => nodes.map((node, index) => {
|
|
792
|
-
const name = inlineCode(node.name);
|
|
793
|
-
if (!node.location) return name;
|
|
794
|
-
const previousHref = nodes[index - 1]?.location?.url.href;
|
|
795
|
-
if (!previousHref || node.location.url.href !== previousHref) return `${name} (${formatProfileLocation(node.location, options)})`;
|
|
796
|
-
const { line, column } = node.location;
|
|
797
|
-
if (line === void 0) return name;
|
|
798
|
-
return `${name} (${line}${column === void 0 ? `` : `:${column}`})`;
|
|
799
|
-
}).join(` ← `);
|
|
800
|
-
const metricPastParticipleVerbPhrase = (metric) => {
|
|
801
|
-
switch (metric.type) {
|
|
802
|
-
case `time`: return `time spent`;
|
|
803
|
-
case `size`: return `bytes allocated`;
|
|
804
|
-
case `custom`: return `${metricDisplayName(metric)} recorded`;
|
|
805
|
-
}
|
|
806
|
-
};
|
|
807
|
-
const metricDisplayName = (metric) => {
|
|
808
|
-
switch (metric.type) {
|
|
809
|
-
case `time`:
|
|
810
|
-
case `size`: return metric.type;
|
|
811
|
-
case `custom`: return metric.name;
|
|
812
|
-
}
|
|
611
|
+
];
|
|
813
612
|
};
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
613
|
+
|
|
614
|
+
//#endregion
|
|
615
|
+
//#region src/snapshot/graph.ts
|
|
616
|
+
/**
|
|
617
|
+
* Computes the immediate dominators of every node.
|
|
618
|
+
*
|
|
619
|
+
* Uses the Lengauer-Tarjan dominator tree algorithm.
|
|
620
|
+
*
|
|
621
|
+
* @see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
|
|
622
|
+
* @see https://www.cs.princeton.edu/courses/archive/fall03/cs528/handouts/a%20fast%20algorithm%20for%20finding.pdf
|
|
623
|
+
*/
|
|
624
|
+
const computeImmediateDominatorGraph = (nodeCount, { ordinalToSuccessorStartOffset, offsetToSuccessorOrdinal, ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal }) => {
|
|
625
|
+
const ordinalToImmediateDominatorOrdinal = new Int32Array(nodeCount).fill(-1);
|
|
626
|
+
const dfsIndexToOrdinal = new Int32Array(nodeCount);
|
|
627
|
+
const ordinalToParentOrdinal = new Int32Array(nodeCount).fill(-1);
|
|
628
|
+
const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
|
|
629
|
+
const ordinalToSemidominatorDfsIndex = new Int32Array(nodeCount);
|
|
630
|
+
ordinalToDfsIndex[0] = 0;
|
|
631
|
+
dfsIndexToOrdinal[0] = 0;
|
|
632
|
+
const dfsStackOrdinals = new Int32Array(nodeCount);
|
|
633
|
+
const dfsStackOffsets = new Int32Array(nodeCount);
|
|
634
|
+
dfsStackOffsets[0] = ordinalToSuccessorStartOffset[0];
|
|
635
|
+
let dfsIndex = 1;
|
|
636
|
+
let dfsStackSize = 1;
|
|
637
|
+
do {
|
|
638
|
+
const topOffset = dfsStackSize - 1;
|
|
639
|
+
const nodeOrdinal = dfsStackOrdinals[topOffset];
|
|
640
|
+
const nextOffset = dfsStackOffsets[topOffset];
|
|
641
|
+
if (nextOffset === ordinalToSuccessorStartOffset[nodeOrdinal + 1]) {
|
|
642
|
+
dfsStackSize--;
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
const childOrdinal = offsetToSuccessorOrdinal[nextOffset];
|
|
646
|
+
dfsStackOffsets[topOffset]++;
|
|
647
|
+
if (ordinalToDfsIndex[childOrdinal] !== -1) continue;
|
|
648
|
+
ordinalToParentOrdinal[childOrdinal] = nodeOrdinal;
|
|
649
|
+
ordinalToDfsIndex[childOrdinal] = dfsIndex;
|
|
650
|
+
ordinalToSemidominatorDfsIndex[childOrdinal] = dfsIndex;
|
|
651
|
+
dfsIndexToOrdinal[dfsIndex] = childOrdinal;
|
|
652
|
+
dfsIndex++;
|
|
653
|
+
dfsStackOrdinals[dfsStackSize] = childOrdinal;
|
|
654
|
+
dfsStackOffsets[dfsStackSize] = ordinalToSuccessorStartOffset[childOrdinal];
|
|
655
|
+
dfsStackSize++;
|
|
656
|
+
} while (dfsStackSize > 0);
|
|
657
|
+
const reachableCount = dfsIndex;
|
|
658
|
+
const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
|
|
659
|
+
const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
|
|
660
|
+
const ordinalToMinSemiAncestorOrdinal = new Int32Array(nodeCount);
|
|
661
|
+
for (let i = 0; i < nodeCount; i++) ordinalToMinSemiAncestorOrdinal[i] = i;
|
|
662
|
+
const compressAncestorPath = (startNodeOrdinal) => {
|
|
663
|
+
let pathLength = 0;
|
|
664
|
+
let nodeOrdinal = startNodeOrdinal;
|
|
665
|
+
while (ordinalToForestAncestorOrdinal[nodeOrdinal] !== -1 && ordinalToForestAncestorOrdinal[ordinalToForestAncestorOrdinal[nodeOrdinal]] !== -1) {
|
|
666
|
+
ancestorNodeOrdinalPath[pathLength++] = nodeOrdinal;
|
|
667
|
+
nodeOrdinal = ordinalToForestAncestorOrdinal[nodeOrdinal];
|
|
668
|
+
}
|
|
669
|
+
for (let pathIndex = pathLength - 1; pathIndex >= 0; pathIndex--) {
|
|
670
|
+
const pathNodeOrdinal = ancestorNodeOrdinalPath[pathIndex];
|
|
671
|
+
const ancestorOrdinal = ordinalToForestAncestorOrdinal[pathNodeOrdinal];
|
|
672
|
+
if (ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[ancestorOrdinal]] < ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal]]) ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal] = ordinalToMinSemiAncestorOrdinal[ancestorOrdinal];
|
|
673
|
+
ordinalToForestAncestorOrdinal[pathNodeOrdinal] = ordinalToForestAncestorOrdinal[ancestorOrdinal];
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
const minSemiAncestorOrdinal = (nodeOrdinal) => {
|
|
677
|
+
if (ordinalToForestAncestorOrdinal[nodeOrdinal] === -1) return nodeOrdinal;
|
|
678
|
+
compressAncestorPath(nodeOrdinal);
|
|
679
|
+
return ordinalToMinSemiAncestorOrdinal[nodeOrdinal];
|
|
680
|
+
};
|
|
681
|
+
const pendingHeadOrdinals = new Int32Array(nodeCount).fill(-1);
|
|
682
|
+
const pendingNextOrdinals = new Int32Array(nodeCount).fill(-1);
|
|
683
|
+
for (let dfsIndex = reachableCount - 1; dfsIndex >= 1; dfsIndex--) {
|
|
684
|
+
const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
|
|
685
|
+
const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
|
|
686
|
+
const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
|
|
687
|
+
for (let predecessorOffset = predecessorStartOffset; predecessorOffset < predecessorEndOffset; predecessorOffset++) {
|
|
688
|
+
const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
|
|
689
|
+
if (ordinalToDfsIndex[predecessorOrdinal] === -1) continue;
|
|
690
|
+
const minAncestorOrdinal = minSemiAncestorOrdinal(predecessorOrdinal);
|
|
691
|
+
if (ordinalToSemidominatorDfsIndex[minAncestorOrdinal] < ordinalToSemidominatorDfsIndex[nodeOrdinal]) ordinalToSemidominatorDfsIndex[nodeOrdinal] = ordinalToSemidominatorDfsIndex[minAncestorOrdinal];
|
|
692
|
+
}
|
|
693
|
+
const semiBucketOrdinal = dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]];
|
|
694
|
+
pendingNextOrdinals[nodeOrdinal] = pendingHeadOrdinals[semiBucketOrdinal];
|
|
695
|
+
pendingHeadOrdinals[semiBucketOrdinal] = nodeOrdinal;
|
|
696
|
+
ordinalToForestAncestorOrdinal[nodeOrdinal] = ordinalToParentOrdinal[nodeOrdinal];
|
|
697
|
+
const parentOrdinal = ordinalToParentOrdinal[nodeOrdinal];
|
|
698
|
+
let pendingOrdinal = pendingHeadOrdinals[parentOrdinal];
|
|
699
|
+
pendingHeadOrdinals[parentOrdinal] = -1;
|
|
700
|
+
while (pendingOrdinal !== -1) {
|
|
701
|
+
const nextPending = pendingNextOrdinals[pendingOrdinal];
|
|
702
|
+
const ancestorOrdinal = minSemiAncestorOrdinal(pendingOrdinal);
|
|
703
|
+
ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : parentOrdinal;
|
|
704
|
+
pendingOrdinal = nextPending;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
for (let dfsIndex = 1; dfsIndex < reachableCount; dfsIndex++) {
|
|
708
|
+
const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
|
|
709
|
+
if (ordinalToImmediateDominatorOrdinal[nodeOrdinal] !== dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]]) ordinalToImmediateDominatorOrdinal[nodeOrdinal] = ordinalToImmediateDominatorOrdinal[ordinalToImmediateDominatorOrdinal[nodeOrdinal]];
|
|
710
|
+
}
|
|
711
|
+
ordinalToImmediateDominatorOrdinal[0] = 0;
|
|
712
|
+
const dominatorOrdinalToDominateeCount = new Int32Array(nodeCount);
|
|
713
|
+
for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
714
|
+
const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
|
|
715
|
+
if (dominatorOrdinal !== -1) dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
|
|
716
|
+
}
|
|
717
|
+
const immediateDominateeOrdinalToStartOffset = new Int32Array(nodeCount + 1);
|
|
718
|
+
for (let offset = 0; offset < nodeCount; offset++) immediateDominateeOrdinalToStartOffset[offset + 1] = immediateDominateeOrdinalToStartOffset[offset] + dominatorOrdinalToDominateeCount[offset];
|
|
719
|
+
const offsetToImmediateDominateeOrdinal = new Int32Array(immediateDominateeOrdinalToStartOffset[nodeCount]);
|
|
720
|
+
dominatorOrdinalToDominateeCount.fill(0);
|
|
721
|
+
for (let nodeOrdinal = 1; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
722
|
+
const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
|
|
723
|
+
if (dominatorOrdinal !== -1) {
|
|
724
|
+
offsetToImmediateDominateeOrdinal[immediateDominateeOrdinalToStartOffset[dominatorOrdinal] + dominatorOrdinalToDominateeCount[dominatorOrdinal]] = nodeOrdinal;
|
|
725
|
+
dominatorOrdinalToDominateeCount[dominatorOrdinal]++;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
return {
|
|
729
|
+
dfsIndexToOrdinal,
|
|
730
|
+
ordinalToImmediateDominatorOrdinal,
|
|
731
|
+
immediateDominateeOrdinalToStartOffset,
|
|
732
|
+
offsetToImmediateDominateeOrdinal
|
|
733
|
+
};
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
//#endregion
|
|
737
|
+
//#region src/snapshot/retained.ts
|
|
738
|
+
const computeNodeOrdinalToRetainedSize = (nodes, nodeFieldCount, selfSizeOffset, { dfsIndexToOrdinal, ordinalToImmediateDominatorOrdinal }) => {
|
|
739
|
+
const nodeOrdinalToRetainedSize = new Float64Array(ordinalToImmediateDominatorOrdinal.length);
|
|
740
|
+
for (let nodeOrdinal = 0; nodeOrdinal < nodeOrdinalToRetainedSize.length; nodeOrdinal++) nodeOrdinalToRetainedSize[nodeOrdinal] = nodes[nodeOrdinal * nodeFieldCount + selfSizeOffset];
|
|
741
|
+
for (let dfsIndex = dfsIndexToOrdinal.length - 1; dfsIndex >= 1; dfsIndex--) {
|
|
742
|
+
const dominateeOrdinal = dfsIndexToOrdinal[dfsIndex];
|
|
743
|
+
nodeOrdinalToRetainedSize[ordinalToImmediateDominatorOrdinal[dominateeOrdinal]] += nodeOrdinalToRetainedSize[dominateeOrdinal];
|
|
744
|
+
}
|
|
745
|
+
return nodeOrdinalToRetainedSize;
|
|
746
|
+
};
|
|
747
|
+
/**
|
|
748
|
+
* Attributes retained sizes to categories of nodes without double-counting.
|
|
749
|
+
*
|
|
750
|
+
* Summing per-node retained sizes across all instances of a category
|
|
751
|
+
* over-counts when one instance dominates another from the same category (the
|
|
752
|
+
* dominated node's memory is already included in the dominator's retained
|
|
753
|
+
* size).
|
|
754
|
+
*
|
|
755
|
+
* This function correctly attributes by doing a DFS of the dominator tree and
|
|
756
|
+
* only crediting the outermost instance of each category on any root-to-leaf
|
|
757
|
+
* path. Inner instances are entirely contained within the outer one's retained
|
|
758
|
+
* set, so they add nothing.
|
|
759
|
+
*/
|
|
760
|
+
const attributeCategoryRetainedSizes = (nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToAggregatedNodeIndex, aggregatedNodes) => {
|
|
761
|
+
const nodeCount = nodeOrdinalToRetainedSize.length;
|
|
762
|
+
const categoryPathDepth = new Int32Array(aggregatedNodes.length);
|
|
763
|
+
const stack = new Int32Array(nodeCount * 2 + 1);
|
|
764
|
+
stack[0] = 0;
|
|
765
|
+
let topOffset = 1;
|
|
766
|
+
do {
|
|
767
|
+
const encodedNodeOrdinal = stack[--topOffset];
|
|
768
|
+
if (encodedNodeOrdinal < 0) {
|
|
769
|
+
const constructorIndex = nodeOrdinalToAggregatedNodeIndex[~encodedNodeOrdinal];
|
|
770
|
+
if (constructorIndex !== -1) categoryPathDepth[constructorIndex] = categoryPathDepth[constructorIndex] - 1;
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
const nodeOrdinal = encodedNodeOrdinal;
|
|
774
|
+
const aggregatedNodeIndex = nodeOrdinalToAggregatedNodeIndex[nodeOrdinal];
|
|
775
|
+
if (aggregatedNodeIndex !== -1) {
|
|
776
|
+
const depth = categoryPathDepth[aggregatedNodeIndex];
|
|
777
|
+
if (depth === 0) aggregatedNodes[aggregatedNodeIndex].retainedSize += nodeOrdinalToRetainedSize[nodeOrdinal];
|
|
778
|
+
categoryPathDepth[aggregatedNodeIndex] = depth + 1;
|
|
779
|
+
stack[topOffset++] = ~nodeOrdinal;
|
|
780
|
+
}
|
|
781
|
+
const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
|
|
782
|
+
const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
|
|
783
|
+
for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) stack[topOffset++] = offsetToImmediateDominateeOrdinal[offset];
|
|
784
|
+
} while (topOffset > 0);
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
//#endregion
|
|
788
|
+
//#region src/snapshot/aggregate.ts
|
|
789
|
+
var SnapshotAggregator = class {
|
|
790
|
+
#nodes;
|
|
791
|
+
#nodeCount;
|
|
792
|
+
#edgeCount;
|
|
793
|
+
#nodeFieldCount;
|
|
794
|
+
#nodeSelfSizeOffset;
|
|
795
|
+
#nodeAdjacencyGraph;
|
|
796
|
+
#formatEdgeLabel;
|
|
797
|
+
#formatNodeLabel;
|
|
798
|
+
#isInternalNode;
|
|
799
|
+
#totalSize = 0;
|
|
800
|
+
#nodeCategoryToStats = /* @__PURE__ */ new Map();
|
|
801
|
+
#immediateDominatorGraph;
|
|
802
|
+
#nodeOrdinalToRetainedSize;
|
|
803
|
+
#constructors = [];
|
|
804
|
+
#nameToConstructorIndex = /* @__PURE__ */ new Map();
|
|
805
|
+
#nodeOrdinalToConstructorIndex;
|
|
806
|
+
#closures = [];
|
|
807
|
+
#keyToClosureIndex = /* @__PURE__ */ new Map();
|
|
808
|
+
#nodeOrdinalToClosureIndex;
|
|
809
|
+
#strings = [];
|
|
810
|
+
constructor({ nodes, nodeCount, edgeCount, nodeFieldCount, nodeSelfSizeOffset, nodeAdjacencyGraph, formatEdgeLabel, formatNodeLabel, isInternalNode }) {
|
|
811
|
+
this.#nodes = nodes;
|
|
812
|
+
this.#nodeCount = nodeCount;
|
|
813
|
+
this.#edgeCount = edgeCount;
|
|
814
|
+
this.#nodeFieldCount = nodeFieldCount;
|
|
815
|
+
this.#nodeSelfSizeOffset = nodeSelfSizeOffset;
|
|
816
|
+
this.#nodeAdjacencyGraph = nodeAdjacencyGraph;
|
|
817
|
+
this.#formatEdgeLabel = formatEdgeLabel;
|
|
818
|
+
this.#formatNodeLabel = formatNodeLabel;
|
|
819
|
+
this.#isInternalNode = isInternalNode;
|
|
820
|
+
this.#immediateDominatorGraph = computeImmediateDominatorGraph(nodeCount, nodeAdjacencyGraph);
|
|
821
|
+
this.#nodeOrdinalToRetainedSize = computeNodeOrdinalToRetainedSize(nodes, nodeFieldCount, nodeSelfSizeOffset, this.#immediateDominatorGraph);
|
|
822
|
+
this.#nodeOrdinalToConstructorIndex = new Int32Array(nodeCount).fill(-1);
|
|
823
|
+
this.#nodeOrdinalToClosureIndex = new Int32Array(nodeCount).fill(-1);
|
|
824
|
+
}
|
|
825
|
+
addCategoryNode(nodeOrdinal, category) {
|
|
826
|
+
const selfSize = this.#selfSize(nodeOrdinal);
|
|
827
|
+
this.#totalSize += selfSize;
|
|
828
|
+
let stats = this.#nodeCategoryToStats.get(category);
|
|
829
|
+
if (!stats) {
|
|
830
|
+
stats = {
|
|
831
|
+
size: 0,
|
|
832
|
+
nodeCount: 0
|
|
833
|
+
};
|
|
834
|
+
this.#nodeCategoryToStats.set(category, stats);
|
|
835
|
+
}
|
|
836
|
+
stats.size += selfSize;
|
|
837
|
+
stats.nodeCount++;
|
|
838
|
+
}
|
|
839
|
+
addConstructorNode(nodeOrdinal, location) {
|
|
840
|
+
const name = this.#formatNodeLabel(nodeOrdinal);
|
|
841
|
+
const selfSize = this.#selfSize(nodeOrdinal);
|
|
842
|
+
const retainedSize = this.#nodeOrdinalToRetainedSize[nodeOrdinal];
|
|
843
|
+
let constructorIndex = this.#nameToConstructorIndex.get(name);
|
|
844
|
+
let constructor;
|
|
845
|
+
if (constructorIndex === void 0) {
|
|
846
|
+
constructorIndex = this.#constructors.length;
|
|
847
|
+
constructor = {
|
|
848
|
+
type: `node`,
|
|
849
|
+
id: nodeOrdinal,
|
|
850
|
+
name,
|
|
851
|
+
location,
|
|
852
|
+
selfSize: 0,
|
|
853
|
+
retainedSize: 0,
|
|
854
|
+
instances: []
|
|
855
|
+
};
|
|
856
|
+
this.#constructors.push(constructor);
|
|
857
|
+
this.#nameToConstructorIndex.set(name, constructorIndex);
|
|
858
|
+
} else {
|
|
859
|
+
constructor = this.#constructors[constructorIndex];
|
|
860
|
+
constructor.location ??= location;
|
|
861
|
+
}
|
|
862
|
+
constructor.selfSize += selfSize;
|
|
863
|
+
constructor.instances.push({
|
|
864
|
+
type: `node`,
|
|
865
|
+
id: nodeOrdinal,
|
|
866
|
+
name,
|
|
867
|
+
selfSize,
|
|
868
|
+
retainedSize,
|
|
869
|
+
location: constructor.location
|
|
870
|
+
});
|
|
871
|
+
this.#nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
|
|
872
|
+
}
|
|
873
|
+
addClosureNode(nodeOrdinal, location) {
|
|
874
|
+
const name = this.#formatNodeLabel(nodeOrdinal);
|
|
875
|
+
const key = location ? `${name}|${location.url.href}:${location.line}:${location.column}` : name;
|
|
876
|
+
const retainedSize = this.#nodeOrdinalToRetainedSize[nodeOrdinal];
|
|
877
|
+
let closureIndex = this.#keyToClosureIndex.get(key);
|
|
878
|
+
if (closureIndex === void 0) {
|
|
879
|
+
closureIndex = this.#closures.length;
|
|
880
|
+
this.#closures.push({
|
|
881
|
+
type: `node`,
|
|
882
|
+
id: nodeOrdinal,
|
|
883
|
+
name,
|
|
884
|
+
location,
|
|
885
|
+
selfSize: 0,
|
|
886
|
+
retainedSize: 0,
|
|
887
|
+
largestInstanceId: nodeOrdinal,
|
|
888
|
+
instanceIds: []
|
|
889
|
+
});
|
|
890
|
+
this.#keyToClosureIndex.set(key, closureIndex);
|
|
891
|
+
}
|
|
892
|
+
const closure = this.#closures[closureIndex];
|
|
893
|
+
closure.selfSize += this.#selfSize(nodeOrdinal);
|
|
894
|
+
closure.instanceIds.push(nodeOrdinal);
|
|
895
|
+
if (retainedSize > this.#nodeOrdinalToRetainedSize[closure.largestInstanceId]) closure.largestInstanceId = nodeOrdinal;
|
|
896
|
+
this.#nodeOrdinalToClosureIndex[nodeOrdinal] = closureIndex;
|
|
897
|
+
}
|
|
898
|
+
addStringNode(nodeOrdinal, name) {
|
|
899
|
+
const selfSize = this.#selfSize(nodeOrdinal);
|
|
900
|
+
this.#strings.push({
|
|
901
|
+
type: `node`,
|
|
902
|
+
id: nodeOrdinal,
|
|
903
|
+
name,
|
|
904
|
+
selfSize,
|
|
905
|
+
retainedSize: selfSize
|
|
906
|
+
});
|
|
907
|
+
}
|
|
908
|
+
#selfSize(nodeOrdinal) {
|
|
909
|
+
return this.#nodes[nodeOrdinal * this.#nodeFieldCount + this.#nodeSelfSizeOffset];
|
|
910
|
+
}
|
|
911
|
+
aggregate() {
|
|
912
|
+
attributeCategoryRetainedSizes(this.#nodeOrdinalToRetainedSize, this.#immediateDominatorGraph, this.#nodeOrdinalToConstructorIndex, this.#constructors);
|
|
913
|
+
attributeCategoryRetainedSizes(this.#nodeOrdinalToRetainedSize, this.#immediateDominatorGraph, this.#nodeOrdinalToClosureIndex, this.#closures);
|
|
914
|
+
return {
|
|
915
|
+
totalSize: this.#totalSize,
|
|
916
|
+
nodeCount: this.#nodeCount,
|
|
917
|
+
edgeCount: this.#edgeCount,
|
|
918
|
+
nodeCategoryToStats: this.#nodeCategoryToStats,
|
|
919
|
+
constructors: this.#constructors,
|
|
920
|
+
closures: this.#closures,
|
|
921
|
+
strings: this.#strings,
|
|
922
|
+
retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, this.#nodeAdjacencyGraph, this.#immediateDominatorGraph, this.#formatEdgeLabel, this.#isInternalNode),
|
|
923
|
+
retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, this.#immediateDominatorGraph, this.#nodeOrdinalToRetainedSize, this.#nodes, this.#nodeFieldCount, this.#nodeSelfSizeOffset, this.#formatNodeLabel, this.#isInternalNode)
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
};
|
|
927
|
+
const computeRetainerPath = (nodeOrdinal, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, { ordinalToImmediateDominatorOrdinal }, formatEdgeLabel, isInternalNode) => {
|
|
928
|
+
const hops = [];
|
|
929
|
+
while (true) {
|
|
930
|
+
const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
|
|
931
|
+
const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
|
|
932
|
+
if (predecessorStartOffset === predecessorEndOffset) break;
|
|
933
|
+
const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
|
|
934
|
+
let predecessorOffset = -1;
|
|
935
|
+
for (let offset = predecessorStartOffset; offset < predecessorEndOffset; offset++) if (offsetToPredecessorOrdinal[offset] === dominatorOrdinal) {
|
|
936
|
+
predecessorOffset = offset;
|
|
937
|
+
break;
|
|
938
|
+
}
|
|
939
|
+
if (predecessorOffset === -1) {
|
|
940
|
+
nodeOrdinal = dominatorOrdinal;
|
|
941
|
+
continue;
|
|
942
|
+
}
|
|
943
|
+
const edgeIndex = offsetToPredecessorEdgeIndex[predecessorOffset];
|
|
944
|
+
const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
|
|
945
|
+
hops.push({
|
|
946
|
+
label: formatEdgeLabel(predecessorOrdinal, edgeIndex),
|
|
947
|
+
internal: isInternalNode(predecessorOrdinal)
|
|
948
|
+
});
|
|
949
|
+
nodeOrdinal = predecessorOrdinal;
|
|
950
|
+
}
|
|
951
|
+
while (hops.at(-1)?.internal) hops.pop();
|
|
952
|
+
if (hops.length === 0) return `(GC root)`;
|
|
953
|
+
return hops.map((hop) => hop.label).join(` ← `);
|
|
954
|
+
};
|
|
955
|
+
const computeRetainedNodes = (nodeOrdinal, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToRetainedSize, nodes, nodeFieldCount, nodeSelfSizeOffset, formatNodeLabel, isInternalNode) => {
|
|
956
|
+
const retainedNodes = [];
|
|
957
|
+
const dominateeOrdinals = [];
|
|
958
|
+
const childStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
|
|
959
|
+
const childEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
|
|
960
|
+
for (let offset = childStartOffset; offset < childEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
|
|
961
|
+
while (dominateeOrdinals.length > 0) {
|
|
962
|
+
const current = dominateeOrdinals.pop();
|
|
963
|
+
if (!isInternalNode(current)) retainedNodes.push({
|
|
964
|
+
type: `node`,
|
|
965
|
+
id: current,
|
|
966
|
+
name: formatNodeLabel(current),
|
|
967
|
+
selfSize: nodes[current * nodeFieldCount + nodeSelfSizeOffset],
|
|
968
|
+
retainedSize: nodeOrdinalToRetainedSize[current]
|
|
969
|
+
});
|
|
970
|
+
const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[current];
|
|
971
|
+
const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[current + 1];
|
|
972
|
+
for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
|
|
973
|
+
}
|
|
974
|
+
return retainedNodes;
|
|
975
|
+
};
|
|
976
|
+
|
|
977
|
+
//#endregion
|
|
978
|
+
//#region src/formats/jsc-heap-snapshot/aggregate.ts
|
|
979
|
+
const aggregateJSCHeapSnapshot = (snapshot) => {
|
|
980
|
+
const { nodes, nodeClassNames, edges, edgeTypes, edgeNames } = snapshot;
|
|
981
|
+
const nodeCount = nodes.length / NODE_FIELD_COUNT;
|
|
982
|
+
const rawEdgeCount = edges.length / EDGE_FIELD_COUNT;
|
|
983
|
+
const stringClassNameIndex = nodeClassNames.indexOf(`string`);
|
|
984
|
+
const indexEdgeType = edgeTypes.indexOf(`Index`);
|
|
985
|
+
const classNameIndexToCategoryOrdinal = computeClassNameIndexToCategoryOrdinal(nodeClassNames);
|
|
986
|
+
const { nodeAdjacencyGraph, edgeCount } = computeNodeAdjacencyGraph$1(edges, nodeCount, rawEdgeCount);
|
|
987
|
+
const snapshotAggregator = new SnapshotAggregator({
|
|
988
|
+
nodeCount,
|
|
989
|
+
edgeCount,
|
|
990
|
+
nodeAdjacencyGraph,
|
|
991
|
+
nodes,
|
|
992
|
+
nodeFieldCount: NODE_FIELD_COUNT,
|
|
993
|
+
nodeSelfSizeOffset: NODE_SIZE_OFFSET,
|
|
994
|
+
formatEdgeLabel: (retainerOrdinal, edgeIndex) => {
|
|
995
|
+
return `${edges[edgeIndex + EDGE_TYPE_OFFSET] === indexEdgeType ? `[${edges[edgeIndex + EDGE_NAME_OFFSET]}]` : `.${edgeNames[edges[edgeIndex + EDGE_NAME_OFFSET]]}`} ${nodeClassNames[nodes[retainerOrdinal * NODE_FIELD_COUNT + NODE_CLASS_OFFSET]]}`;
|
|
996
|
+
},
|
|
997
|
+
formatNodeLabel: (nodeOrdinal) => {
|
|
998
|
+
return nodeClassNames[nodes[nodeOrdinal * NODE_FIELD_COUNT + NODE_CLASS_OFFSET]];
|
|
999
|
+
},
|
|
1000
|
+
isInternalNode: (nodeOrdinal) => {
|
|
1001
|
+
return (nodes[nodeOrdinal * NODE_FIELD_COUNT + NODE_FLAGS_OFFSET] & NODE_INTERNAL_FLAG) !== 0;
|
|
1002
|
+
}
|
|
1003
|
+
});
|
|
1004
|
+
for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
1005
|
+
const nodeIndex = nodeOrdinal * NODE_FIELD_COUNT;
|
|
1006
|
+
const classNameIndex = nodes[nodeIndex + NODE_CLASS_OFFSET];
|
|
1007
|
+
const flags = nodes[nodeIndex + NODE_FLAGS_OFFSET];
|
|
1008
|
+
snapshotAggregator.addCategoryNode(nodeOrdinal, categorizeNode(classNameIndex, flags, classNameIndexToCategoryOrdinal));
|
|
1009
|
+
if (classNameIndex === stringClassNameIndex) snapshotAggregator.addStringNode(nodeOrdinal);
|
|
1010
|
+
else snapshotAggregator.addConstructorNode(nodeOrdinal);
|
|
1011
|
+
}
|
|
1012
|
+
return snapshotAggregator.aggregate();
|
|
1013
|
+
};
|
|
1014
|
+
const computeClassNameIndexToCategoryOrdinal = (nodeClassNames) => {
|
|
1015
|
+
const classNameToCategoryOrdinal = getClassNameToCategoryOrdinal();
|
|
1016
|
+
const classNameIndexToCategoryOrdinal = new Int8Array(nodeClassNames.length).fill(-1);
|
|
1017
|
+
for (let index = 0; index < nodeClassNames.length; index++) {
|
|
1018
|
+
const categoryOrdinal = classNameToCategoryOrdinal[nodeClassNames[index]];
|
|
1019
|
+
if (categoryOrdinal !== void 0) classNameIndexToCategoryOrdinal[index] = categoryOrdinal;
|
|
1020
|
+
}
|
|
1021
|
+
return classNameIndexToCategoryOrdinal;
|
|
1022
|
+
};
|
|
1023
|
+
const getClassNameToCategoryOrdinal = () => {
|
|
1024
|
+
if (classNameToCategoryOrdinal !== void 0) return classNameToCategoryOrdinal;
|
|
1025
|
+
classNameToCategoryOrdinal = {};
|
|
1026
|
+
for (const name of Object.keys(globals.builtin)) classNameToCategoryOrdinal[name] = 12;
|
|
1027
|
+
for (const name of Object.keys(globals.browser)) classNameToCategoryOrdinal[name] = 13;
|
|
1028
|
+
Object.assign(classNameToCategoryOrdinal, {
|
|
1029
|
+
string: 0,
|
|
1030
|
+
Array: 1,
|
|
1031
|
+
"Array Iterator": 1,
|
|
1032
|
+
"Immutable Butterfly": 1,
|
|
1033
|
+
SparseArrayValueMap: 1,
|
|
1034
|
+
Int8Array: 1,
|
|
1035
|
+
Uint8Array: 1,
|
|
1036
|
+
Uint8ClampedArray: 1,
|
|
1037
|
+
Int16Array: 1,
|
|
1038
|
+
Uint16Array: 1,
|
|
1039
|
+
Int32Array: 1,
|
|
1040
|
+
Uint32Array: 1,
|
|
1041
|
+
Float16Array: 1,
|
|
1042
|
+
Float32Array: 1,
|
|
1043
|
+
Float64Array: 1,
|
|
1044
|
+
BigInt64Array: 1,
|
|
1045
|
+
BigUint64Array: 1,
|
|
1046
|
+
Function: 2,
|
|
1047
|
+
GeneratorFunction: 2,
|
|
1048
|
+
AsyncFunction: 2,
|
|
1049
|
+
AsyncGeneratorFunction: 2,
|
|
1050
|
+
Callee: 2,
|
|
1051
|
+
CallbackObject: 2,
|
|
1052
|
+
FunctionExecutable: 3,
|
|
1053
|
+
UnlinkedFunctionExecutable: 3,
|
|
1054
|
+
NativeExecutable: 3,
|
|
1055
|
+
ProgramExecutable: 3,
|
|
1056
|
+
ModuleProgramExecutable: 3,
|
|
1057
|
+
FunctionCodeBlock: 3,
|
|
1058
|
+
UnlinkedFunctionCodeBlock: 3,
|
|
1059
|
+
ModuleRecord: 3,
|
|
1060
|
+
JSSourceCode: 3,
|
|
1061
|
+
RegExp: 4,
|
|
1062
|
+
Number: 5,
|
|
1063
|
+
symbol: 6,
|
|
1064
|
+
Symbol: 6,
|
|
1065
|
+
BigInt: 7,
|
|
1066
|
+
JSLexicalEnvironment: 8,
|
|
1067
|
+
JSModuleEnvironment: 8,
|
|
1068
|
+
JSGlobalLexicalEnvironment: 8,
|
|
1069
|
+
JSWindowProxy: 8,
|
|
1070
|
+
InjectedScriptHost: 8,
|
|
1071
|
+
CommandLineAPIHost: 8,
|
|
1072
|
+
"<root>": 8,
|
|
1073
|
+
Object: 10,
|
|
1074
|
+
Prototype: 10,
|
|
1075
|
+
Generator: 10,
|
|
1076
|
+
AsyncGenerator: 10,
|
|
1077
|
+
"Map Iterator": 10,
|
|
1078
|
+
"Set Iterator": 10,
|
|
1079
|
+
"String Iterator": 10,
|
|
1080
|
+
"RegExp String Iterator": 10,
|
|
1081
|
+
AsyncFromSyncIterator: 10,
|
|
1082
|
+
AsyncIterator: 10,
|
|
1083
|
+
Arguments: 10,
|
|
1084
|
+
Int8ArrayPrototype: 10,
|
|
1085
|
+
Uint8ArrayPrototype: 10,
|
|
1086
|
+
Uint8ClampedArrayPrototype: 10,
|
|
1087
|
+
Int16ArrayPrototype: 10,
|
|
1088
|
+
Uint16ArrayPrototype: 10,
|
|
1089
|
+
Int32ArrayPrototype: 10,
|
|
1090
|
+
Uint32ArrayPrototype: 10,
|
|
1091
|
+
Float32ArrayPrototype: 10,
|
|
1092
|
+
Float64ArrayPrototype: 10,
|
|
1093
|
+
InternalPromise: 12,
|
|
1094
|
+
InternalPromisePrototype: 12,
|
|
1095
|
+
ShadowRealm: 12,
|
|
1096
|
+
ModuleNamespaceObject: 12,
|
|
1097
|
+
"Intl.DurationFormat": 12,
|
|
1098
|
+
"Intl.ListFormat": 12,
|
|
1099
|
+
"Intl.DateTimeFormat": 12,
|
|
1100
|
+
WindowProperties: 13,
|
|
1101
|
+
TextEncoderStreamEncoder: 13,
|
|
1102
|
+
ModuleLoader: 13
|
|
1103
|
+
});
|
|
1104
|
+
return classNameToCategoryOrdinal;
|
|
1105
|
+
};
|
|
1106
|
+
let classNameToCategoryOrdinal;
|
|
1107
|
+
const categorizeNode = (classNameIndex, flags, classNameIndexToCategoryOrdinal) => {
|
|
1108
|
+
let categoryOrdinal = classNameIndexToCategoryOrdinal[classNameIndex];
|
|
1109
|
+
if (categoryOrdinal === -1) if (flags & NODE_INTERNAL_FLAG) categoryOrdinal = 8;
|
|
1110
|
+
else if (flags & NODE_ELEMENT_FLAG) categoryOrdinal = 9;
|
|
1111
|
+
else if (flags & NODE_OBJECT_FLAG) categoryOrdinal = 10;
|
|
1112
|
+
else categoryOrdinal = 11;
|
|
1113
|
+
return CATEGORY_ORDINAL_TO_NAME[categoryOrdinal];
|
|
1114
|
+
};
|
|
1115
|
+
const CATEGORY_ORDINAL_TO_NAME = [
|
|
1116
|
+
`string`,
|
|
1117
|
+
`array`,
|
|
1118
|
+
`closure`,
|
|
1119
|
+
`code`,
|
|
1120
|
+
`regexp`,
|
|
1121
|
+
`number`,
|
|
1122
|
+
`symbol`,
|
|
1123
|
+
`bigint`,
|
|
1124
|
+
`internal`,
|
|
1125
|
+
`element`,
|
|
1126
|
+
`object`,
|
|
1127
|
+
`unknown`,
|
|
1128
|
+
`built-in`,
|
|
1129
|
+
`native`
|
|
1130
|
+
];
|
|
1131
|
+
const computeNodeAdjacencyGraph$1 = (edges, nodeCount, rawEdgeCount) => {
|
|
1132
|
+
const ordinalToSuccessorCount = new Int32Array(nodeCount);
|
|
1133
|
+
const ordinalToPredecessorCount = new Int32Array(nodeCount);
|
|
1134
|
+
for (let edgeOrdinal = 0; edgeOrdinal < rawEdgeCount; edgeOrdinal++) {
|
|
1135
|
+
const edgeIndex = edgeOrdinal * EDGE_FIELD_COUNT;
|
|
1136
|
+
const fromNodeOrdinal = edges[edgeIndex + EDGE_FROM_OFFSET];
|
|
1137
|
+
const toNodeOrdinal = edges[edgeIndex + EDGE_TO_OFFSET];
|
|
1138
|
+
if (fromNodeOrdinal >= nodeCount || toNodeOrdinal >= nodeCount) continue;
|
|
1139
|
+
ordinalToSuccessorCount[fromNodeOrdinal]++;
|
|
1140
|
+
ordinalToPredecessorCount[toNodeOrdinal]++;
|
|
1141
|
+
}
|
|
1142
|
+
const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
|
|
1143
|
+
const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
|
|
1144
|
+
for (let i = 0; i < nodeCount; i++) {
|
|
1145
|
+
ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
|
|
1146
|
+
ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
|
|
1147
|
+
}
|
|
1148
|
+
const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
|
|
1149
|
+
const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
|
|
1150
|
+
const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
|
|
1151
|
+
const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
|
|
1152
|
+
const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
|
|
1153
|
+
ordinalToSuccessorCount.fill(0);
|
|
1154
|
+
ordinalToPredecessorCount.fill(0);
|
|
1155
|
+
for (let edgeOrdinal = 0; edgeOrdinal < rawEdgeCount; edgeOrdinal++) {
|
|
1156
|
+
const edgeIndex = edgeOrdinal * EDGE_FIELD_COUNT;
|
|
1157
|
+
const fromNodeOrdinal = edges[edgeIndex + EDGE_FROM_OFFSET];
|
|
1158
|
+
const toNodeOrdinal = edges[edgeIndex + EDGE_TO_OFFSET];
|
|
1159
|
+
if (fromNodeOrdinal >= nodeCount || toNodeOrdinal >= nodeCount) continue;
|
|
1160
|
+
const successorOffset = ordinalToSuccessorStartOffset[fromNodeOrdinal] + ordinalToSuccessorCount[fromNodeOrdinal];
|
|
1161
|
+
offsetToSuccessorOrdinal[successorOffset] = toNodeOrdinal;
|
|
1162
|
+
offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
|
|
1163
|
+
ordinalToSuccessorCount[fromNodeOrdinal]++;
|
|
1164
|
+
const predecessorOffset = ordinalToPredecessorStartOffset[toNodeOrdinal] + ordinalToPredecessorCount[toNodeOrdinal];
|
|
1165
|
+
offsetToPredecessorOrdinal[predecessorOffset] = fromNodeOrdinal;
|
|
1166
|
+
offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
|
|
1167
|
+
ordinalToPredecessorCount[toNodeOrdinal]++;
|
|
1168
|
+
}
|
|
1169
|
+
return {
|
|
1170
|
+
nodeAdjacencyGraph: {
|
|
1171
|
+
ordinalToSuccessorStartOffset,
|
|
1172
|
+
offsetToSuccessorOrdinal,
|
|
1173
|
+
offsetToSuccessorEdgeIndex,
|
|
1174
|
+
ordinalToPredecessorStartOffset,
|
|
1175
|
+
offsetToPredecessorOrdinal,
|
|
1176
|
+
offsetToPredecessorEdgeIndex
|
|
1177
|
+
},
|
|
1178
|
+
edgeCount: totalEdges
|
|
1179
|
+
};
|
|
1180
|
+
};
|
|
1181
|
+
const NODE_SIZE_OFFSET = 1;
|
|
1182
|
+
const NODE_CLASS_OFFSET = 2;
|
|
1183
|
+
const NODE_FLAGS_OFFSET = 3;
|
|
1184
|
+
const NODE_FIELD_COUNT = 4;
|
|
1185
|
+
const EDGE_FROM_OFFSET = 0;
|
|
1186
|
+
const EDGE_TO_OFFSET = 1;
|
|
1187
|
+
const EDGE_TYPE_OFFSET = 2;
|
|
1188
|
+
const EDGE_NAME_OFFSET = 3;
|
|
1189
|
+
const EDGE_FIELD_COUNT = 4;
|
|
1190
|
+
const NODE_INTERNAL_FLAG = 1;
|
|
1191
|
+
const NODE_OBJECT_FLAG = 2;
|
|
1192
|
+
const NODE_ELEMENT_FLAG = 4;
|
|
1193
|
+
|
|
1194
|
+
//#endregion
|
|
1195
|
+
//#region src/formats/jsc-heap-snapshot/parse.ts
|
|
1196
|
+
const parseJSCHeapSnapshotAsync = (data) => JumboJSON.parseAsync(data);
|
|
1197
|
+
|
|
1198
|
+
//#endregion
|
|
1199
|
+
//#region src/formats/jsc-heap-snapshot/index.ts
|
|
1200
|
+
const detectJSCHeapSnapshot = (json) => {
|
|
1201
|
+
if (typeof json !== `object` || json === null) return;
|
|
1202
|
+
const { version, type, nodes } = json;
|
|
1203
|
+
if (version !== 2 || type !== `Inspector` || !Array.isArray(nodes)) return;
|
|
1204
|
+
return json;
|
|
1205
|
+
};
|
|
1206
|
+
/**
|
|
1207
|
+
* Asynchronously converts the given JSC heap snapshot to Markdown.
|
|
1208
|
+
*
|
|
1209
|
+
* It is assumed that {@link data} is a valid snapshot. The behavior of this
|
|
1210
|
+
* function is undefined for invalid snapshots.
|
|
1211
|
+
*
|
|
1212
|
+
* See the [JSC heap snapshot docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/jsc-heap-snapshot.md)
|
|
1213
|
+
* for supported runtimes and generation instructions
|
|
1214
|
+
* (`profiler-md --help jsc-heap-snapshot`).
|
|
1215
|
+
*/
|
|
1216
|
+
const jscHeapSnapshotToMdAsync = async (data, options) => jscHeapSnapshotToMdInternal(await parseJSCHeapSnapshotAsync(data), options);
|
|
1217
|
+
const jscHeapSnapshotToMdInternal = (snapshot, options) => {
|
|
1218
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1219
|
+
return formatHeapSnapshot(aggregateJSCHeapSnapshot(snapshot), normalizedOptions);
|
|
1220
|
+
};
|
|
1221
|
+
|
|
1222
|
+
//#endregion
|
|
1223
|
+
//#region src/profile/aggregate.ts
|
|
1224
|
+
var ProfileAggregator = class {
|
|
1225
|
+
#metrics;
|
|
1226
|
+
#functionKey;
|
|
1227
|
+
#functionInput;
|
|
1228
|
+
#options;
|
|
1229
|
+
#totalSampleCount;
|
|
1230
|
+
#totalValues;
|
|
1231
|
+
#categoryToMetrics;
|
|
1232
|
+
#keyToCallStack;
|
|
1233
|
+
#keyToFunction;
|
|
1234
|
+
#idToFunction;
|
|
1235
|
+
#functionIdToLastSeenSampleCount;
|
|
1236
|
+
#frameIndexToFramePairKey;
|
|
1237
|
+
constructor({ metrics, functionKey, functionInput }, options) {
|
|
1238
|
+
this.#metrics = metrics;
|
|
1239
|
+
this.#functionKey = functionKey;
|
|
1240
|
+
this.#functionInput = functionInput;
|
|
1241
|
+
this.#options = options;
|
|
1242
|
+
this.#totalSampleCount = 0;
|
|
1243
|
+
this.#totalValues = new Float64Array(this.#metrics.length);
|
|
1244
|
+
this.#categoryToMetrics = /* @__PURE__ */ new Map();
|
|
1245
|
+
this.#keyToCallStack = /* @__PURE__ */ new Map();
|
|
1246
|
+
this.#keyToFunction = /* @__PURE__ */ new Map();
|
|
1247
|
+
this.#idToFunction = [];
|
|
1248
|
+
this.#functionIdToLastSeenSampleCount = new DynamicTypedArray(new Uint32Array(1));
|
|
1249
|
+
this.#frameIndexToFramePairKey = new DynamicTypedArray(new Int32Array(64));
|
|
1250
|
+
}
|
|
1251
|
+
/** Adds a single profile sample. */
|
|
1252
|
+
addSample({ values, nodes, line }) {
|
|
1253
|
+
if (nodes.length === 0) return;
|
|
1254
|
+
const callStack = this.#getOrCreateCallStack(nodes);
|
|
1255
|
+
const callee = callStack.frames[0];
|
|
1256
|
+
const caller = callStack.frames[1];
|
|
1257
|
+
let categoryMetrics = this.#categoryToMetrics.get(callee.category);
|
|
1258
|
+
if (!categoryMetrics) {
|
|
1259
|
+
categoryMetrics = {
|
|
1260
|
+
sampleCount: 0,
|
|
1261
|
+
values: new Float64Array(this.#metrics.length)
|
|
1262
|
+
};
|
|
1263
|
+
this.#categoryToMetrics.set(callee.category, categoryMetrics);
|
|
1264
|
+
}
|
|
1265
|
+
let callerMetrics;
|
|
1266
|
+
if (caller) {
|
|
1267
|
+
callerMetrics = callee.callerIdToMetrics.get(caller.id);
|
|
1268
|
+
if (!callerMetrics) {
|
|
1269
|
+
callerMetrics = {
|
|
1270
|
+
caller,
|
|
1271
|
+
selfSampleCount: 0,
|
|
1272
|
+
selfValues: new Float64Array(this.#metrics.length)
|
|
1273
|
+
};
|
|
1274
|
+
callee.callerIdToMetrics.set(caller.id, callerMetrics);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
let lineMetrics;
|
|
1278
|
+
if (line !== void 0) {
|
|
1279
|
+
lineMetrics = callee.lineToMetrics.get(line);
|
|
1280
|
+
if (!lineMetrics) {
|
|
1281
|
+
lineMetrics = {
|
|
1282
|
+
sampleCount: 0,
|
|
1283
|
+
values: new Float64Array(this.#metrics.length)
|
|
1284
|
+
};
|
|
1285
|
+
callee.lineToMetrics.set(line, lineMetrics);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
this.#totalSampleCount++;
|
|
1289
|
+
categoryMetrics.sampleCount++;
|
|
1290
|
+
callStack.selfSampleCount++;
|
|
1291
|
+
callee.selfSampleCount++;
|
|
1292
|
+
if (callerMetrics) callerMetrics.selfSampleCount++;
|
|
1293
|
+
if (lineMetrics) lineMetrics.sampleCount++;
|
|
1294
|
+
for (let i = 0; i < values.length; i++) {
|
|
1295
|
+
this.#totalValues[i] += values[i];
|
|
1296
|
+
categoryMetrics.values[i] += values[i];
|
|
1297
|
+
callStack.selfValues[i] += values[i];
|
|
1298
|
+
callee.selfValues[i] += values[i];
|
|
1299
|
+
if (callerMetrics) callerMetrics.selfValues[i] += values[i];
|
|
1300
|
+
if (lineMetrics) lineMetrics.values[i] += values[i];
|
|
1301
|
+
}
|
|
1302
|
+
const funcCount = this.#keyToFunction.size;
|
|
1303
|
+
const functionIdToLastSeenSampleCount = this.#functionIdToLastSeenSampleCount.ensureCapacity(funcCount);
|
|
1304
|
+
for (const func of callStack.frames) {
|
|
1305
|
+
if (functionIdToLastSeenSampleCount[func.id] === this.#totalSampleCount) continue;
|
|
1306
|
+
functionIdToLastSeenSampleCount[func.id] = this.#totalSampleCount;
|
|
1307
|
+
func.totalSampleCount++;
|
|
1308
|
+
for (let i = 0; i < values.length; i++) func.totalValues[i] += values[i];
|
|
1309
|
+
}
|
|
1310
|
+
const maxFramePairCount = callStack.frames.length - 1;
|
|
1311
|
+
const frameIndexToFramePairKey = this.#frameIndexToFramePairKey.ensureCapacity(maxFramePairCount);
|
|
1312
|
+
let seenFramePairCount = 0;
|
|
1313
|
+
for (let i = 0; i < maxFramePairCount; i++) {
|
|
1314
|
+
const callee = callStack.frames[i];
|
|
1315
|
+
const caller = callStack.frames[i + 1];
|
|
1316
|
+
const pairKey = caller.id * funcCount + callee.id;
|
|
1317
|
+
let pairAlreadySeen = false;
|
|
1318
|
+
for (let j = 0; j < seenFramePairCount; j++) if (frameIndexToFramePairKey[j] === pairKey) {
|
|
1319
|
+
pairAlreadySeen = true;
|
|
1320
|
+
break;
|
|
1321
|
+
}
|
|
1322
|
+
if (pairAlreadySeen) continue;
|
|
1323
|
+
frameIndexToFramePairKey[seenFramePairCount++] = pairKey;
|
|
1324
|
+
let calleeMetrics = caller.calleeIdToMetrics.get(callee.id);
|
|
1325
|
+
if (!calleeMetrics) {
|
|
1326
|
+
calleeMetrics = {
|
|
1327
|
+
callee,
|
|
1328
|
+
totalSampleCount: 0,
|
|
1329
|
+
totalValues: new Float64Array(this.#metrics.length)
|
|
1330
|
+
};
|
|
1331
|
+
caller.calleeIdToMetrics.set(callee.id, calleeMetrics);
|
|
1332
|
+
}
|
|
1333
|
+
calleeMetrics.totalSampleCount++;
|
|
1334
|
+
for (let i = 0; i < values.length; i++) calleeMetrics.totalValues[i] += values[i];
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
addLineMetrics({ node, lines }) {
|
|
1338
|
+
const func = this.#getOrCreateFunction(node);
|
|
1339
|
+
for (const { line, sampleCount, values } of lines) {
|
|
1340
|
+
let lineMetrics = func.lineToMetrics.get(line);
|
|
1341
|
+
if (!lineMetrics) {
|
|
1342
|
+
lineMetrics = {
|
|
1343
|
+
sampleCount: 0,
|
|
1344
|
+
values: new Float64Array(this.#metrics.length)
|
|
1345
|
+
};
|
|
1346
|
+
func.lineToMetrics.set(line, lineMetrics);
|
|
1347
|
+
}
|
|
1348
|
+
lineMetrics.sampleCount += sampleCount;
|
|
1349
|
+
for (let i = 0; i < values.length; i++) lineMetrics.values[i] += values[i];
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
#getOrCreateCallStack(nodes) {
|
|
1353
|
+
const frames = nodes.map((node) => this.#getOrCreateFunction(node));
|
|
1354
|
+
const key = frames.map((frame) => frame.id).join(`,`);
|
|
1355
|
+
let callStack = this.#keyToCallStack.get(key);
|
|
1356
|
+
if (callStack) return callStack;
|
|
1357
|
+
callStack = {
|
|
1358
|
+
frames,
|
|
1359
|
+
selfSampleCount: 0,
|
|
1360
|
+
selfValues: new Float64Array(this.#metrics.length)
|
|
1361
|
+
};
|
|
1362
|
+
this.#keyToCallStack.set(key, callStack);
|
|
1363
|
+
return callStack;
|
|
1364
|
+
}
|
|
1365
|
+
#getOrCreateFunction(node) {
|
|
1366
|
+
const { id } = node;
|
|
1367
|
+
if (id !== void 0) {
|
|
1368
|
+
const func = this.#idToFunction[id];
|
|
1369
|
+
if (func) return func;
|
|
1370
|
+
}
|
|
1371
|
+
const key = this.#functionKey(node);
|
|
1372
|
+
let func = this.#keyToFunction.get(key);
|
|
1373
|
+
if (func) {
|
|
1374
|
+
if (id !== void 0) this.#idToFunction[id] = func;
|
|
1375
|
+
return func;
|
|
1376
|
+
}
|
|
1377
|
+
const { name: nameInput, location: locationInput } = this.#functionInput(node);
|
|
1378
|
+
const entry = {
|
|
1379
|
+
id: this.#keyToFunction.size,
|
|
1380
|
+
name: nameInput || `(anonymous)`,
|
|
1381
|
+
location: locationInput ? makeProfileLocation(locationInput) : void 0
|
|
1382
|
+
};
|
|
1383
|
+
func = {
|
|
1384
|
+
type: `function`,
|
|
1385
|
+
...entry,
|
|
1386
|
+
category: this.#options.categorizeEntry(entry),
|
|
1387
|
+
selfSampleCount: 0,
|
|
1388
|
+
totalSampleCount: 0,
|
|
1389
|
+
selfValues: new Float64Array(this.#metrics.length),
|
|
1390
|
+
totalValues: new Float64Array(this.#metrics.length),
|
|
1391
|
+
lineToMetrics: /* @__PURE__ */ new Map(),
|
|
1392
|
+
callerIdToMetrics: /* @__PURE__ */ new Map(),
|
|
1393
|
+
calleeIdToMetrics: /* @__PURE__ */ new Map()
|
|
1394
|
+
};
|
|
1395
|
+
if (id !== void 0) this.#idToFunction[id] = func;
|
|
1396
|
+
this.#keyToFunction.set(key, func);
|
|
1397
|
+
return func;
|
|
1398
|
+
}
|
|
1399
|
+
aggregate() {
|
|
1400
|
+
const samplingRates = new Float64Array(this.#metrics.length);
|
|
1401
|
+
for (let i = 0; i < samplingRates.length; i++) samplingRates[i] = this.#totalValues[i] / this.#totalSampleCount;
|
|
1402
|
+
const functions = [...this.#keyToFunction.values()];
|
|
1403
|
+
const callStacks = [...this.#keyToCallStack.values()];
|
|
1404
|
+
return {
|
|
1405
|
+
metrics: this.#metrics,
|
|
1406
|
+
totalSampleCount: this.#totalSampleCount,
|
|
1407
|
+
totalValues: this.#totalValues,
|
|
1408
|
+
samplingRates,
|
|
1409
|
+
categoryToMetrics: this.#categoryToMetrics,
|
|
1410
|
+
functions,
|
|
1411
|
+
callStacks
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
};
|
|
1415
|
+
/**
|
|
1416
|
+
* Returns the list of callers of {@link callStacks} that is the longest common
|
|
1417
|
+
* suffix of their frames, except it never returns a call stack as long as one
|
|
1418
|
+
* of the input call stacks.
|
|
1419
|
+
*
|
|
1420
|
+
* This behavior is so that it's safe to remove that suffix from any of the call
|
|
1421
|
+
* stacks and end up with a non-empty call stack to format.
|
|
1422
|
+
*/
|
|
1423
|
+
const findCommonCallStack = (callStacks) => {
|
|
1424
|
+
if (callStacks.length <= 1) return [];
|
|
1425
|
+
const minLength = Math.min(...callStacks.map((cs) => cs.frames.length));
|
|
1426
|
+
const firstFrames = callStacks[0].frames;
|
|
1427
|
+
let suffixLength = 0;
|
|
1428
|
+
for (let i = 1; i < minLength; i++) {
|
|
1429
|
+
const suffix = firstFrames.slice(-i).map((frame) => frame.id);
|
|
1430
|
+
if (callStacks.every((callStack) => callStack.frames.slice(-i).every((frame, j) => frame.id === suffix[j]))) suffixLength = i;
|
|
1431
|
+
else break;
|
|
1432
|
+
}
|
|
1433
|
+
return suffixLength > 0 ? firstFrames.slice(-suffixLength) : [];
|
|
1434
|
+
};
|
|
1435
|
+
|
|
1436
|
+
//#endregion
|
|
1437
|
+
//#region src/profile/format.ts
|
|
1438
|
+
const formatProfile = (profile, options) => {
|
|
1439
|
+
const headingLevel = 1;
|
|
1440
|
+
return `${[
|
|
1441
|
+
formatHeading(headingLevel, formatTitle(profile)),
|
|
1442
|
+
...formatOverallSummary(profile),
|
|
1443
|
+
...formatMetricSections(profile, {
|
|
1444
|
+
...options,
|
|
1445
|
+
headingLevel: headingLevel + 1
|
|
1446
|
+
})
|
|
1447
|
+
].join(`\n\n`)}\n`;
|
|
1448
|
+
};
|
|
1449
|
+
const formatTitle = (profile) => capitalizeFirst(`${formatConjunction(profile.metrics.map((metric) => metric.phrases.titleNoun))} profile`);
|
|
1450
|
+
const formatOverallSummary = (profile) => [formatSummaryLine(profile), ...formatCategoryTable(profile)];
|
|
1451
|
+
const formatSummaryLine = ({ metrics, totalSampleCount, totalValues, samplingRates }) => {
|
|
1452
|
+
const totalsSummary = capitalizeFirst(formatConjunction(metrics.map((metric, index) => `${metric.phrases.pastTenseVerb} ${formatValue(totalValues[index], metric)}`)));
|
|
1453
|
+
const samplingRatesSummary = `(${formatConjunction(Array.from(samplingRates, (rate, index) => formatSamplingRate(rate, metrics[index])))} per sample)`;
|
|
1454
|
+
return `${totalsSummary} over ${formatCount(totalSampleCount, `sample`)} ${samplingRatesSummary}.`;
|
|
1455
|
+
};
|
|
1456
|
+
const formatCategoryTable = ({ metrics, totalValues, categoryToMetrics }) => {
|
|
1457
|
+
const hottestCategories = [...categoryToMetrics].sort(([, metrics1], [, metrics2]) => metrics2.values[0] - metrics1.values[0]);
|
|
1458
|
+
if (hottestCategories.length === 0) return [];
|
|
1459
|
+
return [formatTable([
|
|
1460
|
+
`Category`,
|
|
1461
|
+
{
|
|
1462
|
+
content: `%`,
|
|
1463
|
+
align: `right`
|
|
1464
|
+
},
|
|
1465
|
+
...metrics.map((metric) => ({
|
|
1466
|
+
content: capitalizeFirst(metric.phrases.columnNoun),
|
|
1467
|
+
align: `right`
|
|
1468
|
+
})),
|
|
1469
|
+
{
|
|
1470
|
+
content: `Samples`,
|
|
1471
|
+
align: `right`
|
|
1472
|
+
}
|
|
1473
|
+
], hottestCategories.map(([category, { values, sampleCount }]) => [
|
|
1474
|
+
category,
|
|
1475
|
+
formatPercent(values[0] / totalValues[0]),
|
|
1476
|
+
...metrics.map((metric, index) => formatValue(values[index], metric)),
|
|
1477
|
+
formatCount(sampleCount)
|
|
1478
|
+
]))];
|
|
1479
|
+
};
|
|
1480
|
+
const formatSamplingRate = (samplingRate, metric) => {
|
|
1481
|
+
switch (metric.type) {
|
|
1482
|
+
case `time`: return formatMicroseconds(samplingRate * 1e3 * metric.milliseconds);
|
|
1483
|
+
case `size`: return formatBytes(samplingRate * metric.bytes);
|
|
1484
|
+
case `custom`: return formatCount(samplingRate, metric.unit);
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1487
|
+
const formatMetricSections = (profile, options) => profile.metrics.flatMap((metric, index) => {
|
|
1488
|
+
const sections = [];
|
|
1489
|
+
let sectionOptions = options;
|
|
1490
|
+
if (profile.metrics.length > 1) {
|
|
1491
|
+
sections.push(formatHeading(options.headingLevel, capitalizeFirst(metric.phrases.titleNoun)));
|
|
1492
|
+
sectionOptions = {
|
|
1493
|
+
...options,
|
|
1494
|
+
headingLevel: options.headingLevel + 1
|
|
1495
|
+
};
|
|
1496
|
+
}
|
|
1497
|
+
return [
|
|
1498
|
+
...sections,
|
|
1499
|
+
...formatHottestFunctions(index, profile, sectionOptions),
|
|
1500
|
+
...formatHottestCallStacks(index, profile, sectionOptions)
|
|
1501
|
+
];
|
|
1502
|
+
});
|
|
1503
|
+
const formatHottestFunctions = (metricIndex, profile, options) => {
|
|
1504
|
+
const subsectionOptions = {
|
|
1505
|
+
...options,
|
|
1506
|
+
headingLevel: options.headingLevel + 1
|
|
1507
|
+
};
|
|
1508
|
+
const functionsSections = [...formatHottestSelfFunctions(metricIndex, profile, subsectionOptions), ...formatHottestTotalFunctions(metricIndex, profile, subsectionOptions)];
|
|
1509
|
+
if (functionsSections.length === 0) return [];
|
|
1510
|
+
return [formatHeading(options.headingLevel, `Hottest functions`), ...functionsSections];
|
|
1511
|
+
};
|
|
1512
|
+
const formatHottestSelfFunctions = (metricIndex, profile, options) => {
|
|
1513
|
+
const hottestFunctions = selectTopN(profile.functions.filter((func) => options.showEntry(func) && func.selfValues[metricIndex] > 0), options.topN, (func) => func.selfValues[metricIndex]);
|
|
1514
|
+
if (hottestFunctions.length === 0) return [];
|
|
1515
|
+
const subsectionOptions = {
|
|
1516
|
+
...options,
|
|
1517
|
+
headingLevel: options.headingLevel + 2
|
|
1518
|
+
};
|
|
1519
|
+
const hottestLinesSections = hottestFunctions.filter((func) => func.lineToMetrics.size > 0).flatMap((func) => formatHottestLines(metricIndex, func, profile, subsectionOptions));
|
|
1520
|
+
const hottestCallersSections = hottestFunctions.flatMap((func) => formatHottestCallers(metricIndex, func, profile, subsectionOptions));
|
|
1521
|
+
const metric = profile.metrics[metricIndex];
|
|
1522
|
+
return [
|
|
1523
|
+
formatHeading(options.headingLevel, `Self ${metric.phrases.columnNoun}`),
|
|
1524
|
+
`Functions ranked by ${metric.phrases.pastParticipleVerbPhrase} directly in the function body, excluding callees.`,
|
|
1525
|
+
formatTable([
|
|
1526
|
+
{
|
|
1527
|
+
content: `%`,
|
|
1528
|
+
align: `right`
|
|
1529
|
+
},
|
|
1530
|
+
{
|
|
1531
|
+
content: capitalizeFirst(metric.phrases.columnNoun),
|
|
1532
|
+
align: `right`
|
|
1533
|
+
},
|
|
1534
|
+
{
|
|
1535
|
+
content: `Samples`,
|
|
1536
|
+
align: `right`
|
|
1537
|
+
},
|
|
1538
|
+
`Function`,
|
|
1539
|
+
`Location`
|
|
1540
|
+
], hottestFunctions.map((func) => [
|
|
1541
|
+
formatPercent(func.selfValues[metricIndex] / profile.totalValues[metricIndex]),
|
|
1542
|
+
formatValue(func.selfValues[metricIndex], metric),
|
|
1543
|
+
formatCount(func.selfSampleCount),
|
|
1544
|
+
inlineCode(func.name),
|
|
1545
|
+
formatProfileLocation(func.location, options)
|
|
1546
|
+
])),
|
|
1547
|
+
...hottestLinesSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Lines`), `Lines ranked by contribution to each function's self ${metric.phrases.columnNoun}.`] : [],
|
|
1548
|
+
...hottestLinesSections,
|
|
1549
|
+
...hottestCallersSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callers`), `Callers ranked by contribution to each function's self ${metric.phrases.columnNoun}. Caller attribution may be imprecise due to inlining.`] : [],
|
|
1550
|
+
...hottestCallersSections
|
|
1551
|
+
];
|
|
1552
|
+
};
|
|
1553
|
+
const formatHottestLines = (metricIndex, func, profile, options) => {
|
|
1554
|
+
const selfValue = func.selfValues[metricIndex];
|
|
1555
|
+
const hottestLines = selectTopN([...func.lineToMetrics], Math.ceil(options.topN / 4), ([, metrics]) => metrics.values[metricIndex]);
|
|
1556
|
+
if (hottestLines.length === 0) return [];
|
|
1557
|
+
const metric = profile.metrics[metricIndex];
|
|
1558
|
+
return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
|
|
1559
|
+
{
|
|
1560
|
+
content: `%`,
|
|
1561
|
+
align: `right`
|
|
1562
|
+
},
|
|
1563
|
+
{
|
|
1564
|
+
content: capitalizeFirst(metric.phrases.columnNoun),
|
|
1565
|
+
align: `right`
|
|
1566
|
+
},
|
|
1567
|
+
{
|
|
1568
|
+
content: `Samples`,
|
|
1569
|
+
align: `right`
|
|
1570
|
+
},
|
|
1571
|
+
`Location`
|
|
1572
|
+
], hottestLines.map(([line, stats]) => [
|
|
1573
|
+
formatPercent(stats.values[metricIndex] / selfValue),
|
|
1574
|
+
formatValue(stats.values[metricIndex], metric),
|
|
1575
|
+
formatCount(stats.sampleCount),
|
|
1576
|
+
func.location ? formatProfileLocation({
|
|
1577
|
+
...func.location,
|
|
1578
|
+
line,
|
|
1579
|
+
column: void 0
|
|
1580
|
+
}, options) : String(line)
|
|
1581
|
+
]))];
|
|
1582
|
+
};
|
|
1583
|
+
const formatHottestCallers = (metricIndex, func, profile, options) => {
|
|
1584
|
+
const selfValue = func.selfValues[metricIndex];
|
|
1585
|
+
const hottestCallers = selectTopN([...func.callerIdToMetrics.values()].filter((entry) => options.showEntry(entry.caller) && entry.selfValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.selfValues[metricIndex]);
|
|
1586
|
+
if (hottestCallers.length === 0) return [];
|
|
1587
|
+
const metric = profile.metrics[metricIndex];
|
|
1588
|
+
return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
|
|
1589
|
+
{
|
|
1590
|
+
content: `%`,
|
|
1591
|
+
align: `right`
|
|
1592
|
+
},
|
|
1593
|
+
{
|
|
1594
|
+
content: capitalizeFirst(metric.phrases.columnNoun),
|
|
1595
|
+
align: `right`
|
|
1596
|
+
},
|
|
1597
|
+
{
|
|
1598
|
+
content: `Samples`,
|
|
1599
|
+
align: `right`
|
|
1600
|
+
},
|
|
1601
|
+
`Caller`,
|
|
1602
|
+
`Location`
|
|
1603
|
+
], hottestCallers.map(({ caller, selfValues, selfSampleCount }) => [
|
|
1604
|
+
formatPercent(selfValues[metricIndex] / selfValue),
|
|
1605
|
+
formatValue(selfValues[metricIndex], metric),
|
|
1606
|
+
formatCount(selfSampleCount),
|
|
1607
|
+
inlineCode(caller.name),
|
|
1608
|
+
formatProfileLocation(caller.location, options)
|
|
1609
|
+
]))];
|
|
1610
|
+
};
|
|
1611
|
+
const formatHottestTotalFunctions = (metricIndex, profile, options) => {
|
|
1612
|
+
const totalValue = profile.totalValues[metricIndex];
|
|
1613
|
+
const hottestFunctions = selectTopN(profile.functions.filter((func) => options.showEntry(func) && func.totalValues[metricIndex] > 0), options.topN, (func) => func.totalValues[metricIndex]);
|
|
1614
|
+
if (hottestFunctions.length === 0) return [];
|
|
1615
|
+
const subsectionOptions = {
|
|
1616
|
+
...options,
|
|
1617
|
+
headingLevel: options.headingLevel + 2
|
|
1618
|
+
};
|
|
1619
|
+
const calleeSections = hottestFunctions.flatMap((func) => formatHottestCallees(metricIndex, func, profile, subsectionOptions));
|
|
1620
|
+
const metric = profile.metrics[metricIndex];
|
|
1621
|
+
return [
|
|
1622
|
+
formatHeading(options.headingLevel, `Total ${metric.phrases.columnNoun}`),
|
|
1623
|
+
`Functions ranked by total ${metric.phrases.pastParticipleVerbPhrase} in the function and all its callees.`,
|
|
1624
|
+
formatTable([
|
|
1625
|
+
{
|
|
1626
|
+
content: `%`,
|
|
1627
|
+
align: `right`
|
|
1628
|
+
},
|
|
1629
|
+
{
|
|
1630
|
+
content: capitalizeFirst(metric.phrases.columnNoun),
|
|
1631
|
+
align: `right`
|
|
1632
|
+
},
|
|
1633
|
+
{
|
|
1634
|
+
content: `Samples`,
|
|
1635
|
+
align: `right`
|
|
1636
|
+
},
|
|
1637
|
+
`Function`,
|
|
1638
|
+
`Location`
|
|
1639
|
+
], hottestFunctions.map((func) => [
|
|
1640
|
+
formatPercent(func.totalValues[metricIndex] / totalValue),
|
|
1641
|
+
formatValue(func.totalValues[metricIndex], metric),
|
|
1642
|
+
formatCount(func.totalSampleCount),
|
|
1643
|
+
inlineCode(func.name),
|
|
1644
|
+
formatProfileLocation(func.location, options)
|
|
1645
|
+
])),
|
|
1646
|
+
...calleeSections.length > 0 ? [formatHeading(options.headingLevel + 1, `Callees`), `Callees ranked by contribution to each function's total ${metric.phrases.columnNoun}. Callee attribution may be imprecise due to inlining.`] : [],
|
|
1647
|
+
...calleeSections
|
|
1648
|
+
];
|
|
1649
|
+
};
|
|
1650
|
+
const formatHottestCallees = (metricIndex, func, profile, options) => {
|
|
1651
|
+
const totalValue = func.totalValues[metricIndex];
|
|
1652
|
+
const hottestCallees = selectTopN([...func.calleeIdToMetrics.values()].filter((entry) => options.showEntry(entry.callee) && entry.totalValues[metricIndex] > 0), Math.ceil(options.topN / 4), (entry) => entry.totalValues[metricIndex]);
|
|
1653
|
+
if (hottestCallees.length === 0) return [];
|
|
1654
|
+
const metric = profile.metrics[metricIndex];
|
|
1655
|
+
return [formatHeading(options.headingLevel, `${inlineCode(func.name)} (${formatProfileLocation(func.location, options)})`), formatTable([
|
|
1656
|
+
{
|
|
1657
|
+
content: `%`,
|
|
1658
|
+
align: `right`
|
|
1659
|
+
},
|
|
1660
|
+
{
|
|
1661
|
+
content: capitalizeFirst(metric.phrases.columnNoun),
|
|
1662
|
+
align: `right`
|
|
1663
|
+
},
|
|
1664
|
+
{
|
|
1665
|
+
content: `Samples`,
|
|
1666
|
+
align: `right`
|
|
1667
|
+
},
|
|
1668
|
+
`Callee`,
|
|
1669
|
+
`Location`
|
|
1670
|
+
], hottestCallees.map(({ callee, totalValues, totalSampleCount }) => [
|
|
1671
|
+
formatPercent(totalValues[metricIndex] / totalValue),
|
|
1672
|
+
formatValue(totalValues[metricIndex], metric),
|
|
1673
|
+
formatCount(totalSampleCount),
|
|
1674
|
+
inlineCode(callee.name),
|
|
1675
|
+
formatProfileLocation(callee.location, options)
|
|
1676
|
+
]))];
|
|
1677
|
+
};
|
|
1678
|
+
const formatHottestCallStacks = (metricIndex, profile, options) => {
|
|
1679
|
+
const totalValue = profile.totalValues[metricIndex];
|
|
1680
|
+
const hottestCallStacks = selectTopN(profile.callStacks.map((callStack) => ({
|
|
1681
|
+
...callStack,
|
|
1682
|
+
frames: callStack.frames.filter(options.showEntry)
|
|
1683
|
+
})).filter((callStack) => callStack.frames.length > 1), options.topN, (callStack) => callStack.selfValues[metricIndex]);
|
|
1684
|
+
if (hottestCallStacks.length === 0) return [];
|
|
1685
|
+
const metric = profile.metrics[metricIndex];
|
|
1686
|
+
const commonCallStack = findCommonCallStack(hottestCallStacks);
|
|
1687
|
+
return [
|
|
1688
|
+
formatHeading(options.headingLevel, `Hottest call stacks`),
|
|
1689
|
+
`Call stacks ranked by ${metric.phrases.pastParticipleVerbPhrase} in their leaf frame.`,
|
|
1690
|
+
...commonCallStack.length > 0 ? [`Common call stack: ${formatCallStack(commonCallStack, options)}`] : [],
|
|
1691
|
+
formatTable([
|
|
1692
|
+
{
|
|
1693
|
+
content: `%`,
|
|
1694
|
+
align: `right`
|
|
1695
|
+
},
|
|
1696
|
+
{
|
|
1697
|
+
content: capitalizeFirst(metric.phrases.columnNoun),
|
|
1698
|
+
align: `right`
|
|
1699
|
+
},
|
|
1700
|
+
{
|
|
1701
|
+
content: `Samples`,
|
|
1702
|
+
align: `right`
|
|
1703
|
+
},
|
|
1704
|
+
`Call stack`
|
|
1705
|
+
], hottestCallStacks.map(({ frames, selfValues, selfSampleCount }) => [
|
|
1706
|
+
formatPercent(selfValues[metricIndex] / totalValue),
|
|
1707
|
+
formatValue(selfValues[metricIndex], metric),
|
|
1708
|
+
formatCount(selfSampleCount),
|
|
1709
|
+
formatCallStack(commonCallStack.length > 0 ? frames.slice(0, -commonCallStack.length) : frames, options)
|
|
1710
|
+
]))
|
|
1711
|
+
];
|
|
1712
|
+
};
|
|
1713
|
+
const formatCallStack = (nodes, options) => nodes.map((node, index) => {
|
|
1714
|
+
const name = inlineCode(node.name);
|
|
1715
|
+
if (!node.location) return name;
|
|
1716
|
+
const previousHref = nodes[index - 1]?.location?.url.href;
|
|
1717
|
+
if (!previousHref || node.location.url.href !== previousHref) return `${name} (${formatProfileLocation(node.location, options)})`;
|
|
1718
|
+
const { line, column } = node.location;
|
|
1719
|
+
if (line === void 0) return name;
|
|
1720
|
+
return `${name} (${line}${column === void 0 ? `` : `:${column}`})`;
|
|
1721
|
+
}).join(` ← `);
|
|
1722
|
+
const formatValue = (value, metric) => {
|
|
1723
|
+
switch (metric.type) {
|
|
1724
|
+
case `time`: return formatMilliseconds(value * metric.milliseconds);
|
|
1725
|
+
case `size`: return formatBytes(value * metric.bytes);
|
|
1726
|
+
case `custom`: return formatCount(value, metric.unit);
|
|
819
1727
|
}
|
|
820
1728
|
};
|
|
821
1729
|
const capitalizeFirst = (string) => string.length === 0 ? string : string[0].toUpperCase() + string.slice(1);
|
|
822
1730
|
|
|
823
1731
|
//#endregion
|
|
824
1732
|
//#region src/profile/metric.ts
|
|
825
|
-
const determineMetric = ({ name, unit }) =>
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
1733
|
+
const determineMetric = ({ name, unit }) => {
|
|
1734
|
+
const metric = UNIT_TO_METRIC.get(unit.toLowerCase()) ?? {
|
|
1735
|
+
type: `custom`,
|
|
1736
|
+
unit,
|
|
1737
|
+
phrases: {
|
|
1738
|
+
titleNoun: name,
|
|
1739
|
+
columnNoun: name,
|
|
1740
|
+
pastTenseVerb: `recorded`,
|
|
1741
|
+
pastParticipleVerbPhrase: `${name} recorded`
|
|
1742
|
+
}
|
|
1743
|
+
};
|
|
1744
|
+
const phrases = METRIC_TYPE_AND_NAME_TO_PHRASES.get(metric.type)?.get(name.toLowerCase());
|
|
1745
|
+
if (phrases) return {
|
|
1746
|
+
...metric,
|
|
1747
|
+
phrases
|
|
1748
|
+
};
|
|
1749
|
+
return metric;
|
|
1750
|
+
};
|
|
1751
|
+
const TIME_PHRASES = {
|
|
1752
|
+
titleNoun: `CPU`,
|
|
1753
|
+
columnNoun: `time`,
|
|
1754
|
+
pastTenseVerb: `took`,
|
|
1755
|
+
pastParticipleVerbPhrase: `time spent`
|
|
1756
|
+
};
|
|
1757
|
+
const SIZE_PHRASES = {
|
|
1758
|
+
titleNoun: `heap`,
|
|
1759
|
+
columnNoun: `size`,
|
|
1760
|
+
pastTenseVerb: `allocated`,
|
|
1761
|
+
pastParticipleVerbPhrase: `bytes allocated`
|
|
829
1762
|
};
|
|
830
1763
|
const NANOSECONDS = {
|
|
831
1764
|
type: `time`,
|
|
832
|
-
milliseconds: 1e-6
|
|
1765
|
+
milliseconds: 1e-6,
|
|
1766
|
+
phrases: TIME_PHRASES
|
|
833
1767
|
};
|
|
834
1768
|
const MICROSECONDS = {
|
|
835
1769
|
type: `time`,
|
|
836
|
-
milliseconds: .001
|
|
1770
|
+
milliseconds: .001,
|
|
1771
|
+
phrases: TIME_PHRASES
|
|
837
1772
|
};
|
|
838
1773
|
const MILLISECONDS = {
|
|
839
1774
|
type: `time`,
|
|
840
|
-
milliseconds: 1
|
|
1775
|
+
milliseconds: 1,
|
|
1776
|
+
phrases: TIME_PHRASES
|
|
841
1777
|
};
|
|
842
1778
|
const SECONDS = {
|
|
843
1779
|
type: `time`,
|
|
844
|
-
milliseconds: 1e3
|
|
1780
|
+
milliseconds: 1e3,
|
|
1781
|
+
phrases: TIME_PHRASES
|
|
845
1782
|
};
|
|
846
1783
|
const BYTES = {
|
|
847
1784
|
type: `size`,
|
|
848
|
-
bytes: 1
|
|
1785
|
+
bytes: 1,
|
|
1786
|
+
phrases: SIZE_PHRASES
|
|
849
1787
|
};
|
|
850
1788
|
const KILOBYTES = {
|
|
851
1789
|
type: `size`,
|
|
852
|
-
bytes: 1024
|
|
1790
|
+
bytes: 1024,
|
|
1791
|
+
phrases: SIZE_PHRASES
|
|
853
1792
|
};
|
|
854
1793
|
const MEGABYTES = {
|
|
855
1794
|
type: `size`,
|
|
856
|
-
bytes: 1 << 20
|
|
1795
|
+
bytes: 1 << 20,
|
|
1796
|
+
phrases: SIZE_PHRASES
|
|
857
1797
|
};
|
|
858
1798
|
const GIGABYTES = {
|
|
859
1799
|
type: `size`,
|
|
860
|
-
bytes: 1 << 30
|
|
1800
|
+
bytes: 1 << 30,
|
|
1801
|
+
phrases: SIZE_PHRASES
|
|
861
1802
|
};
|
|
862
|
-
const
|
|
1803
|
+
const UNIT_TO_METRIC = new Map([
|
|
863
1804
|
[`nanoseconds`, NANOSECONDS],
|
|
864
1805
|
[`nanosecond`, NANOSECONDS],
|
|
865
1806
|
[`nanos`, NANOSECONDS],
|
|
@@ -898,18 +1839,103 @@ const METRICS = new Map([
|
|
|
898
1839
|
[`gb`, GIGABYTES],
|
|
899
1840
|
[`none`, {
|
|
900
1841
|
type: `custom`,
|
|
901
|
-
|
|
902
|
-
|
|
1842
|
+
unit: `count`,
|
|
1843
|
+
phrases: {
|
|
1844
|
+
titleNoun: `count`,
|
|
1845
|
+
columnNoun: `count`,
|
|
1846
|
+
pastTenseVerb: `recorded`,
|
|
1847
|
+
pastParticipleVerbPhrase: `count recorded`
|
|
1848
|
+
}
|
|
903
1849
|
}]
|
|
904
1850
|
]);
|
|
1851
|
+
const METRIC_TYPE_AND_NAME_TO_PHRASES = new Map([[`size`, new Map([[`alloc_space`, {
|
|
1852
|
+
titleNoun: `allocated heap`,
|
|
1853
|
+
columnNoun: `size`,
|
|
1854
|
+
pastTenseVerb: `allocated`,
|
|
1855
|
+
pastParticipleVerbPhrase: `bytes allocated`
|
|
1856
|
+
}], [`inuse_space`, {
|
|
1857
|
+
titleNoun: `retained heap`,
|
|
1858
|
+
columnNoun: `size`,
|
|
1859
|
+
pastTenseVerb: `retained`,
|
|
1860
|
+
pastParticipleVerbPhrase: `bytes retained`
|
|
1861
|
+
}]])]]);
|
|
1862
|
+
|
|
1863
|
+
//#endregion
|
|
1864
|
+
//#region src/formats/pprof/aggregate.ts
|
|
1865
|
+
const aggregatePprof = ({ valueTypes, samples, locations, functions }, options) => {
|
|
1866
|
+
const nonCountValueTypes = [...valueTypes.entries()].filter(([, valueType]) => valueType.unit.toLowerCase() !== `count`);
|
|
1867
|
+
const profileAggregator = new ProfileAggregator({
|
|
1868
|
+
metrics: nonCountValueTypes.map(([, valueType]) => determineMetric({
|
|
1869
|
+
name: valueType.type,
|
|
1870
|
+
unit: valueType.unit
|
|
1871
|
+
})),
|
|
1872
|
+
functionKey: (func) => func.id,
|
|
1873
|
+
functionInput: (func) => ({
|
|
1874
|
+
name: func.name || func.systemName,
|
|
1875
|
+
location: {
|
|
1876
|
+
urlOrPath: func.filename,
|
|
1877
|
+
line: func.startLine > 0 ? func.startLine : void 0
|
|
1878
|
+
}
|
|
1879
|
+
})
|
|
1880
|
+
}, options);
|
|
1881
|
+
for (const sample of samples) {
|
|
1882
|
+
const { locationIds, values } = sample;
|
|
1883
|
+
const nodes = [];
|
|
1884
|
+
let calleeLine;
|
|
1885
|
+
for (const locationId of locationIds) {
|
|
1886
|
+
const location = locations[locationId];
|
|
1887
|
+
for (const { functionId, line } of location.lines) {
|
|
1888
|
+
nodes.push(functions[functionId]);
|
|
1889
|
+
calleeLine ??= line;
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
if (nodes.length === 0) continue;
|
|
1893
|
+
profileAggregator.addSample({
|
|
1894
|
+
values: nonCountValueTypes.map(([index]) => values[index]),
|
|
1895
|
+
nodes,
|
|
1896
|
+
line: calleeLine
|
|
1897
|
+
});
|
|
1898
|
+
}
|
|
1899
|
+
return profileAggregator.aggregate();
|
|
1900
|
+
};
|
|
905
1901
|
|
|
906
1902
|
//#endregion
|
|
907
|
-
//#region src/
|
|
908
|
-
const
|
|
1903
|
+
//#region src/helpers/bytes.ts
|
|
1904
|
+
const streamToUint8Array = async (stream) => {
|
|
1905
|
+
const chunks = [];
|
|
1906
|
+
const reader = stream.getReader();
|
|
1907
|
+
try {
|
|
1908
|
+
while (true) {
|
|
1909
|
+
const { done, value } = await reader.read();
|
|
1910
|
+
if (done) break;
|
|
1911
|
+
chunks.push(value);
|
|
1912
|
+
}
|
|
1913
|
+
} finally {
|
|
1914
|
+
reader.releaseLock();
|
|
1915
|
+
}
|
|
1916
|
+
return concatUint8Arrays(chunks);
|
|
1917
|
+
};
|
|
1918
|
+
const concatUint8Arrays = (arrays) => {
|
|
1919
|
+
const arrayArray = Array.isArray(arrays) ? arrays : [...arrays];
|
|
1920
|
+
const concatenated = new Uint8Array(arrayArray.reduce((size, array) => size + array.length, 0));
|
|
1921
|
+
let offset = 0;
|
|
1922
|
+
for (const array of arrayArray) {
|
|
1923
|
+
concatenated.set(array, offset);
|
|
1924
|
+
offset += array.length;
|
|
1925
|
+
}
|
|
1926
|
+
return concatenated;
|
|
1927
|
+
};
|
|
909
1928
|
|
|
910
1929
|
//#endregion
|
|
911
1930
|
//#region src/formats/pprof/parse.ts
|
|
912
|
-
const
|
|
1931
|
+
const parsePprofAsync = async (data) => parsePprof(await (data instanceof Blob ? data.bytes() : streamToUint8Array(data)));
|
|
1932
|
+
const parsePprof = (data) => {
|
|
1933
|
+
if (!ArrayBuffer.isView(data)) {
|
|
1934
|
+
if (!Array.isArray(data)) data = [...data];
|
|
1935
|
+
data = concatUint8Arrays(data);
|
|
1936
|
+
}
|
|
1937
|
+
return parsePprofInternal(Profile.decode(data));
|
|
1938
|
+
};
|
|
913
1939
|
const parsePprofInternal = (profile) => {
|
|
914
1940
|
const { strings } = profile.stringTable;
|
|
915
1941
|
const valueTypes = profile.sampleType.map(({ type, unit }) => ({
|
|
@@ -953,52 +1979,13 @@ const parsePprofInternal = (profile) => {
|
|
|
953
1979
|
};
|
|
954
1980
|
};
|
|
955
1981
|
|
|
956
|
-
//#endregion
|
|
957
|
-
//#region src/formats/pprof/summarize.ts
|
|
958
|
-
const summarizePprof = ({ valueTypes, samples, locations, functions }, options) => {
|
|
959
|
-
const nonCountValueTypes = [...valueTypes.entries()].filter(([, valueType]) => valueType.unit.toLowerCase() !== `count`);
|
|
960
|
-
const profileBuilder = new ProfileBuilder({
|
|
961
|
-
metrics: nonCountValueTypes.map(([, valueType]) => determineMetric({
|
|
962
|
-
name: valueType.type,
|
|
963
|
-
unit: valueType.unit
|
|
964
|
-
})),
|
|
965
|
-
functionKey: (func) => func.id,
|
|
966
|
-
functionInput: (func) => ({
|
|
967
|
-
name: func.name || func.systemName,
|
|
968
|
-
location: {
|
|
969
|
-
urlOrPath: func.filename,
|
|
970
|
-
line: func.startLine > 0 ? func.startLine : void 0
|
|
971
|
-
}
|
|
972
|
-
})
|
|
973
|
-
}, options);
|
|
974
|
-
for (const sample of samples) {
|
|
975
|
-
const { locationIds, values } = sample;
|
|
976
|
-
const nodes = [];
|
|
977
|
-
let calleeLine;
|
|
978
|
-
for (const locationId of locationIds) {
|
|
979
|
-
const location = locations[locationId];
|
|
980
|
-
for (const { functionId, line } of location.lines) {
|
|
981
|
-
nodes.push(functions[functionId]);
|
|
982
|
-
calleeLine ??= line;
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
if (nodes.length === 0) continue;
|
|
986
|
-
profileBuilder.addSample({
|
|
987
|
-
values: nonCountValueTypes.map(([index]) => values[index]),
|
|
988
|
-
nodes,
|
|
989
|
-
line: calleeLine
|
|
990
|
-
});
|
|
991
|
-
}
|
|
992
|
-
return profileBuilder.build();
|
|
993
|
-
};
|
|
994
|
-
|
|
995
1982
|
//#endregion
|
|
996
1983
|
//#region src/formats/pprof/index.ts
|
|
997
|
-
const detectPprof = (data) => {
|
|
998
|
-
if (data.
|
|
1984
|
+
const detectPprof = async (data) => {
|
|
1985
|
+
if (data.size === 0) return;
|
|
999
1986
|
let profile;
|
|
1000
1987
|
try {
|
|
1001
|
-
profile = Profile.decode(data);
|
|
1988
|
+
profile = Profile.decode(await data.bytes());
|
|
1002
1989
|
} catch {
|
|
1003
1990
|
return;
|
|
1004
1991
|
}
|
|
@@ -1006,7 +1993,7 @@ const detectPprof = (data) => {
|
|
|
1006
1993
|
return parsePprofInternal(profile);
|
|
1007
1994
|
};
|
|
1008
1995
|
/**
|
|
1009
|
-
*
|
|
1996
|
+
* Asynchronously converts the given pprof to Markdown.
|
|
1010
1997
|
*
|
|
1011
1998
|
* It is assumed that {@link data} is a valid pprof (raw protobuf). The behavior
|
|
1012
1999
|
* of this function is undefined for invalid profiles.
|
|
@@ -1014,56 +2001,44 @@ const detectPprof = (data) => {
|
|
|
1014
2001
|
* See the [pprof docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/pprof.md)
|
|
1015
2002
|
* for supported tools and generation instructions (`profiler-md --help pprof`).
|
|
1016
2003
|
*/
|
|
1017
|
-
const
|
|
2004
|
+
const pprofToMdAsync = async (data, options) => pprofToMdInternal(await parsePprofAsync(data), options);
|
|
1018
2005
|
const pprofToMdInternal = (pprof, options) => {
|
|
1019
2006
|
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1020
|
-
return
|
|
2007
|
+
return formatProfile(aggregatePprof(pprof, normalizedOptions), normalizedOptions);
|
|
1021
2008
|
};
|
|
1022
2009
|
|
|
1023
2010
|
//#endregion
|
|
1024
|
-
//#region src/formats/speedscope/
|
|
1025
|
-
const
|
|
1026
|
-
|
|
1027
|
-
//#endregion
|
|
1028
|
-
//#region src/helpers/json.ts
|
|
1029
|
-
const parseJson = (data) => JSON.parse(data);
|
|
1030
|
-
|
|
1031
|
-
//#endregion
|
|
1032
|
-
//#region src/formats/speedscope/parse.ts
|
|
1033
|
-
const parseSpeedscopeProfile = (data) => parseJson(data);
|
|
1034
|
-
|
|
1035
|
-
//#endregion
|
|
1036
|
-
//#region src/formats/speedscope/summarize.ts
|
|
1037
|
-
const summarizeSpeedscopeProfile = (profile, options) => {
|
|
2011
|
+
//#region src/formats/speedscope/aggregate.ts
|
|
2012
|
+
const aggregateSpeedscopeProfile = (profile, options) => {
|
|
1038
2013
|
const nodes = profile.shared.frames.map((frame, id) => ({
|
|
1039
2014
|
...frame,
|
|
1040
2015
|
id
|
|
1041
2016
|
}));
|
|
1042
|
-
return profile.profiles.map((profile) => profile.type === `sampled` ?
|
|
2017
|
+
return profile.profiles.map((profile) => profile.type === `sampled` ? aggregateSampled(profile, nodes, options) : aggregateEvented(profile, nodes, options));
|
|
1043
2018
|
};
|
|
1044
|
-
const
|
|
1045
|
-
const
|
|
2019
|
+
const aggregateSampled = (profile, nodes, options) => {
|
|
2020
|
+
const profileAggregator = makeProfileAggregator(profile.unit, options);
|
|
1046
2021
|
for (let index = 0; index < profile.samples.length; index++) {
|
|
1047
2022
|
const weight = profile.weights[index];
|
|
1048
2023
|
if (weight <= 0) continue;
|
|
1049
2024
|
const sampleNodes = profile.samples[index].map((frameIndex) => nodes[frameIndex]).reverse();
|
|
1050
2025
|
if (sampleNodes.length === 0) continue;
|
|
1051
|
-
|
|
2026
|
+
profileAggregator.addSample({
|
|
1052
2027
|
values: [weight],
|
|
1053
2028
|
nodes: sampleNodes
|
|
1054
2029
|
});
|
|
1055
2030
|
}
|
|
1056
|
-
return
|
|
2031
|
+
return profileAggregator.aggregate();
|
|
1057
2032
|
};
|
|
1058
|
-
const
|
|
1059
|
-
const
|
|
2033
|
+
const aggregateEvented = (profile, nodes, options) => {
|
|
2034
|
+
const profileAggregator = makeProfileAggregator(profile.unit, options);
|
|
1060
2035
|
const stack = [];
|
|
1061
2036
|
const emitTopSelfTime = (at) => {
|
|
1062
2037
|
if (stack.length === 0) return;
|
|
1063
2038
|
const top = stack.at(-1);
|
|
1064
2039
|
const selfTime = at - top.lastChildClosed;
|
|
1065
2040
|
if (selfTime <= 0) return;
|
|
1066
|
-
|
|
2041
|
+
profileAggregator.addSample({
|
|
1067
2042
|
values: [selfTime],
|
|
1068
2043
|
nodes: stack.map((entry) => entry.node).reverse()
|
|
1069
2044
|
});
|
|
@@ -1080,9 +2055,9 @@ const summarizeEvented = (profile, nodes, options) => {
|
|
|
1080
2055
|
stack.pop();
|
|
1081
2056
|
if (stack.length > 0) stack.at(-1).lastChildClosed = event.at;
|
|
1082
2057
|
}
|
|
1083
|
-
return
|
|
2058
|
+
return profileAggregator.aggregate();
|
|
1084
2059
|
};
|
|
1085
|
-
const
|
|
2060
|
+
const makeProfileAggregator = (unit, options) => new ProfileAggregator({
|
|
1086
2061
|
metrics: [determineMetric({
|
|
1087
2062
|
name: unit,
|
|
1088
2063
|
unit
|
|
@@ -1098,6 +2073,10 @@ const makeProfileBuilder = (unit, options) => new ProfileBuilder({
|
|
|
1098
2073
|
})
|
|
1099
2074
|
}, options);
|
|
1100
2075
|
|
|
2076
|
+
//#endregion
|
|
2077
|
+
//#region src/formats/speedscope/parse.ts
|
|
2078
|
+
const parseSpeedscopeProfileAsync = (data) => JumboJSON.parseAsync(data);
|
|
2079
|
+
|
|
1101
2080
|
//#endregion
|
|
1102
2081
|
//#region src/formats/speedscope/index.ts
|
|
1103
2082
|
const detectSpeedscopeProfile = (json) => {
|
|
@@ -1107,7 +2086,7 @@ const detectSpeedscopeProfile = (json) => {
|
|
|
1107
2086
|
return json;
|
|
1108
2087
|
};
|
|
1109
2088
|
/**
|
|
1110
|
-
*
|
|
2089
|
+
* Asynchronously converts the given Speedscope profile to Markdown.
|
|
1111
2090
|
*
|
|
1112
2091
|
* It is assumed that {@link data} is a valid Speedscope JSON file. The behavior
|
|
1113
2092
|
* of this function is undefined for invalid profiles.
|
|
@@ -1116,19 +2095,11 @@ const detectSpeedscopeProfile = (json) => {
|
|
|
1116
2095
|
* for supported tools and generation instructions
|
|
1117
2096
|
* (`profiler-md --help speedscope`).
|
|
1118
2097
|
*/
|
|
1119
|
-
const
|
|
2098
|
+
const speedscopeProfileToMdAsync = async (data, options) => speedscopeProfileToMdInternal(await parseSpeedscopeProfileAsync(data), options);
|
|
1120
2099
|
const speedscopeProfileToMdInternal = (profile, options) => {
|
|
1121
|
-
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1122
|
-
return
|
|
1123
|
-
};
|
|
1124
|
-
|
|
1125
|
-
//#endregion
|
|
1126
|
-
//#region src/formats/v8/cpu-profile/format.ts
|
|
1127
|
-
const formatV8CpuProfile = (profile, options) => formatProfile(profile, options);
|
|
1128
|
-
|
|
1129
|
-
//#endregion
|
|
1130
|
-
//#region src/formats/v8/cpu-profile/parse.ts
|
|
1131
|
-
const parseV8CpuProfile = (data) => parseJson(data);
|
|
2100
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
2101
|
+
return aggregateSpeedscopeProfile(profile, normalizedOptions).map((profile) => formatProfile(profile, normalizedOptions)).join(`\n\n`);
|
|
2102
|
+
};
|
|
1132
2103
|
|
|
1133
2104
|
//#endregion
|
|
1134
2105
|
//#region src/formats/v8/common.ts
|
|
@@ -1146,9 +2117,9 @@ const callFrameFunctionInput = (callFrame) => {
|
|
|
1146
2117
|
};
|
|
1147
2118
|
|
|
1148
2119
|
//#endregion
|
|
1149
|
-
//#region src/formats/v8/cpu-profile/
|
|
1150
|
-
const
|
|
1151
|
-
const
|
|
2120
|
+
//#region src/formats/v8/cpu-profile/aggregate.ts
|
|
2121
|
+
const aggregateV8CpuProfile = (profile, options) => {
|
|
2122
|
+
const profileAggregator = new ProfileAggregator({
|
|
1152
2123
|
metrics: [MICROSECONDS],
|
|
1153
2124
|
functionKey: (node) => callFrameKey(node.callFrame),
|
|
1154
2125
|
functionInput: (node) => callFrameFunctionInput(node.callFrame)
|
|
@@ -1180,7 +2151,7 @@ const summarizeV8CpuProfile = (profile, options) => {
|
|
|
1180
2151
|
if (parentIndex === -1) break;
|
|
1181
2152
|
currentNode = profile.nodes[parentIndex];
|
|
1182
2153
|
}
|
|
1183
|
-
|
|
2154
|
+
profileAggregator.addSample({
|
|
1184
2155
|
values: [timeDelta],
|
|
1185
2156
|
nodes
|
|
1186
2157
|
});
|
|
@@ -1188,7 +2159,7 @@ const summarizeV8CpuProfile = (profile, options) => {
|
|
|
1188
2159
|
for (const node of profile.nodes) {
|
|
1189
2160
|
if (!node.positionTicks) continue;
|
|
1190
2161
|
const selfTime = indexToSelfTime[node.id];
|
|
1191
|
-
|
|
2162
|
+
profileAggregator.addLineMetrics({
|
|
1192
2163
|
node,
|
|
1193
2164
|
lines: node.positionTicks.map(({ line, ticks }) => ({
|
|
1194
2165
|
line,
|
|
@@ -1197,9 +2168,13 @@ const summarizeV8CpuProfile = (profile, options) => {
|
|
|
1197
2168
|
}))
|
|
1198
2169
|
});
|
|
1199
2170
|
}
|
|
1200
|
-
return
|
|
2171
|
+
return profileAggregator.aggregate();
|
|
1201
2172
|
};
|
|
1202
2173
|
|
|
2174
|
+
//#endregion
|
|
2175
|
+
//#region src/formats/v8/cpu-profile/parse.ts
|
|
2176
|
+
const parseV8CpuProfileAsync = (data) => JumboJSON.parseAsync(data);
|
|
2177
|
+
|
|
1203
2178
|
//#endregion
|
|
1204
2179
|
//#region src/formats/v8/cpu-profile/index.ts
|
|
1205
2180
|
const detectV8CpuProfile = (json) => {
|
|
@@ -1209,7 +2184,7 @@ const detectV8CpuProfile = (json) => {
|
|
|
1209
2184
|
return json;
|
|
1210
2185
|
};
|
|
1211
2186
|
/**
|
|
1212
|
-
*
|
|
2187
|
+
* Asynchronously converts the given V8 CPU profile to Markdown.
|
|
1213
2188
|
*
|
|
1214
2189
|
* It is assumed that {@link data} is a valid profile. The behavior of this
|
|
1215
2190
|
* function is undefined for invalid profiles.
|
|
@@ -1218,24 +2193,16 @@ const detectV8CpuProfile = (json) => {
|
|
|
1218
2193
|
* for supported runtimes and generation instructions
|
|
1219
2194
|
* (`profiler-md --help v8-cpu-profile`).
|
|
1220
2195
|
*/
|
|
1221
|
-
const
|
|
2196
|
+
const v8CpuProfileToMdAsync = async (data, options) => v8CpuProfileToMdInternal(await parseV8CpuProfileAsync(data), options);
|
|
1222
2197
|
const v8CpuProfileToMdInternal = (profile, options) => {
|
|
1223
2198
|
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1224
|
-
return
|
|
2199
|
+
return formatProfile(aggregateV8CpuProfile(profile, normalizedOptions), normalizedOptions);
|
|
1225
2200
|
};
|
|
1226
2201
|
|
|
1227
2202
|
//#endregion
|
|
1228
|
-
//#region src/formats/v8/heap-profile/
|
|
1229
|
-
const
|
|
1230
|
-
|
|
1231
|
-
//#endregion
|
|
1232
|
-
//#region src/formats/v8/heap-profile/parse.ts
|
|
1233
|
-
const parseV8HeapProfile = (data) => parseJson(data);
|
|
1234
|
-
|
|
1235
|
-
//#endregion
|
|
1236
|
-
//#region src/formats/v8/heap-profile/summarize.ts
|
|
1237
|
-
const summarizeV8HeapProfile = (profile, options) => {
|
|
1238
|
-
const profileBuilder = new ProfileBuilder({
|
|
2203
|
+
//#region src/formats/v8/heap-profile/aggregate.ts
|
|
2204
|
+
const aggregateV8HeapProfile = (profile, options) => {
|
|
2205
|
+
const profileAggregator = new ProfileAggregator({
|
|
1239
2206
|
metrics: [BYTES],
|
|
1240
2207
|
functionKey: (node) => callFrameKey(node.callFrame),
|
|
1241
2208
|
functionInput: (node) => callFrameFunctionInput(node.callFrame)
|
|
@@ -1256,733 +2223,208 @@ const summarizeV8HeapProfile = (profile, options) => {
|
|
|
1256
2223
|
indexToParentIndex.push(parentIndex);
|
|
1257
2224
|
for (const child of node.children) stack.push({
|
|
1258
2225
|
node: child,
|
|
1259
|
-
parentIndex: index
|
|
1260
|
-
});
|
|
1261
|
-
} while (stack.length > 0);
|
|
1262
|
-
for (const { size, nodeId } of profile.samples) {
|
|
1263
|
-
const nodeIndex = idToIndex[nodeId];
|
|
1264
|
-
if (nodeIndex === void 0) continue;
|
|
1265
|
-
const nodes = [];
|
|
1266
|
-
let currentIndex = nodeIndex;
|
|
1267
|
-
while (true) {
|
|
1268
|
-
nodes.push(flatNodes[currentIndex]);
|
|
1269
|
-
const parentIndex = indexToParentIndex[currentIndex];
|
|
1270
|
-
if (parentIndex === -1) break;
|
|
1271
|
-
currentIndex = parentIndex;
|
|
1272
|
-
}
|
|
1273
|
-
|
|
1274
|
-
values: [size],
|
|
1275
|
-
nodes
|
|
1276
|
-
});
|
|
1277
|
-
}
|
|
1278
|
-
return
|
|
1279
|
-
};
|
|
1280
|
-
|
|
1281
|
-
//#endregion
|
|
1282
|
-
//#region src/formats/v8/heap-profile/index.ts
|
|
1283
|
-
const detectV8HeapProfile = (json) => {
|
|
1284
|
-
if (typeof json !== `object` || json === null) return;
|
|
1285
|
-
const object = json;
|
|
1286
|
-
if (typeof object.head !== `object` || object.head === null || !Array.isArray(object.samples)) return;
|
|
1287
|
-
return json;
|
|
1288
|
-
};
|
|
1289
|
-
/**
|
|
1290
|
-
* Converts the given V8 sampling heap profile to Markdown.
|
|
1291
|
-
*
|
|
1292
|
-
* It is assumed that {@link data} is a valid profile. The behavior of this
|
|
1293
|
-
* function is undefined for invalid profiles.
|
|
1294
|
-
*
|
|
1295
|
-
* See the [V8 heap profile docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-heap-profile.md)
|
|
1296
|
-
* for supported runtimes and generation instructions
|
|
1297
|
-
* (`profiler-md --help v8-heap-profile`).
|
|
1298
|
-
*/
|
|
1299
|
-
const v8HeapProfileToMd = (data, options) => v8HeapProfileToMdInternal(parseV8HeapProfile(data), options);
|
|
1300
|
-
const v8HeapProfileToMdInternal = (profile, options) => {
|
|
1301
|
-
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
1302
|
-
return formatV8HeapProfile(summarizeV8HeapProfile(profile, normalizedOptions), normalizedOptions);
|
|
1303
|
-
};
|
|
1304
|
-
|
|
1305
|
-
//#endregion
|
|
1306
|
-
//#region src/formats/v8/heap-snapshot/format.ts
|
|
1307
|
-
const formatV8HeapSnapshot = (snapshot, options) => `${[
|
|
1308
|
-
`# Heap snapshot`,
|
|
1309
|
-
formatOverallSummary(snapshot),
|
|
1310
|
-
formatLargestConstructors(snapshot, options),
|
|
1311
|
-
formatLargestClosures(snapshot, options),
|
|
1312
|
-
formatLargestStrings(snapshot, options)
|
|
1313
|
-
].filter(Boolean).join(`\n\n`)}\n`;
|
|
1314
|
-
const formatOverallSummary = ({ totalSize, nodeCount, edgeCount, nodeCategoryToStats }) => {
|
|
1315
|
-
const hottestObjectCategories = [...nodeCategoryToStats].sort(([, stats1], [, stats2]) => stats2.size - stats1.size);
|
|
1316
|
-
return [`Allocated ${formatBytes(totalSize)} across ${formatCount(nodeCount)} objects and ${formatCount(edgeCount)} references.`, formatTable([
|
|
1317
|
-
`Category`,
|
|
1318
|
-
{
|
|
1319
|
-
content: `%`,
|
|
1320
|
-
align: `right`
|
|
1321
|
-
},
|
|
1322
|
-
{
|
|
1323
|
-
content: `Size`,
|
|
1324
|
-
align: `right`
|
|
1325
|
-
},
|
|
1326
|
-
{
|
|
1327
|
-
content: `Objects`,
|
|
1328
|
-
align: `right`
|
|
1329
|
-
}
|
|
1330
|
-
], hottestObjectCategories.map(([type, { size, nodeCount: objectCount }]) => [
|
|
1331
|
-
type,
|
|
1332
|
-
formatPercent(size / totalSize),
|
|
1333
|
-
formatBytes(size),
|
|
1334
|
-
formatCount(objectCount)
|
|
1335
|
-
]))].join(`\n\n`);
|
|
1336
|
-
};
|
|
1337
|
-
const formatLargestConstructors = (snapshot, options) => [
|
|
1338
|
-
`## Largest constructors`,
|
|
1339
|
-
formatLargestSelfSizeConstructors(snapshot, options),
|
|
1340
|
-
formatLargestRetainedSizeConstructors(snapshot, options)
|
|
1341
|
-
].join(`\n\n`);
|
|
1342
|
-
const formatLargestSelfSizeConstructors = (snapshot, options) => {
|
|
1343
|
-
const { totalSize, constructors } = snapshot;
|
|
1344
|
-
const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.selfSize);
|
|
1345
|
-
const largestInstanceSections = largestConstructors.map((constructor) => formatLargestSelfSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
|
|
1346
|
-
return [
|
|
1347
|
-
`### Self size`,
|
|
1348
|
-
`Constructors ranked by bytes allocated for their instances, excluding objects kept reachable by them.`,
|
|
1349
|
-
formatTable([
|
|
1350
|
-
{
|
|
1351
|
-
content: `%`,
|
|
1352
|
-
align: `right`
|
|
1353
|
-
},
|
|
1354
|
-
{
|
|
1355
|
-
content: `Size`,
|
|
1356
|
-
align: `right`
|
|
1357
|
-
},
|
|
1358
|
-
{
|
|
1359
|
-
content: `Instances`,
|
|
1360
|
-
align: `right`
|
|
1361
|
-
},
|
|
1362
|
-
`Constructor`,
|
|
1363
|
-
`Location`
|
|
1364
|
-
], largestConstructors.map((constructor) => [
|
|
1365
|
-
formatPercent(constructor.selfSize / totalSize),
|
|
1366
|
-
formatBytes(constructor.selfSize),
|
|
1367
|
-
formatCount(constructor.instances.length),
|
|
1368
|
-
inlineCode(constructor.name),
|
|
1369
|
-
formatProfileLocation(constructor.location, options)
|
|
1370
|
-
])),
|
|
1371
|
-
...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's self size.`] : [],
|
|
1372
|
-
...largestInstanceSections
|
|
1373
|
-
].join(`\n\n`);
|
|
1374
|
-
};
|
|
1375
|
-
const formatLargestSelfSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
|
|
1376
|
-
const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.selfSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.selfSize - group1.selfSize);
|
|
1377
|
-
if (largestInstanceGroups.length === 0) return;
|
|
1378
|
-
return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
|
|
1379
|
-
{
|
|
1380
|
-
content: `%`,
|
|
1381
|
-
align: `right`
|
|
1382
|
-
},
|
|
1383
|
-
{
|
|
1384
|
-
content: `Size`,
|
|
1385
|
-
align: `right`
|
|
1386
|
-
},
|
|
1387
|
-
{
|
|
1388
|
-
content: `Instances`,
|
|
1389
|
-
align: `right`
|
|
1390
|
-
},
|
|
1391
|
-
`Path`
|
|
1392
|
-
], largestInstanceGroups.map((group) => [
|
|
1393
|
-
formatPercent(group.selfSize / constructor.selfSize),
|
|
1394
|
-
formatBytes(group.selfSize),
|
|
1395
|
-
formatCount(group.instanceCount),
|
|
1396
|
-
inlineCode(group.retainerPath)
|
|
1397
|
-
]))].join(`\n\n`);
|
|
1398
|
-
};
|
|
1399
|
-
const formatLargestRetainedSizeConstructors = (snapshot, options) => {
|
|
1400
|
-
const { totalSize, constructors } = snapshot;
|
|
1401
|
-
const largestConstructors = selectTopN(constructors.filter(options.includeEntry), options.topN, (constructor) => constructor.retainedSize);
|
|
1402
|
-
const largestInstanceSections = largestConstructors.map((constructor) => formatLargestRetainedSizeConstructorInstances(constructor, snapshot, options)).filter((section) => section !== void 0);
|
|
1403
|
-
return [
|
|
1404
|
-
`### Retained size`,
|
|
1405
|
-
`Constructors ranked by bytes allocated for their instances and all objects that would be freed if their instances were garbage collected.`,
|
|
1406
|
-
formatTable([
|
|
1407
|
-
{
|
|
1408
|
-
content: `%`,
|
|
1409
|
-
align: `right`
|
|
1410
|
-
},
|
|
1411
|
-
{
|
|
1412
|
-
content: `Size`,
|
|
1413
|
-
align: `right`
|
|
1414
|
-
},
|
|
1415
|
-
{
|
|
1416
|
-
content: `Instances`,
|
|
1417
|
-
align: `right`
|
|
1418
|
-
},
|
|
1419
|
-
`Constructor`,
|
|
1420
|
-
`Location`
|
|
1421
|
-
], largestConstructors.map((constructor) => [
|
|
1422
|
-
formatPercent(constructor.retainedSize / totalSize),
|
|
1423
|
-
formatBytes(constructor.retainedSize),
|
|
1424
|
-
formatCount(constructor.instances.length),
|
|
1425
|
-
inlineCode(constructor.name),
|
|
1426
|
-
formatProfileLocation(constructor.location, options)
|
|
1427
|
-
])),
|
|
1428
|
-
...largestInstanceSections.length > 0 ? [`#### Instances`, `Instances ranked by contribution to each constructor's retained size.`] : [],
|
|
1429
|
-
...largestInstanceSections
|
|
1430
|
-
].join(`\n\n`);
|
|
1431
|
-
};
|
|
1432
|
-
const formatLargestRetainedSizeConstructorInstances = (constructor, { retainerPathOf }, options) => {
|
|
1433
|
-
const largestInstanceGroups = selectLargestInstancesByRetainerPath(constructor.instances, (instance) => instance.retainedSize, retainerPathOf, Math.ceil(options.topN / 4)).sort((group1, group2) => group2.retainedSize - group1.retainedSize);
|
|
1434
|
-
if (largestInstanceGroups.length === 0) return;
|
|
1435
|
-
return [`##### ${inlineCode(constructor.name)} (${formatProfileLocation(constructor.location, options)})`, formatTable([
|
|
1436
|
-
{
|
|
1437
|
-
content: `%`,
|
|
1438
|
-
align: `right`
|
|
1439
|
-
},
|
|
1440
|
-
{
|
|
1441
|
-
content: `Size`,
|
|
1442
|
-
align: `right`
|
|
1443
|
-
},
|
|
1444
|
-
{
|
|
1445
|
-
content: `Instances`,
|
|
1446
|
-
align: `right`
|
|
1447
|
-
},
|
|
1448
|
-
`Path`
|
|
1449
|
-
], largestInstanceGroups.map((group) => [
|
|
1450
|
-
formatPercent(group.retainedSize / constructor.retainedSize),
|
|
1451
|
-
formatBytes(group.retainedSize),
|
|
1452
|
-
formatCount(group.instanceCount),
|
|
1453
|
-
inlineCode(group.retainerPath)
|
|
1454
|
-
]))].join(`\n\n`);
|
|
1455
|
-
};
|
|
1456
|
-
const selectLargestInstancesByRetainerPath = (instances, sizeOf, retainerPathOf, topN) => {
|
|
1457
|
-
const heap = new MaxHeap(instances, sizeOf);
|
|
1458
|
-
const pathToGroup = /* @__PURE__ */ new Map();
|
|
1459
|
-
while (heap.length > 0 && pathToGroup.size < topN) {
|
|
1460
|
-
const instance = heap.pop();
|
|
1461
|
-
const retainerPath = retainerPathOf(instance.id);
|
|
1462
|
-
let group = pathToGroup.get(retainerPath);
|
|
1463
|
-
if (!group) {
|
|
1464
|
-
group = {
|
|
1465
|
-
retainerPath,
|
|
1466
|
-
instanceCount: 0,
|
|
1467
|
-
selfSize: 0,
|
|
1468
|
-
retainedSize: 0
|
|
1469
|
-
};
|
|
1470
|
-
pathToGroup.set(retainerPath, group);
|
|
1471
|
-
}
|
|
1472
|
-
group.instanceCount++;
|
|
1473
|
-
group.selfSize += instance.selfSize;
|
|
1474
|
-
group.retainedSize += instance.retainedSize;
|
|
1475
|
-
}
|
|
1476
|
-
return [...pathToGroup.values()];
|
|
1477
|
-
};
|
|
1478
|
-
const formatLargestClosures = (snapshot, options) => {
|
|
1479
|
-
const { totalSize, closures, retainerPathOf } = snapshot;
|
|
1480
|
-
const largestClosures = selectTopN(closures.filter((closure) => options.includeEntry({
|
|
1481
|
-
...closure,
|
|
1482
|
-
id: closure.largestInstanceId
|
|
1483
|
-
})), options.topN, (closure) => closure.retainedSize);
|
|
1484
|
-
const retainedSections = largestClosures.map((closure) => formatClosureRetainedObjects(closure, snapshot, options)).filter((section) => section !== void 0);
|
|
1485
|
-
return [
|
|
1486
|
-
`## Largest closures`,
|
|
1487
|
-
`Closures ranked by bytes that would be freed if the closure were garbage collected.`,
|
|
1488
|
-
formatTable([
|
|
1489
|
-
{
|
|
1490
|
-
content: `%`,
|
|
1491
|
-
align: `right`
|
|
1492
|
-
},
|
|
1493
|
-
{
|
|
1494
|
-
content: `Retained`,
|
|
1495
|
-
align: `right`
|
|
1496
|
-
},
|
|
1497
|
-
{
|
|
1498
|
-
content: `Instances`,
|
|
1499
|
-
align: `right`
|
|
1500
|
-
},
|
|
1501
|
-
{
|
|
1502
|
-
content: `Paths`,
|
|
1503
|
-
align: `right`
|
|
1504
|
-
},
|
|
1505
|
-
`Name`,
|
|
1506
|
-
`Location`,
|
|
1507
|
-
`Example path`
|
|
1508
|
-
], largestClosures.map((closure) => [
|
|
1509
|
-
formatPercent(closure.retainedSize / totalSize),
|
|
1510
|
-
formatBytes(closure.retainedSize),
|
|
1511
|
-
formatCount(closure.instanceIds.length),
|
|
1512
|
-
formatCount(new Set(closure.instanceIds.map(retainerPathOf)).size),
|
|
1513
|
-
inlineCode(closure.name),
|
|
1514
|
-
formatProfileLocation(closure.location, options),
|
|
1515
|
-
inlineCode(retainerPathOf(closure.largestInstanceId))
|
|
1516
|
-
])),
|
|
1517
|
-
...retainedSections.length > 0 ? [`### Retained`, `Objects ranked by contribution to each closure's retained size.`] : [],
|
|
1518
|
-
...retainedSections
|
|
1519
|
-
].join(`\n\n`);
|
|
1520
|
-
};
|
|
1521
|
-
const formatClosureRetainedObjects = (closure, { retainedNodesOf, retainerPathOf }, options) => {
|
|
1522
|
-
const instanceIdToSeen = new DynamicTypedArray(new Uint8Array(256));
|
|
1523
|
-
const allRetainedNodes = [];
|
|
1524
|
-
for (const instanceId of closure.instanceIds) for (const node of retainedNodesOf(instanceId)) {
|
|
1525
|
-
const seen = instanceIdToSeen.ensureCapacity(node.id + 1);
|
|
1526
|
-
if (seen[node.id]) continue;
|
|
1527
|
-
seen[node.id] = 1;
|
|
1528
|
-
if (options.includeEntry(node)) allRetainedNodes.push(node);
|
|
1529
|
-
}
|
|
1530
|
-
const retainedNodes = selectTopN(allRetainedNodes, Math.ceil(options.topN / 4), (node) => node.selfSize);
|
|
1531
|
-
if (retainedNodes.length === 0) return;
|
|
1532
|
-
return [`#### ${inlineCode(closure.name)} (${formatProfileLocation(closure.location, options)})`, formatTable([
|
|
1533
|
-
{
|
|
1534
|
-
content: `%`,
|
|
1535
|
-
align: `right`
|
|
1536
|
-
},
|
|
1537
|
-
{
|
|
1538
|
-
content: `Self`,
|
|
1539
|
-
align: `right`
|
|
1540
|
-
},
|
|
1541
|
-
`Name`,
|
|
1542
|
-
`Path`
|
|
1543
|
-
], retainedNodes.map((node) => [
|
|
1544
|
-
formatPercent(node.selfSize / closure.retainedSize),
|
|
1545
|
-
formatBytes(node.selfSize),
|
|
1546
|
-
inlineCode(node.name || `(unknown)`),
|
|
1547
|
-
inlineCode(retainerPathOf(node.id))
|
|
1548
|
-
]))].join(`\n\n`);
|
|
1549
|
-
};
|
|
1550
|
-
const formatLargestStrings = ({ totalSize, strings, retainerPathOf }, options) => {
|
|
1551
|
-
return [
|
|
1552
|
-
`## Largest strings`,
|
|
1553
|
-
`Strings ranked by bytes allocated for them.`,
|
|
1554
|
-
formatTable([
|
|
1555
|
-
{
|
|
1556
|
-
content: `%`,
|
|
1557
|
-
align: `right`
|
|
1558
|
-
},
|
|
1559
|
-
{
|
|
1560
|
-
content: `Size`,
|
|
1561
|
-
align: `right`
|
|
1562
|
-
},
|
|
1563
|
-
`Value`,
|
|
1564
|
-
`Path`
|
|
1565
|
-
], selectTopN(strings, options.topN, (string) => string.selfSize).map((string) => [
|
|
1566
|
-
formatPercent(string.selfSize / totalSize),
|
|
1567
|
-
formatBytes(string.selfSize),
|
|
1568
|
-
inlineCode(string.name),
|
|
1569
|
-
inlineCode(retainerPathOf(string.id))
|
|
1570
|
-
]))
|
|
1571
|
-
].join(`\n\n`);
|
|
2226
|
+
parentIndex: index
|
|
2227
|
+
});
|
|
2228
|
+
} while (stack.length > 0);
|
|
2229
|
+
for (const { size, nodeId } of profile.samples) {
|
|
2230
|
+
const nodeIndex = idToIndex[nodeId];
|
|
2231
|
+
if (nodeIndex === void 0) continue;
|
|
2232
|
+
const nodes = [];
|
|
2233
|
+
let currentIndex = nodeIndex;
|
|
2234
|
+
while (true) {
|
|
2235
|
+
nodes.push(flatNodes[currentIndex]);
|
|
2236
|
+
const parentIndex = indexToParentIndex[currentIndex];
|
|
2237
|
+
if (parentIndex === -1) break;
|
|
2238
|
+
currentIndex = parentIndex;
|
|
2239
|
+
}
|
|
2240
|
+
profileAggregator.addSample({
|
|
2241
|
+
values: [size],
|
|
2242
|
+
nodes
|
|
2243
|
+
});
|
|
2244
|
+
}
|
|
2245
|
+
return profileAggregator.aggregate();
|
|
1572
2246
|
};
|
|
1573
2247
|
|
|
1574
2248
|
//#endregion
|
|
1575
|
-
//#region src/formats/v8/heap-
|
|
1576
|
-
const
|
|
2249
|
+
//#region src/formats/v8/heap-profile/parse.ts
|
|
2250
|
+
const parseV8HeapProfileAsync = (data) => JumboJSON.parseAsync(data);
|
|
2251
|
+
|
|
2252
|
+
//#endregion
|
|
2253
|
+
//#region src/formats/v8/heap-profile/index.ts
|
|
2254
|
+
const detectV8HeapProfile = (json) => {
|
|
2255
|
+
if (typeof json !== `object` || json === null) return;
|
|
2256
|
+
const object = json;
|
|
2257
|
+
if (typeof object.head !== `object` || object.head === null || !Array.isArray(object.samples)) return;
|
|
2258
|
+
return json;
|
|
2259
|
+
};
|
|
2260
|
+
/**
|
|
2261
|
+
* Asynchronously converts the given V8 sampling heap profile to Markdown.
|
|
2262
|
+
*
|
|
2263
|
+
* It is assumed that {@link data} is a valid profile. The behavior of this
|
|
2264
|
+
* function is undefined for invalid profiles.
|
|
2265
|
+
*
|
|
2266
|
+
* See the [V8 heap profile docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/v8-heap-profile.md)
|
|
2267
|
+
* for supported runtimes and generation instructions
|
|
2268
|
+
* (`profiler-md --help v8-heap-profile`).
|
|
2269
|
+
*/
|
|
2270
|
+
const v8HeapProfileToMdAsync = async (data, options) => v8HeapProfileToMdInternal(await parseV8HeapProfileAsync(data), options);
|
|
2271
|
+
const v8HeapProfileToMdInternal = (profile, options) => {
|
|
2272
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
2273
|
+
return formatProfile(aggregateV8HeapProfile(profile, normalizedOptions), normalizedOptions);
|
|
2274
|
+
};
|
|
1577
2275
|
|
|
1578
2276
|
//#endregion
|
|
1579
|
-
//#region src/formats/v8/heap-snapshot/
|
|
1580
|
-
const
|
|
2277
|
+
//#region src/formats/v8/heap-snapshot/aggregate.ts
|
|
2278
|
+
const aggregateV8HeapSnapshot = (snapshot, options) => {
|
|
1581
2279
|
const { snapshot: { meta, node_count: nodeCount, edge_count: edgeCount }, nodes } = snapshot;
|
|
1582
2280
|
const [nodeTypes] = meta.node_types;
|
|
1583
2281
|
const fieldLayout = computeFieldLayout(meta);
|
|
1584
2282
|
const nodeAdjacencyGraph = computeNodeAdjacencyGraph(snapshot, fieldLayout);
|
|
1585
2283
|
const nodeOrdinalToLocation = computeNodeOrdinalToLocation(snapshot, nodeAdjacencyGraph, fieldLayout);
|
|
1586
|
-
const
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
2284
|
+
const snapshotAggregator = new SnapshotAggregator({
|
|
2285
|
+
nodeCount,
|
|
2286
|
+
edgeCount,
|
|
2287
|
+
nodeAdjacencyGraph,
|
|
2288
|
+
nodes,
|
|
2289
|
+
nodeFieldCount: fieldLayout.nodeFieldCount,
|
|
2290
|
+
nodeSelfSizeOffset: fieldLayout.nodeSelfSizeOffset,
|
|
2291
|
+
formatEdgeLabel: (retainerOrdinal, edgeIndex) => {
|
|
2292
|
+
const edgeLabel = formatEdgeLabel(edgeIndex, snapshot, fieldLayout, options);
|
|
2293
|
+
const retainerLabel = formatNodeLabel(retainerOrdinal, snapshot, fieldLayout, options);
|
|
2294
|
+
const retainerLocation = nodeOrdinalToLocation[retainerOrdinal];
|
|
2295
|
+
return `${edgeLabel} ${retainerLabel}${retainerLocation ? ` (${formatProfileLocation(retainerLocation, options)})` : ``}`;
|
|
2296
|
+
},
|
|
2297
|
+
formatNodeLabel: (nodeOrdinal) => formatNodeLabel(nodeOrdinal, snapshot, fieldLayout, options),
|
|
2298
|
+
isInternalNode: (nodeOrdinal) => {
|
|
2299
|
+
const nodeType = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeTypeOffset];
|
|
2300
|
+
return nodeType === fieldLayout.nodeTypeHidden || nodeType === fieldLayout.nodeTypeSynthetic;
|
|
2301
|
+
}
|
|
2302
|
+
});
|
|
1597
2303
|
for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
1598
|
-
const
|
|
1599
|
-
const selfSize = nodes[nodeIndex + fieldLayout.nodeSelfSizeOffset];
|
|
1600
|
-
totalSize += selfSize;
|
|
1601
|
-
const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
|
|
2304
|
+
const nodeType = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeTypeOffset];
|
|
1602
2305
|
const category = nodeTypes[nodeType];
|
|
1603
|
-
|
|
1604
|
-
if (!categoryStats) {
|
|
1605
|
-
categoryStats = {
|
|
1606
|
-
size: 0,
|
|
1607
|
-
nodeCount: 0
|
|
1608
|
-
};
|
|
1609
|
-
nodeCategoryToStats.set(category, categoryStats);
|
|
1610
|
-
}
|
|
1611
|
-
categoryStats.size += selfSize;
|
|
1612
|
-
categoryStats.nodeCount++;
|
|
2306
|
+
snapshotAggregator.addCategoryNode(nodeOrdinal, category);
|
|
1613
2307
|
switch (nodeType) {
|
|
1614
2308
|
case fieldLayout.nodeTypeObject:
|
|
1615
|
-
case fieldLayout.nodeTypeNative:
|
|
1616
|
-
|
|
1617
|
-
let constructorIndex = nameToConstructorIndex.get(name);
|
|
1618
|
-
let constructor;
|
|
1619
|
-
if (constructorIndex === void 0) {
|
|
1620
|
-
constructorIndex = constructors.length;
|
|
1621
|
-
constructor = {
|
|
1622
|
-
id: nodeOrdinal,
|
|
1623
|
-
name,
|
|
1624
|
-
location: void 0,
|
|
1625
|
-
selfSize: 0,
|
|
1626
|
-
retainedSize: 0,
|
|
1627
|
-
instances: []
|
|
1628
|
-
};
|
|
1629
|
-
constructors.push(constructor);
|
|
1630
|
-
nameToConstructorIndex.set(name, constructorIndex);
|
|
1631
|
-
} else constructor = constructors[constructorIndex];
|
|
1632
|
-
constructor.selfSize += selfSize;
|
|
1633
|
-
constructor.location ??= nodeOrdinalToLocation[nodeOrdinal];
|
|
1634
|
-
constructor.instances.push({
|
|
1635
|
-
id: nodeOrdinal,
|
|
1636
|
-
name: constructor.name,
|
|
1637
|
-
selfSize,
|
|
1638
|
-
retainedSize: nodeOrdinalToRetainedSize[nodeOrdinal],
|
|
1639
|
-
location: constructor.location
|
|
1640
|
-
});
|
|
1641
|
-
nodeOrdinalToConstructorIndex[nodeOrdinal] = constructorIndex;
|
|
2309
|
+
case fieldLayout.nodeTypeNative:
|
|
2310
|
+
snapshotAggregator.addConstructorNode(nodeOrdinal, nodeOrdinalToLocation[nodeOrdinal]);
|
|
1642
2311
|
break;
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
const name = formatNodeLabel(nodeIndex, snapshot, fieldLayout, options);
|
|
1646
|
-
const location = nodeOrdinalToLocation[nodeOrdinal];
|
|
1647
|
-
const key = `${name}|${location ? formatProfileLocation(location, options) : ``}`;
|
|
1648
|
-
const retainedSize = nodeOrdinalToRetainedSize[nodeOrdinal];
|
|
1649
|
-
let closureIndex = keyToClosureIndex.get(key);
|
|
1650
|
-
if (closureIndex === void 0) {
|
|
1651
|
-
closureIndex = closures.length;
|
|
1652
|
-
closures.push({
|
|
1653
|
-
name,
|
|
1654
|
-
location,
|
|
1655
|
-
retainedSize: 0,
|
|
1656
|
-
largestInstanceId: nodeOrdinal,
|
|
1657
|
-
instanceIds: []
|
|
1658
|
-
});
|
|
1659
|
-
keyToClosureIndex.set(key, closureIndex);
|
|
1660
|
-
}
|
|
1661
|
-
const closure = closures[closureIndex];
|
|
1662
|
-
closure.instanceIds.push(nodeOrdinal);
|
|
1663
|
-
if (retainedSize > nodeOrdinalToRetainedSize[closure.largestInstanceId]) closure.largestInstanceId = nodeOrdinal;
|
|
1664
|
-
nodeOrdinalToClosureIndex[nodeOrdinal] = closureIndex;
|
|
2312
|
+
case fieldLayout.nodeTypeClosure:
|
|
2313
|
+
snapshotAggregator.addClosureNode(nodeOrdinal, nodeOrdinalToLocation[nodeOrdinal]);
|
|
1665
2314
|
break;
|
|
1666
|
-
}
|
|
1667
2315
|
case fieldLayout.nodeTypeString:
|
|
1668
2316
|
case fieldLayout.nodeTypeSlicedString:
|
|
1669
2317
|
case fieldLayout.nodeTypeConcatenatedString:
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
name: formatNodeLabel(nodeIndex, snapshot, fieldLayout, options),
|
|
1673
|
-
selfSize,
|
|
1674
|
-
retainedSize: selfSize
|
|
1675
|
-
});
|
|
1676
|
-
break;
|
|
1677
|
-
}
|
|
1678
|
-
}
|
|
1679
|
-
attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToConstructorIndex, constructors);
|
|
1680
|
-
attributeGroupRetainedSizes(nodeOrdinalToRetainedSize, immediateDominatorGraph, nodeOrdinalToClosureIndex, closures);
|
|
1681
|
-
return {
|
|
1682
|
-
totalSize,
|
|
1683
|
-
nodeCount,
|
|
1684
|
-
edgeCount,
|
|
1685
|
-
nodeCategoryToStats,
|
|
1686
|
-
constructors,
|
|
1687
|
-
closures,
|
|
1688
|
-
strings,
|
|
1689
|
-
retainerPathOf: (nodeOrdinal) => computeRetainerPath(nodeOrdinal, snapshot, nodeAdjacencyGraph, nodeOrdinalToLocation, immediateDominatorGraph, fieldLayout, options),
|
|
1690
|
-
retainedNodesOf: (nodeOrdinal) => computeRetainedNodes(nodeOrdinal, snapshot, nodeOrdinalToRetainedSize, immediateDominatorGraph, fieldLayout, options)
|
|
1691
|
-
};
|
|
1692
|
-
};
|
|
1693
|
-
const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes, edges }, fieldLayout) => {
|
|
1694
|
-
const ordinalToSuccessorCount = new Int32Array(nodeCount);
|
|
1695
|
-
const ordinalToPredecessorCount = new Int32Array(nodeCount);
|
|
1696
|
-
let nodeEdgesStartIndex = 0;
|
|
1697
|
-
for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
1698
|
-
const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
|
|
1699
|
-
for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
|
|
1700
|
-
const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
|
|
1701
|
-
if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
|
|
1702
|
-
const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
|
|
1703
|
-
ordinalToSuccessorCount[nodeOrdinal]++;
|
|
1704
|
-
ordinalToPredecessorCount[successorOrdinal]++;
|
|
1705
|
-
}
|
|
1706
|
-
nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
|
|
1707
|
-
}
|
|
1708
|
-
const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
|
|
1709
|
-
const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
|
|
1710
|
-
for (let i = 0; i < nodeCount; i++) {
|
|
1711
|
-
ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
|
|
1712
|
-
ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
|
|
1713
|
-
}
|
|
1714
|
-
const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
|
|
1715
|
-
const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
|
|
1716
|
-
const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
|
|
1717
|
-
const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
|
|
1718
|
-
const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
|
|
1719
|
-
ordinalToSuccessorCount.fill(0);
|
|
1720
|
-
ordinalToPredecessorCount.fill(0);
|
|
1721
|
-
nodeEdgesStartIndex = 0;
|
|
1722
|
-
for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
1723
|
-
const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
|
|
1724
|
-
for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
|
|
1725
|
-
const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
|
|
1726
|
-
if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
|
|
1727
|
-
const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
|
|
1728
|
-
const successorOffset = ordinalToSuccessorStartOffset[nodeOrdinal] + ordinalToSuccessorCount[nodeOrdinal];
|
|
1729
|
-
offsetToSuccessorOrdinal[successorOffset] = successorOrdinal;
|
|
1730
|
-
offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
|
|
1731
|
-
ordinalToSuccessorCount[nodeOrdinal]++;
|
|
1732
|
-
const predecessorOffset = ordinalToPredecessorStartOffset[successorOrdinal] + ordinalToPredecessorCount[successorOrdinal];
|
|
1733
|
-
offsetToPredecessorOrdinal[predecessorOffset] = nodeOrdinal;
|
|
1734
|
-
offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
|
|
1735
|
-
ordinalToPredecessorCount[successorOrdinal]++;
|
|
1736
|
-
}
|
|
1737
|
-
nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
|
|
1738
|
-
}
|
|
1739
|
-
return {
|
|
1740
|
-
ordinalToSuccessorStartOffset,
|
|
1741
|
-
offsetToSuccessorOrdinal,
|
|
1742
|
-
offsetToSuccessorEdgeIndex,
|
|
1743
|
-
ordinalToPredecessorStartOffset,
|
|
1744
|
-
offsetToPredecessorOrdinal,
|
|
1745
|
-
offsetToPredecessorEdgeIndex
|
|
1746
|
-
};
|
|
1747
|
-
};
|
|
1748
|
-
const computeNodeOrdinalToLocation = ({ snapshot: { node_count: nodeCount }, nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
|
|
1749
|
-
const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
|
|
1750
|
-
const nodeOrdinal = nodeIndex / nodeFieldCount;
|
|
1751
|
-
const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
|
|
1752
|
-
const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
|
|
1753
|
-
for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
|
|
1754
|
-
const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
|
|
1755
|
-
if (strings[edges[edgeIndex + edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + edgeToNodeOffset];
|
|
1756
|
-
}
|
|
1757
|
-
};
|
|
1758
|
-
const scriptIdToFileLocation = /* @__PURE__ */ new Map();
|
|
1759
|
-
for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
|
|
1760
|
-
const scriptId = locations[locationIndex + locationScriptIdOffset];
|
|
1761
|
-
if (scriptIdToFileLocation.has(scriptId)) continue;
|
|
1762
|
-
const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
|
|
1763
|
-
if (nodes[nodeIndex + nodeTypeOffset] !== nodeTypeClosure) continue;
|
|
1764
|
-
const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
|
|
1765
|
-
if (sharedNodeIndex === void 0) continue;
|
|
1766
|
-
const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
|
|
1767
|
-
if (scriptNodeIndex === void 0) continue;
|
|
1768
|
-
const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
|
|
1769
|
-
if (locationNodeIndex === void 0) continue;
|
|
1770
|
-
const location = strings[nodes[locationNodeIndex + nodeNameOffset]];
|
|
1771
|
-
if (!location) continue;
|
|
1772
|
-
scriptIdToFileLocation.set(scriptId, location);
|
|
1773
|
-
}
|
|
1774
|
-
const nodeOrdinalToLocation = Array.from({ length: nodeCount });
|
|
1775
|
-
const fileLocationToUrl = /* @__PURE__ */ new Map();
|
|
1776
|
-
for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
|
|
1777
|
-
const scriptId = locations[locationIndex + locationScriptIdOffset];
|
|
1778
|
-
const fileLocation = scriptIdToFileLocation.get(scriptId);
|
|
1779
|
-
if (!fileLocation) continue;
|
|
1780
|
-
let url = fileLocationToUrl.get(fileLocation);
|
|
1781
|
-
if (url === void 0) {
|
|
1782
|
-
url = makeProfileLocation({ urlOrPath: fileLocation })?.url ?? null;
|
|
1783
|
-
fileLocationToUrl.set(fileLocation, url);
|
|
1784
|
-
}
|
|
1785
|
-
if (!url) continue;
|
|
1786
|
-
const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
|
|
1787
|
-
const line = locations[locationIndex + locationLineOffset];
|
|
1788
|
-
const column = locations[locationIndex + locationColumnOffset];
|
|
1789
|
-
nodeOrdinalToLocation[nodeIndex / nodeFieldCount] = {
|
|
1790
|
-
url,
|
|
1791
|
-
line: line + 1,
|
|
1792
|
-
column: column + 1
|
|
1793
|
-
};
|
|
1794
|
-
}
|
|
1795
|
-
return nodeOrdinalToLocation;
|
|
1796
|
-
};
|
|
1797
|
-
/**
|
|
1798
|
-
* Computes the immediate dominators of every node.
|
|
1799
|
-
*
|
|
1800
|
-
* Weak edges are excluded because they don't keep nodes alive.
|
|
1801
|
-
*
|
|
1802
|
-
* Uses the Lengauer-Tarjan dominator tree algorithm.
|
|
1803
|
-
*
|
|
1804
|
-
* @see https://en.wikipedia.org/wiki/Dominator_(graph_theory)
|
|
1805
|
-
* @see https://www.cs.princeton.edu/courses/archive/fall03/cs528/handouts/a%20fast%20algorithm%20for%20finding.pdf
|
|
1806
|
-
*/
|
|
1807
|
-
const computeImmediateDominatorGraph = (snapshot, { ordinalToSuccessorStartOffset, offsetToSuccessorOrdinal, ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal }) => {
|
|
1808
|
-
const { snapshot: { node_count: nodeCount } } = snapshot;
|
|
1809
|
-
const ordinalToImmediateDominatorOrdinal = new Int32Array(nodeCount).fill(-1);
|
|
1810
|
-
const dfsIndexToOrdinal = new Int32Array(nodeCount);
|
|
1811
|
-
const ordinalToParentOrdinal = new Int32Array(nodeCount).fill(-1);
|
|
1812
|
-
const ordinalToDfsIndex = new Int32Array(nodeCount).fill(-1);
|
|
1813
|
-
const ordinalToSemidominatorDfsIndex = new Int32Array(nodeCount);
|
|
1814
|
-
ordinalToDfsIndex[0] = 0;
|
|
1815
|
-
dfsIndexToOrdinal[0] = 0;
|
|
1816
|
-
const dfsStackOrdinals = new Int32Array(nodeCount);
|
|
1817
|
-
const dfsStackOffsets = new Int32Array(nodeCount);
|
|
1818
|
-
dfsStackOffsets[0] = ordinalToSuccessorStartOffset[0];
|
|
1819
|
-
let dfsIndex = 1;
|
|
1820
|
-
let dfsStackSize = 1;
|
|
1821
|
-
do {
|
|
1822
|
-
const topOffset = dfsStackSize - 1;
|
|
1823
|
-
const nodeOrdinal = dfsStackOrdinals[topOffset];
|
|
1824
|
-
const nextOffset = dfsStackOffsets[topOffset];
|
|
1825
|
-
if (nextOffset === ordinalToSuccessorStartOffset[nodeOrdinal + 1]) {
|
|
1826
|
-
dfsStackSize--;
|
|
1827
|
-
continue;
|
|
1828
|
-
}
|
|
1829
|
-
const childOrdinal = offsetToSuccessorOrdinal[nextOffset];
|
|
1830
|
-
dfsStackOffsets[topOffset]++;
|
|
1831
|
-
if (ordinalToDfsIndex[childOrdinal] !== -1) continue;
|
|
1832
|
-
ordinalToParentOrdinal[childOrdinal] = nodeOrdinal;
|
|
1833
|
-
ordinalToDfsIndex[childOrdinal] = dfsIndex;
|
|
1834
|
-
ordinalToSemidominatorDfsIndex[childOrdinal] = dfsIndex;
|
|
1835
|
-
dfsIndexToOrdinal[dfsIndex] = childOrdinal;
|
|
1836
|
-
dfsIndex++;
|
|
1837
|
-
dfsStackOrdinals[dfsStackSize] = childOrdinal;
|
|
1838
|
-
dfsStackOffsets[dfsStackSize] = ordinalToSuccessorStartOffset[childOrdinal];
|
|
1839
|
-
dfsStackSize++;
|
|
1840
|
-
} while (dfsStackSize > 0);
|
|
1841
|
-
const reachableCount = dfsIndex;
|
|
1842
|
-
const ancestorNodeOrdinalPath = new Int32Array(nodeCount);
|
|
1843
|
-
const ordinalToForestAncestorOrdinal = new Int32Array(nodeCount).fill(-1);
|
|
1844
|
-
const ordinalToMinSemiAncestorOrdinal = new Int32Array(nodeCount);
|
|
1845
|
-
for (let i = 0; i < nodeCount; i++) ordinalToMinSemiAncestorOrdinal[i] = i;
|
|
1846
|
-
const compressAncestorPath = (startNodeOrdinal) => {
|
|
1847
|
-
let pathLength = 0;
|
|
1848
|
-
let nodeOrdinal = startNodeOrdinal;
|
|
1849
|
-
while (ordinalToForestAncestorOrdinal[nodeOrdinal] !== -1 && ordinalToForestAncestorOrdinal[ordinalToForestAncestorOrdinal[nodeOrdinal]] !== -1) {
|
|
1850
|
-
ancestorNodeOrdinalPath[pathLength++] = nodeOrdinal;
|
|
1851
|
-
nodeOrdinal = ordinalToForestAncestorOrdinal[nodeOrdinal];
|
|
1852
|
-
}
|
|
1853
|
-
for (let pathIndex = pathLength - 1; pathIndex >= 0; pathIndex--) {
|
|
1854
|
-
const pathNodeOrdinal = ancestorNodeOrdinalPath[pathIndex];
|
|
1855
|
-
const ancestorOrdinal = ordinalToForestAncestorOrdinal[pathNodeOrdinal];
|
|
1856
|
-
if (ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[ancestorOrdinal]] < ordinalToSemidominatorDfsIndex[ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal]]) ordinalToMinSemiAncestorOrdinal[pathNodeOrdinal] = ordinalToMinSemiAncestorOrdinal[ancestorOrdinal];
|
|
1857
|
-
ordinalToForestAncestorOrdinal[pathNodeOrdinal] = ordinalToForestAncestorOrdinal[ancestorOrdinal];
|
|
1858
|
-
}
|
|
1859
|
-
};
|
|
1860
|
-
const minSemiAncestorOrdinal = (nodeOrdinal) => {
|
|
1861
|
-
if (ordinalToForestAncestorOrdinal[nodeOrdinal] === -1) return nodeOrdinal;
|
|
1862
|
-
compressAncestorPath(nodeOrdinal);
|
|
1863
|
-
return ordinalToMinSemiAncestorOrdinal[nodeOrdinal];
|
|
1864
|
-
};
|
|
1865
|
-
const pendingHeadOrdinals = new Int32Array(nodeCount).fill(-1);
|
|
1866
|
-
const pendingNextOrdinals = new Int32Array(nodeCount).fill(-1);
|
|
1867
|
-
for (let dfsIndex = reachableCount - 1; dfsIndex >= 1; dfsIndex--) {
|
|
1868
|
-
const nodeOrdinal = dfsIndexToOrdinal[dfsIndex];
|
|
1869
|
-
const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
|
|
1870
|
-
const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
|
|
1871
|
-
for (let predecessorOffset = predecessorStartOffset; predecessorOffset < predecessorEndOffset; predecessorOffset++) {
|
|
1872
|
-
const predecessorOrdinal = offsetToPredecessorOrdinal[predecessorOffset];
|
|
1873
|
-
if (ordinalToDfsIndex[predecessorOrdinal] === -1) continue;
|
|
1874
|
-
const minAncestorOrdinal = minSemiAncestorOrdinal(predecessorOrdinal);
|
|
1875
|
-
if (ordinalToSemidominatorDfsIndex[minAncestorOrdinal] < ordinalToSemidominatorDfsIndex[nodeOrdinal]) ordinalToSemidominatorDfsIndex[nodeOrdinal] = ordinalToSemidominatorDfsIndex[minAncestorOrdinal];
|
|
1876
|
-
}
|
|
1877
|
-
const semiBucketOrdinal = dfsIndexToOrdinal[ordinalToSemidominatorDfsIndex[nodeOrdinal]];
|
|
1878
|
-
pendingNextOrdinals[nodeOrdinal] = pendingHeadOrdinals[semiBucketOrdinal];
|
|
1879
|
-
pendingHeadOrdinals[semiBucketOrdinal] = nodeOrdinal;
|
|
1880
|
-
ordinalToForestAncestorOrdinal[nodeOrdinal] = ordinalToParentOrdinal[nodeOrdinal];
|
|
1881
|
-
const parentOrdinal = ordinalToParentOrdinal[nodeOrdinal];
|
|
1882
|
-
let pendingOrdinal = pendingHeadOrdinals[parentOrdinal];
|
|
1883
|
-
pendingHeadOrdinals[parentOrdinal] = -1;
|
|
1884
|
-
while (pendingOrdinal !== -1) {
|
|
1885
|
-
const nextPending = pendingNextOrdinals[pendingOrdinal];
|
|
1886
|
-
const ancestorOrdinal = minSemiAncestorOrdinal(pendingOrdinal);
|
|
1887
|
-
ordinalToImmediateDominatorOrdinal[pendingOrdinal] = ordinalToSemidominatorDfsIndex[ancestorOrdinal] < ordinalToSemidominatorDfsIndex[pendingOrdinal] ? ancestorOrdinal : parentOrdinal;
|
|
1888
|
-
pendingOrdinal = nextPending;
|
|
2318
|
+
snapshotAggregator.addStringNode(nodeOrdinal, formatNodeLabel(nodeOrdinal, snapshot, fieldLayout, options));
|
|
2319
|
+
break;
|
|
1889
2320
|
}
|
|
1890
2321
|
}
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
2322
|
+
return snapshotAggregator.aggregate();
|
|
2323
|
+
};
|
|
2324
|
+
const computeNodeAdjacencyGraph = ({ snapshot: { node_count: nodeCount }, nodes, edges }, fieldLayout) => {
|
|
2325
|
+
const ordinalToSuccessorCount = new Int32Array(nodeCount);
|
|
2326
|
+
const ordinalToPredecessorCount = new Int32Array(nodeCount);
|
|
2327
|
+
let nodeEdgesStartIndex = 0;
|
|
2328
|
+
for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
2329
|
+
const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
|
|
2330
|
+
for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
|
|
2331
|
+
const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
|
|
2332
|
+
if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
|
|
2333
|
+
const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
|
|
2334
|
+
ordinalToSuccessorCount[nodeOrdinal]++;
|
|
2335
|
+
ordinalToPredecessorCount[successorOrdinal]++;
|
|
2336
|
+
}
|
|
2337
|
+
nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
|
|
1894
2338
|
}
|
|
1895
|
-
|
|
1896
|
-
const
|
|
1897
|
-
for (let
|
|
1898
|
-
|
|
1899
|
-
|
|
2339
|
+
const ordinalToSuccessorStartOffset = new Int32Array(nodeCount + 1);
|
|
2340
|
+
const ordinalToPredecessorStartOffset = new Int32Array(nodeCount + 1);
|
|
2341
|
+
for (let i = 0; i < nodeCount; i++) {
|
|
2342
|
+
ordinalToSuccessorStartOffset[i + 1] = ordinalToSuccessorStartOffset[i] + ordinalToSuccessorCount[i];
|
|
2343
|
+
ordinalToPredecessorStartOffset[i + 1] = ordinalToPredecessorStartOffset[i] + ordinalToPredecessorCount[i];
|
|
1900
2344
|
}
|
|
1901
|
-
const
|
|
1902
|
-
|
|
1903
|
-
const
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
2345
|
+
const totalEdges = ordinalToSuccessorStartOffset[nodeCount];
|
|
2346
|
+
const offsetToSuccessorOrdinal = new Int32Array(totalEdges);
|
|
2347
|
+
const offsetToSuccessorEdgeIndex = new Int32Array(totalEdges);
|
|
2348
|
+
const offsetToPredecessorOrdinal = new Int32Array(totalEdges);
|
|
2349
|
+
const offsetToPredecessorEdgeIndex = new Int32Array(totalEdges);
|
|
2350
|
+
ordinalToSuccessorCount.fill(0);
|
|
2351
|
+
ordinalToPredecessorCount.fill(0);
|
|
2352
|
+
nodeEdgesStartIndex = 0;
|
|
2353
|
+
for (let nodeOrdinal = 0; nodeOrdinal < nodeCount; nodeOrdinal++) {
|
|
2354
|
+
const nodeEdgeCount = nodes[nodeOrdinal * fieldLayout.nodeFieldCount + fieldLayout.nodeEdgeCountOffset];
|
|
2355
|
+
for (let edgeOrdinal = 0; edgeOrdinal < nodeEdgeCount; edgeOrdinal++) {
|
|
2356
|
+
const edgeIndex = nodeEdgesStartIndex + edgeOrdinal * fieldLayout.edgeFieldCount;
|
|
2357
|
+
if (edges[edgeIndex + fieldLayout.edgeTypeOffset] === fieldLayout.edgeTypeWeak) continue;
|
|
2358
|
+
const successorOrdinal = edges[edgeIndex + fieldLayout.edgeToNodeOffset] / fieldLayout.nodeFieldCount;
|
|
2359
|
+
const successorOffset = ordinalToSuccessorStartOffset[nodeOrdinal] + ordinalToSuccessorCount[nodeOrdinal];
|
|
2360
|
+
offsetToSuccessorOrdinal[successorOffset] = successorOrdinal;
|
|
2361
|
+
offsetToSuccessorEdgeIndex[successorOffset] = edgeIndex;
|
|
2362
|
+
ordinalToSuccessorCount[nodeOrdinal]++;
|
|
2363
|
+
const predecessorOffset = ordinalToPredecessorStartOffset[successorOrdinal] + ordinalToPredecessorCount[successorOrdinal];
|
|
2364
|
+
offsetToPredecessorOrdinal[predecessorOffset] = nodeOrdinal;
|
|
2365
|
+
offsetToPredecessorEdgeIndex[predecessorOffset] = edgeIndex;
|
|
2366
|
+
ordinalToPredecessorCount[successorOrdinal]++;
|
|
1910
2367
|
}
|
|
2368
|
+
nodeEdgesStartIndex += nodeEdgeCount * fieldLayout.edgeFieldCount;
|
|
1911
2369
|
}
|
|
1912
2370
|
return {
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
2371
|
+
ordinalToSuccessorStartOffset,
|
|
2372
|
+
offsetToSuccessorOrdinal,
|
|
2373
|
+
offsetToSuccessorEdgeIndex,
|
|
2374
|
+
ordinalToPredecessorStartOffset,
|
|
2375
|
+
offsetToPredecessorOrdinal,
|
|
2376
|
+
offsetToPredecessorEdgeIndex
|
|
1917
2377
|
};
|
|
1918
2378
|
};
|
|
1919
|
-
const
|
|
1920
|
-
const
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
const
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
};
|
|
1928
|
-
const computeRetainerPath = (nodeOrdinal, snapshot, { ordinalToPredecessorStartOffset, offsetToPredecessorOrdinal, offsetToPredecessorEdgeIndex }, nodeOrdinalToLocation, { ordinalToImmediateDominatorOrdinal }, fieldLayout, options) => {
|
|
1929
|
-
const { nodes } = snapshot;
|
|
1930
|
-
const hops = [];
|
|
1931
|
-
while (true) {
|
|
1932
|
-
const predecessorStartOffset = ordinalToPredecessorStartOffset[nodeOrdinal];
|
|
1933
|
-
const predecessorEndOffset = ordinalToPredecessorStartOffset[nodeOrdinal + 1];
|
|
1934
|
-
if (predecessorStartOffset === predecessorEndOffset) break;
|
|
1935
|
-
const dominatorOrdinal = ordinalToImmediateDominatorOrdinal[nodeOrdinal];
|
|
1936
|
-
let predecessorOffset = -1;
|
|
1937
|
-
for (let offset = predecessorStartOffset; offset < predecessorEndOffset; offset++) if (offsetToPredecessorOrdinal[offset] === dominatorOrdinal) {
|
|
1938
|
-
predecessorOffset = offset;
|
|
1939
|
-
break;
|
|
1940
|
-
}
|
|
1941
|
-
if (predecessorOffset === -1) {
|
|
1942
|
-
nodeOrdinal = dominatorOrdinal;
|
|
1943
|
-
continue;
|
|
2379
|
+
const computeNodeOrdinalToLocation = ({ snapshot: { node_count: nodeCount }, nodes, edges, strings, locations }, { ordinalToSuccessorStartOffset, offsetToSuccessorEdgeIndex }, { nodeFieldCount, nodeTypeOffset, nodeNameOffset, nodeTypeClosure, edgeNameOrIndexOffset, edgeToNodeOffset, locationFieldCount, locationScriptIdOffset, locationObjectIndexOffset, locationLineOffset, locationColumnOffset }) => {
|
|
2380
|
+
const namedEdgeToNodeIndex = (nodeIndex, targetEdgeName) => {
|
|
2381
|
+
const nodeOrdinal = nodeIndex / nodeFieldCount;
|
|
2382
|
+
const successorStartOffset = ordinalToSuccessorStartOffset[nodeOrdinal];
|
|
2383
|
+
const successorEndOffset = ordinalToSuccessorStartOffset[nodeOrdinal + 1];
|
|
2384
|
+
for (let successorOffset = successorStartOffset; successorOffset < successorEndOffset; successorOffset++) {
|
|
2385
|
+
const edgeIndex = offsetToSuccessorEdgeIndex[successorOffset];
|
|
2386
|
+
if (strings[edges[edgeIndex + edgeNameOrIndexOffset]] === targetEdgeName) return edges[edgeIndex + edgeToNodeOffset];
|
|
1944
2387
|
}
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
const
|
|
1949
|
-
|
|
1950
|
-
const
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
2388
|
+
};
|
|
2389
|
+
const scriptIdToFileLocation = /* @__PURE__ */ new Map();
|
|
2390
|
+
for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
|
|
2391
|
+
const scriptId = locations[locationIndex + locationScriptIdOffset];
|
|
2392
|
+
if (scriptIdToFileLocation.has(scriptId)) continue;
|
|
2393
|
+
const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
|
|
2394
|
+
if (nodes[nodeIndex + nodeTypeOffset] !== nodeTypeClosure) continue;
|
|
2395
|
+
const sharedNodeIndex = namedEdgeToNodeIndex(nodeIndex, `shared`);
|
|
2396
|
+
if (sharedNodeIndex === void 0) continue;
|
|
2397
|
+
const scriptNodeIndex = namedEdgeToNodeIndex(sharedNodeIndex, `script`);
|
|
2398
|
+
if (scriptNodeIndex === void 0) continue;
|
|
2399
|
+
const locationNodeIndex = namedEdgeToNodeIndex(scriptNodeIndex, `name`);
|
|
2400
|
+
if (locationNodeIndex === void 0) continue;
|
|
2401
|
+
const location = strings[nodes[locationNodeIndex + nodeNameOffset]];
|
|
2402
|
+
if (!location) continue;
|
|
2403
|
+
scriptIdToFileLocation.set(scriptId, location);
|
|
1957
2404
|
}
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
const
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
const
|
|
1971
|
-
const
|
|
1972
|
-
const
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
});
|
|
1979
|
-
const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
|
|
1980
|
-
const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
|
|
1981
|
-
for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) dominateeOrdinals.push(offsetToImmediateDominateeOrdinal[offset]);
|
|
2405
|
+
const nodeOrdinalToLocation = Array.from({ length: nodeCount });
|
|
2406
|
+
const fileLocationToUrl = /* @__PURE__ */ new Map();
|
|
2407
|
+
for (let locationIndex = 0; locationIndex < locations.length; locationIndex += locationFieldCount) {
|
|
2408
|
+
const scriptId = locations[locationIndex + locationScriptIdOffset];
|
|
2409
|
+
const fileLocation = scriptIdToFileLocation.get(scriptId);
|
|
2410
|
+
if (!fileLocation) continue;
|
|
2411
|
+
let url = fileLocationToUrl.get(fileLocation);
|
|
2412
|
+
if (url === void 0) {
|
|
2413
|
+
url = makeProfileLocation({ urlOrPath: fileLocation })?.url ?? null;
|
|
2414
|
+
fileLocationToUrl.set(fileLocation, url);
|
|
2415
|
+
}
|
|
2416
|
+
if (!url) continue;
|
|
2417
|
+
const nodeIndex = locations[locationIndex + locationObjectIndexOffset];
|
|
2418
|
+
const line = locations[locationIndex + locationLineOffset];
|
|
2419
|
+
const column = locations[locationIndex + locationColumnOffset];
|
|
2420
|
+
nodeOrdinalToLocation[nodeIndex / nodeFieldCount] = {
|
|
2421
|
+
url,
|
|
2422
|
+
line: line + 1,
|
|
2423
|
+
column: column + 1
|
|
2424
|
+
};
|
|
1982
2425
|
}
|
|
1983
|
-
return
|
|
2426
|
+
return nodeOrdinalToLocation;
|
|
1984
2427
|
};
|
|
1985
|
-
const isInternalNodeType = (nodeType, fieldLayout) => nodeType === fieldLayout.nodeTypeHidden || nodeType === fieldLayout.nodeTypeSynthetic;
|
|
1986
2428
|
const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) => {
|
|
1987
2429
|
const edgeType = edges[edgeIndex + fieldLayout.edgeTypeOffset];
|
|
1988
2430
|
const edgeNameOrIndex = edges[edgeIndex + fieldLayout.edgeNameOrIndexOffset];
|
|
@@ -1991,7 +2433,8 @@ const formatEdgeLabel = (edgeIndex, { edges, strings }, fieldLayout, options) =>
|
|
|
1991
2433
|
const edgeLocation = makeProfileLocation({ urlOrPath: rawEdgeName });
|
|
1992
2434
|
return `.${edgeLocation ? formatProfileLocation(edgeLocation, options) : rawEdgeName}`;
|
|
1993
2435
|
};
|
|
1994
|
-
const formatNodeLabel = (
|
|
2436
|
+
const formatNodeLabel = (nodeOrdinal, { snapshot: { meta: { node_types: [nodeTypes] } }, nodes, strings }, fieldLayout, options) => {
|
|
2437
|
+
const nodeIndex = nodeOrdinal * fieldLayout.nodeFieldCount;
|
|
1995
2438
|
const nodeType = nodes[nodeIndex + fieldLayout.nodeTypeOffset];
|
|
1996
2439
|
switch (nodeType) {
|
|
1997
2440
|
case fieldLayout.nodeTypeString:
|
|
@@ -2013,44 +2456,6 @@ const formatString = (string) => {
|
|
|
2013
2456
|
return string.replaceAll(`\n`, `\\n`);
|
|
2014
2457
|
};
|
|
2015
2458
|
const MAX_STRING_LENGTH = 50;
|
|
2016
|
-
/**
|
|
2017
|
-
* Attributes retained sizes to groups of nodes without double-counting.
|
|
2018
|
-
*
|
|
2019
|
-
* Summing per-node retained sizes across all instances of a group over-counts
|
|
2020
|
-
* when one instance dominates another from the same group (the dominated node's
|
|
2021
|
-
* memory is already included in the dominator's retained size).
|
|
2022
|
-
*
|
|
2023
|
-
* This function correctly attributes by doing a DFS of the dominator tree and
|
|
2024
|
-
* only crediting the outermost instance of each group on any root-to-leaf path.
|
|
2025
|
-
* Inner instances are entirely contained within the outer one's retained set,
|
|
2026
|
-
* so they add nothing.
|
|
2027
|
-
*/
|
|
2028
|
-
const attributeGroupRetainedSizes = (nodeOrdinalToRetainedSize, { immediateDominateeOrdinalToStartOffset, offsetToImmediateDominateeOrdinal }, nodeOrdinalToSummarizedNodeIndex, summarizedNodes) => {
|
|
2029
|
-
const nodeCount = nodeOrdinalToRetainedSize.length;
|
|
2030
|
-
const groupPathDepth = new Int32Array(summarizedNodes.length);
|
|
2031
|
-
const stack = new Int32Array(nodeCount * 2 + 1);
|
|
2032
|
-
stack[0] = 0;
|
|
2033
|
-
let topOffset = 1;
|
|
2034
|
-
do {
|
|
2035
|
-
const encodedNodeOrdinal = stack[--topOffset];
|
|
2036
|
-
if (encodedNodeOrdinal < 0) {
|
|
2037
|
-
const constructorIndex = nodeOrdinalToSummarizedNodeIndex[~encodedNodeOrdinal];
|
|
2038
|
-
if (constructorIndex !== -1) groupPathDepth[constructorIndex] = groupPathDepth[constructorIndex] - 1;
|
|
2039
|
-
continue;
|
|
2040
|
-
}
|
|
2041
|
-
const nodeOrdinal = encodedNodeOrdinal;
|
|
2042
|
-
const summarizedNodeIndex = nodeOrdinalToSummarizedNodeIndex[nodeOrdinal];
|
|
2043
|
-
if (summarizedNodeIndex !== -1) {
|
|
2044
|
-
const depth = groupPathDepth[summarizedNodeIndex];
|
|
2045
|
-
if (depth === 0) summarizedNodes[summarizedNodeIndex].retainedSize += nodeOrdinalToRetainedSize[nodeOrdinal];
|
|
2046
|
-
groupPathDepth[summarizedNodeIndex] = depth + 1;
|
|
2047
|
-
stack[topOffset++] = ~nodeOrdinal;
|
|
2048
|
-
}
|
|
2049
|
-
const dominateeStartOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal];
|
|
2050
|
-
const dominateeEndOffset = immediateDominateeOrdinalToStartOffset[nodeOrdinal + 1];
|
|
2051
|
-
for (let offset = dominateeStartOffset; offset < dominateeEndOffset; offset++) stack[topOffset++] = offsetToImmediateDominateeOrdinal[offset];
|
|
2052
|
-
} while (topOffset > 0);
|
|
2053
|
-
};
|
|
2054
2459
|
const computeFieldLayout = (meta) => {
|
|
2055
2460
|
const { node_fields: nodeFields, node_types: [nodeTypes], edge_fields: edgeFields, edge_types: [edgeTypes], location_fields: locationFields } = meta;
|
|
2056
2461
|
const nodeFieldToIndex = valueToIndex(nodeFields);
|
|
@@ -2096,6 +2501,10 @@ const computeFieldLayout = (meta) => {
|
|
|
2096
2501
|
};
|
|
2097
2502
|
const valueToIndex = (values) => new Map(values.map((value, index) => [value, index]));
|
|
2098
2503
|
|
|
2504
|
+
//#endregion
|
|
2505
|
+
//#region src/formats/v8/heap-snapshot/parse.ts
|
|
2506
|
+
const parseV8HeapSnapshotAsync = (data) => JumboJSON.parseAsync(data);
|
|
2507
|
+
|
|
2099
2508
|
//#endregion
|
|
2100
2509
|
//#region src/formats/v8/heap-snapshot/index.ts
|
|
2101
2510
|
const detectV8HeapSnapshot = (json) => {
|
|
@@ -2108,7 +2517,7 @@ const detectV8HeapSnapshot = (json) => {
|
|
|
2108
2517
|
return json;
|
|
2109
2518
|
};
|
|
2110
2519
|
/**
|
|
2111
|
-
*
|
|
2520
|
+
* Asynchronously converts the given V8 heap snapshot to Markdown.
|
|
2112
2521
|
*
|
|
2113
2522
|
* It is assumed that {@link data} is a valid snapshot. The behavior of this
|
|
2114
2523
|
* function is undefined for invalid snapshots.
|
|
@@ -2117,10 +2526,69 @@ const detectV8HeapSnapshot = (json) => {
|
|
|
2117
2526
|
* for supported runtimes and generation instructions
|
|
2118
2527
|
* (`profiler-md --help v8-heap-snapshot`).
|
|
2119
2528
|
*/
|
|
2120
|
-
const
|
|
2529
|
+
const v8HeapSnapshotToMdAsync = async (data, options) => v8HeapSnapshotToMdInternal(await parseV8HeapSnapshotAsync(data), options);
|
|
2121
2530
|
const v8HeapSnapshotToMdInternal = (snapshot, options) => {
|
|
2122
2531
|
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
2123
|
-
return
|
|
2532
|
+
return formatHeapSnapshot(aggregateV8HeapSnapshot(snapshot, normalizedOptions), normalizedOptions);
|
|
2533
|
+
};
|
|
2534
|
+
|
|
2535
|
+
//#endregion
|
|
2536
|
+
//#region src/formats/webkit-timeline-recording/aggregate.ts
|
|
2537
|
+
const aggregateWebKitTimelineRecording = ({ recording: { sampleStackTraces, sampleDurations } }, options) => {
|
|
2538
|
+
const profileAggregator = new ProfileAggregator({
|
|
2539
|
+
metrics: [SECONDS],
|
|
2540
|
+
functionKey: (node) => `${node.name}|${node.url}|${node.line}|${node.column}`,
|
|
2541
|
+
functionInput: (node) => ({
|
|
2542
|
+
name: node.name,
|
|
2543
|
+
location: node.url ? {
|
|
2544
|
+
urlOrPath: node.url,
|
|
2545
|
+
line: node.line === -1 ? void 0 : node.line,
|
|
2546
|
+
column: node.column === -1 ? void 0 : node.column
|
|
2547
|
+
} : void 0
|
|
2548
|
+
})
|
|
2549
|
+
}, options);
|
|
2550
|
+
for (let index = 0; index < sampleStackTraces.length; index++) {
|
|
2551
|
+
const duration = sampleDurations[index];
|
|
2552
|
+
const { stackFrames } = sampleStackTraces[index];
|
|
2553
|
+
if (stackFrames.length === 0) continue;
|
|
2554
|
+
const expressionLine = stackFrames[0].expressionLocation?.line;
|
|
2555
|
+
profileAggregator.addSample({
|
|
2556
|
+
values: [duration],
|
|
2557
|
+
nodes: stackFrames,
|
|
2558
|
+
line: expressionLine !== void 0 && expressionLine !== -1 ? expressionLine : void 0
|
|
2559
|
+
});
|
|
2560
|
+
}
|
|
2561
|
+
return profileAggregator.aggregate();
|
|
2562
|
+
};
|
|
2563
|
+
|
|
2564
|
+
//#endregion
|
|
2565
|
+
//#region src/formats/webkit-timeline-recording/parse.ts
|
|
2566
|
+
const parseWebKitTimelineRecordingAsync = (data) => JumboJSON.parseAsync(data);
|
|
2567
|
+
|
|
2568
|
+
//#endregion
|
|
2569
|
+
//#region src/formats/webkit-timeline-recording/index.ts
|
|
2570
|
+
const detectWebKitTimelineRecording = (json) => {
|
|
2571
|
+
if (typeof json !== `object` || json === null) return;
|
|
2572
|
+
const object = json;
|
|
2573
|
+
if (object.version !== 1) return;
|
|
2574
|
+
if (typeof object.recording !== `object` || object.recording === null) return;
|
|
2575
|
+
const recording = object.recording;
|
|
2576
|
+
if (!Array.isArray(recording.sampleStackTraces) || !Array.isArray(recording.sampleDurations)) return;
|
|
2577
|
+
return json;
|
|
2578
|
+
};
|
|
2579
|
+
/**
|
|
2580
|
+
* Asynchronously converts the given WebKit timeline recording to Markdown.
|
|
2581
|
+
*
|
|
2582
|
+
* It is assumed that {@link data} is a valid recording. The behavior of this
|
|
2583
|
+
* function is undefined for invalid recordings.
|
|
2584
|
+
*
|
|
2585
|
+
* See the [WebKit timeline recording docs](https://github.com/TomerAberbach/profiler-md/blob/main/docs/formats/webkit-timeline-recording.md)
|
|
2586
|
+
* for generation instructions (`profiler-md --help webkit-timeline-recording`).
|
|
2587
|
+
*/
|
|
2588
|
+
const webkitTimelineRecordingToMdAsync = async (data, options) => webkitTimelineRecordingToMdInternal(await parseWebKitTimelineRecordingAsync(data), options);
|
|
2589
|
+
const webkitTimelineRecordingToMdInternal = (recording, options) => {
|
|
2590
|
+
const normalizedOptions = normalizeProfileToMdOptions(options);
|
|
2591
|
+
return formatProfile(aggregateWebKitTimelineRecording(recording, normalizedOptions), normalizedOptions);
|
|
2124
2592
|
};
|
|
2125
2593
|
|
|
2126
2594
|
//#endregion
|
|
@@ -2149,13 +2617,27 @@ const languages = new Map([
|
|
|
2149
2617
|
[`javascript`, {
|
|
2150
2618
|
name: `JavaScript`,
|
|
2151
2619
|
formats: [
|
|
2620
|
+
`jsc-heap-snapshot`,
|
|
2621
|
+
`pprof`,
|
|
2622
|
+
`speedscope`,
|
|
2152
2623
|
`v8-cpu-profile`,
|
|
2153
2624
|
`v8-heap-profile`,
|
|
2154
2625
|
`v8-heap-snapshot`,
|
|
2155
|
-
`
|
|
2156
|
-
`speedscope`
|
|
2626
|
+
`webkit-timeline-recording`
|
|
2157
2627
|
],
|
|
2158
2628
|
examples: {
|
|
2629
|
+
"jsc-heap-snapshot": [{
|
|
2630
|
+
filename: `jsc-heap-snapshot.json`,
|
|
2631
|
+
label: `Safari`
|
|
2632
|
+
}],
|
|
2633
|
+
pprof: [{
|
|
2634
|
+
filename: `node.pprof`,
|
|
2635
|
+
label: `Node.js`
|
|
2636
|
+
}],
|
|
2637
|
+
speedscope: [{
|
|
2638
|
+
filename: `node.speedscope.json`,
|
|
2639
|
+
label: `Node.js`
|
|
2640
|
+
}],
|
|
2159
2641
|
"v8-cpu-profile": [
|
|
2160
2642
|
{
|
|
2161
2643
|
filename: `node.cpuprofile`,
|
|
@@ -2178,13 +2660,9 @@ const languages = new Map([
|
|
|
2178
2660
|
filename: `node.heapsnapshot`,
|
|
2179
2661
|
label: `Node.js`
|
|
2180
2662
|
}],
|
|
2181
|
-
|
|
2182
|
-
filename: `
|
|
2183
|
-
label: `
|
|
2184
|
-
}],
|
|
2185
|
-
speedscope: [{
|
|
2186
|
-
filename: `node.speedscope.json`,
|
|
2187
|
-
label: `Node.js`
|
|
2663
|
+
"webkit-timeline-recording": [{
|
|
2664
|
+
filename: `webkit-timeline-recording.json`,
|
|
2665
|
+
label: `example`
|
|
2188
2666
|
}]
|
|
2189
2667
|
},
|
|
2190
2668
|
aliases: [{
|
|
@@ -2208,50 +2686,61 @@ const languages = new Map([
|
|
|
2208
2686
|
name: `Rust`,
|
|
2209
2687
|
formats: [`pprof`, `speedscope`],
|
|
2210
2688
|
examples: { pprof: [{
|
|
2211
|
-
filename: `
|
|
2212
|
-
label: `
|
|
2213
|
-
}, {
|
|
2214
|
-
filename: `rust2.pprof`,
|
|
2215
|
-
label: `2`
|
|
2689
|
+
filename: `rust.pprof`,
|
|
2690
|
+
label: `example`
|
|
2216
2691
|
}] }
|
|
2217
2692
|
}]
|
|
2218
2693
|
]);
|
|
2219
2694
|
const languageAliasToPrimary = new Map([...languages.entries()].flatMap(([primaryId, { aliases }]) => aliases?.map(({ id }) => [id, primaryId]) ?? []));
|
|
2220
2695
|
const formats = new Map([
|
|
2696
|
+
[`jsc-heap-snapshot`, {
|
|
2697
|
+
name: `JSC heap snapshot`,
|
|
2698
|
+
kind: `json`,
|
|
2699
|
+
detect: detectJSCHeapSnapshot,
|
|
2700
|
+
toMdInternal: jscHeapSnapshotToMdInternal,
|
|
2701
|
+
toMdAsync: jscHeapSnapshotToMdAsync
|
|
2702
|
+
}],
|
|
2703
|
+
[`pprof`, {
|
|
2704
|
+
name: `pprof`,
|
|
2705
|
+
kind: `binary`,
|
|
2706
|
+
detect: detectPprof,
|
|
2707
|
+
toMdInternal: pprofToMdInternal,
|
|
2708
|
+
toMdAsync: pprofToMdAsync
|
|
2709
|
+
}],
|
|
2221
2710
|
[`speedscope`, {
|
|
2222
2711
|
name: `Speedscope`,
|
|
2223
2712
|
kind: `json`,
|
|
2224
2713
|
detect: detectSpeedscopeProfile,
|
|
2225
2714
|
toMdInternal: speedscopeProfileToMdInternal,
|
|
2226
|
-
|
|
2715
|
+
toMdAsync: speedscopeProfileToMdAsync
|
|
2227
2716
|
}],
|
|
2228
2717
|
[`v8-cpu-profile`, {
|
|
2229
2718
|
name: `V8 CPU profile`,
|
|
2230
2719
|
kind: `json`,
|
|
2231
2720
|
detect: detectV8CpuProfile,
|
|
2232
2721
|
toMdInternal: v8CpuProfileToMdInternal,
|
|
2233
|
-
|
|
2722
|
+
toMdAsync: v8CpuProfileToMdAsync
|
|
2234
2723
|
}],
|
|
2235
2724
|
[`v8-heap-profile`, {
|
|
2236
2725
|
name: `V8 heap profile`,
|
|
2237
2726
|
kind: `json`,
|
|
2238
2727
|
detect: detectV8HeapProfile,
|
|
2239
2728
|
toMdInternal: v8HeapProfileToMdInternal,
|
|
2240
|
-
|
|
2729
|
+
toMdAsync: v8HeapProfileToMdAsync
|
|
2241
2730
|
}],
|
|
2242
2731
|
[`v8-heap-snapshot`, {
|
|
2243
2732
|
name: `V8 heap snapshot`,
|
|
2244
2733
|
kind: `json`,
|
|
2245
2734
|
detect: detectV8HeapSnapshot,
|
|
2246
2735
|
toMdInternal: v8HeapSnapshotToMdInternal,
|
|
2247
|
-
|
|
2736
|
+
toMdAsync: v8HeapSnapshotToMdAsync
|
|
2248
2737
|
}],
|
|
2249
|
-
[`
|
|
2250
|
-
name: `
|
|
2251
|
-
kind: `
|
|
2252
|
-
detect:
|
|
2253
|
-
toMdInternal:
|
|
2254
|
-
|
|
2738
|
+
[`webkit-timeline-recording`, {
|
|
2739
|
+
name: `WebKit timeline recording`,
|
|
2740
|
+
kind: `json`,
|
|
2741
|
+
detect: detectWebKitTimelineRecording,
|
|
2742
|
+
toMdInternal: webkitTimelineRecordingToMdInternal,
|
|
2743
|
+
toMdAsync: webkitTimelineRecordingToMdAsync
|
|
2255
2744
|
}]
|
|
2256
2745
|
]);
|
|
2257
2746
|
|
|
@@ -2260,67 +2749,40 @@ const formats = new Map([
|
|
|
2260
2749
|
const formatTopics = [...formats.keys()];
|
|
2261
2750
|
const languageTopics = [...languages.entries()].flatMap(([id, { aliases }]) => [id, ...aliases?.map((alias) => alias.id) ?? []]);
|
|
2262
2751
|
const topics = [...formatTopics, ...languageTopics];
|
|
2263
|
-
const
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
NO_COLOR and FORCE_COLOR)
|
|
2282
|
-
--help [format|language] Show this help message or topic docs
|
|
2283
|
-
|
|
2284
|
-
Formats: ${formatTopics.join(`, `)}
|
|
2285
|
-
Languages: ${languageTopics.join(`, `)}
|
|
2286
|
-
`, {
|
|
2287
|
-
importMeta: import.meta,
|
|
2288
|
-
autoHelp: false,
|
|
2289
|
-
allowUnknownFlags: false,
|
|
2290
|
-
booleanDefault: void 0,
|
|
2291
|
-
flags: {
|
|
2292
|
-
help: {
|
|
2293
|
-
type: `boolean`,
|
|
2294
|
-
shortFlag: `h`
|
|
2295
|
-
},
|
|
2296
|
-
format: {
|
|
2297
|
-
type: `string`,
|
|
2298
|
-
shortFlag: `f`
|
|
2299
|
-
},
|
|
2300
|
-
output: {
|
|
2301
|
-
type: `string`,
|
|
2302
|
-
shortFlag: `o`,
|
|
2303
|
-
default: `-`
|
|
2304
|
-
},
|
|
2305
|
-
topN: { type: `number` },
|
|
2306
|
-
cwd: { type: `string` },
|
|
2307
|
-
thirdParty: {
|
|
2308
|
-
type: `string`,
|
|
2309
|
-
isMultiple: true,
|
|
2310
|
-
default: []
|
|
2311
|
-
},
|
|
2312
|
-
sourceMaps: {
|
|
2313
|
-
type: `string`,
|
|
2314
|
-
isMultiple: true,
|
|
2315
|
-
default: []
|
|
2316
|
-
},
|
|
2317
|
-
pager: {
|
|
2318
|
-
type: `boolean`,
|
|
2319
|
-
default: true
|
|
2320
|
-
},
|
|
2321
|
-
color: { type: `boolean` }
|
|
2752
|
+
const parser = object({
|
|
2753
|
+
help: optional(or(option(`-h`, `--help`, choice(topics, { metavar: `[TOPIC]` }), { description: message`Show this help message or topic docs` }), flag(`-h`, `--help`, { hidden: `help` }))),
|
|
2754
|
+
format: optional(option(`-f`, `--format`, choice(formatTopics, { metavar: `FORMAT` }), { description: message`Input profile format (default: auto)` })),
|
|
2755
|
+
output: withDefault(option(`-o`, `--output`, path({ metavar: `FILE` }), { description: message`Output file (default: - for stdout)` }), `-`),
|
|
2756
|
+
topN: optional(option(`--top-n`, integer({ metavar: `N` }), { description: message`Number of top entries to show (default: 20)` })),
|
|
2757
|
+
cwd: optional(option(`--cwd`, path(), { description: message`Directory to show paths relative to (default: cwd)` })),
|
|
2758
|
+
thirdParty: multiple(option(`--third-party`, string({ metavar: `GLOB` }), { description: message`Additional URLs to consider third-party (repeatable)` })),
|
|
2759
|
+
sourceMaps: multiple(option(`--source-maps`, string({ metavar: `GLOB` }), { description: message`Source maps (JSON or inline) to apply to profile locations (repeatable)` })),
|
|
2760
|
+
pager: map(option(`--no-pager`, { description: message`Disable stdout output paging (default: auto)` }), (value) => !value),
|
|
2761
|
+
color: optional(or(flag(`--color`, { description: message`Enable or disable ANSI syntax highlighting (default: auto)` }), map(flag(`--no-color`), () => false))),
|
|
2762
|
+
file: optional(argument(path({ metavar: `FILE` }), { description: message`Profile file to convert (reads from stdin if omitted)` }))
|
|
2763
|
+
});
|
|
2764
|
+
const program = defineProgram({
|
|
2765
|
+
parser,
|
|
2766
|
+
metadata: {
|
|
2767
|
+
name,
|
|
2768
|
+
version,
|
|
2769
|
+
description: message`${text(description)}`
|
|
2322
2770
|
}
|
|
2323
2771
|
});
|
|
2772
|
+
const getHelpText = () => `${[
|
|
2773
|
+
formatDocPage(program.metadata.name, {
|
|
2774
|
+
...getDocPage(parser),
|
|
2775
|
+
...program.metadata
|
|
2776
|
+
}, { maxWidth: process.stdout.columns ?? 80 }),
|
|
2777
|
+
`Formats: ${formatTopics.join(`, `)}`,
|
|
2778
|
+
`Languages: ${languageTopics.join(`, `)}`
|
|
2779
|
+
].join(`\n`)}\n`;
|
|
2780
|
+
const parseArgs = () => run(program, {
|
|
2781
|
+
colors: false,
|
|
2782
|
+
version: program.metadata.version,
|
|
2783
|
+
completion: `option`,
|
|
2784
|
+
errorExitCode: 2
|
|
2785
|
+
});
|
|
2324
2786
|
|
|
2325
2787
|
//#endregion
|
|
2326
2788
|
//#region src/cli/error.ts
|
|
@@ -2350,25 +2812,20 @@ const reportError = (error) => {
|
|
|
2350
2812
|
//#region src/cli/convert.ts
|
|
2351
2813
|
const jsonFormats = [...formats.entries()].filter((entry) => entry[1].kind === `json`);
|
|
2352
2814
|
const binaryFormats = [...formats.entries()].filter((entry) => entry[1].kind === `binary`);
|
|
2353
|
-
const
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
return format;
|
|
2357
|
-
};
|
|
2358
|
-
const convertToMarkdown = (data, forcedFormat, options) => {
|
|
2359
|
-
if (forcedFormat) return forcedFormat.toMd(data, options);
|
|
2360
|
-
const markdown = autoDetectAndConvert(data, options);
|
|
2815
|
+
const convertToMarkdown = async (data, forcedFormat, options) => {
|
|
2816
|
+
if (forcedFormat) return forcedFormat.toMdAsync(data, options);
|
|
2817
|
+
const markdown = await autoDetectAndConvert(data, options);
|
|
2361
2818
|
if (markdown === void 0) throw new CliError(`could not detect profile format from content\nUse --format to specify the format, or run with --help to see supported formats.`, 2);
|
|
2362
2819
|
return markdown;
|
|
2363
2820
|
};
|
|
2364
|
-
const autoDetectAndConvert = (data, options) => {
|
|
2821
|
+
const autoDetectAndConvert = async (data, options) => {
|
|
2365
2822
|
let json;
|
|
2366
2823
|
try {
|
|
2367
|
-
json =
|
|
2824
|
+
json = await JumboJSON.parseAsync(data);
|
|
2368
2825
|
} catch {}
|
|
2369
2826
|
if (json === void 0) {
|
|
2370
2827
|
for (const [, format] of binaryFormats) {
|
|
2371
|
-
const parsed = format.detect(data);
|
|
2828
|
+
const parsed = await format.detect(data);
|
|
2372
2829
|
if (parsed !== void 0) return format.toMdInternal(parsed, options);
|
|
2373
2830
|
}
|
|
2374
2831
|
return;
|
|
@@ -2443,32 +2900,19 @@ const openOutput = async (outputPath) => {
|
|
|
2443
2900
|
};
|
|
2444
2901
|
|
|
2445
2902
|
//#endregion
|
|
2446
|
-
//#region src/cli/
|
|
2447
|
-
const makeAnsis = (
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
}
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
if (depth >= 24) return 3;
|
|
2460
|
-
if (depth >= 8) return 2;
|
|
2461
|
-
return 1;
|
|
2462
|
-
};
|
|
2463
|
-
const parseForceColor = (value) => {
|
|
2464
|
-
if (!value) return null;
|
|
2465
|
-
switch (value) {
|
|
2466
|
-
case `0`:
|
|
2467
|
-
case `false`: return 0;
|
|
2468
|
-
case `2`: return 2;
|
|
2469
|
-
case `3`: return 3;
|
|
2470
|
-
default: return 1;
|
|
2471
|
-
}
|
|
2903
|
+
//#region src/cli/ansis.ts
|
|
2904
|
+
const makeAnsis = ({ outputPath }) => {
|
|
2905
|
+
if (isTTYOutput(outputPath)) return new Ansis();
|
|
2906
|
+
return new Ansis({
|
|
2907
|
+
...globalThis,
|
|
2908
|
+
process: {
|
|
2909
|
+
...process,
|
|
2910
|
+
env: {
|
|
2911
|
+
NO_COLOR: `1`,
|
|
2912
|
+
...process.env
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
});
|
|
2472
2916
|
};
|
|
2473
2917
|
|
|
2474
2918
|
//#endregion
|
|
@@ -2849,9 +3293,9 @@ const FONT_STYLE_STRIKETHROUGH = 8;
|
|
|
2849
3293
|
|
|
2850
3294
|
//#endregion
|
|
2851
3295
|
//#region src/cli/help.ts
|
|
2852
|
-
const printHelpTopic = async (topic, { pager
|
|
3296
|
+
const printHelpTopic = async (topic, { pager }) => {
|
|
2853
3297
|
if (topic === void 0) {
|
|
2854
|
-
await writeOutput(
|
|
3298
|
+
await writeOutput(getHelpText(), `-`, { pager });
|
|
2855
3299
|
process.exit(0);
|
|
2856
3300
|
}
|
|
2857
3301
|
const language = languages.get(languageAliasToPrimary.get(topic) ?? topic);
|
|
@@ -2867,50 +3311,52 @@ const printHelpTopic = async (topic, { pager, color }) => {
|
|
|
2867
3311
|
}) : language ? language.formats : [];
|
|
2868
3312
|
const seeAlsoSuffix = seeAlso.length > 0 ? `\nSee also: ${seeAlso.join(`, `)}\n` : ``;
|
|
2869
3313
|
const outputPath = `-`;
|
|
2870
|
-
await writeOutput(await highlightMarkdown(`${doc}${seeAlsoSuffix}`, {
|
|
2871
|
-
outputPath,
|
|
2872
|
-
color
|
|
2873
|
-
}), outputPath, { pager });
|
|
3314
|
+
await writeOutput(await highlightMarkdown(`${doc}${seeAlsoSuffix}`, { outputPath }), outputPath, { pager });
|
|
2874
3315
|
process.exit(0);
|
|
2875
3316
|
};
|
|
2876
3317
|
|
|
2877
3318
|
//#endregion
|
|
2878
3319
|
//#region src/cli/input.ts
|
|
2879
|
-
const
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
const readRawInput = async (filePath) => {
|
|
2883
|
-
if (!filePath) return Buffer.concat(await Array.fromAsync(process.stdin));
|
|
3320
|
+
const openInputAsBlob = async (filePath) => decompressBlob(await openRawInputAsBlob(filePath), filePath);
|
|
3321
|
+
const openRawInputAsBlob = async (filePath) => {
|
|
3322
|
+
if (!filePath) return blob(process.stdin);
|
|
2884
3323
|
try {
|
|
2885
|
-
return await
|
|
3324
|
+
return await openAsBlob(filePath);
|
|
2886
3325
|
} catch (error) {
|
|
2887
3326
|
throw new CliError(error instanceof Error ? error.message : String(error), 1);
|
|
2888
3327
|
}
|
|
2889
3328
|
};
|
|
2890
|
-
const
|
|
3329
|
+
const decompressBlob = async (data, filePath) => {
|
|
2891
3330
|
try {
|
|
2892
|
-
if (filePath?.endsWith(`.br`)) return await
|
|
2893
|
-
|
|
3331
|
+
if (filePath?.endsWith(`.br`)) return await decompressStream(data, createBrotliDecompress());
|
|
3332
|
+
const header = new Uint8Array(await data.slice(0, 2).arrayBuffer());
|
|
3333
|
+
if (header[0] === 31 && header[1] === 139) return await decompressStream(data, createGunzip());
|
|
2894
3334
|
return data;
|
|
2895
3335
|
} catch (error) {
|
|
2896
3336
|
throw new CliError(`failed to decompress input: ${error instanceof Error ? error.message : String(error)}`, 1);
|
|
2897
3337
|
}
|
|
2898
3338
|
};
|
|
2899
|
-
const
|
|
2900
|
-
const
|
|
3339
|
+
const decompressStream = async (data, transform) => {
|
|
3340
|
+
const decompressedData = blob(transform);
|
|
3341
|
+
await pipeline(data.stream(), transform);
|
|
3342
|
+
return decompressedData;
|
|
3343
|
+
};
|
|
2901
3344
|
|
|
2902
3345
|
//#endregion
|
|
2903
3346
|
//#region src/cli/options.ts
|
|
2904
3347
|
const buildOptions = async ({ topN, cwd, thirdParty, sourceMaps }) => ({
|
|
2905
3348
|
topN,
|
|
2906
3349
|
cwd,
|
|
2907
|
-
|
|
3350
|
+
categorizeEntry: buildCategorizeEntry(thirdParty),
|
|
2908
3351
|
sourceMaps: await loadSourceMaps(sourceMaps)
|
|
2909
3352
|
});
|
|
2910
|
-
const
|
|
3353
|
+
const buildCategorizeEntry = (patterns) => {
|
|
2911
3354
|
if (patterns.length === 0) return;
|
|
2912
|
-
const
|
|
2913
|
-
return (entry) =>
|
|
3355
|
+
const isMatch = picomatch([...patterns], { dot: true });
|
|
3356
|
+
return (entry) => {
|
|
3357
|
+
if (entry.location && isMatch(entry.location.url.pathname)) return `third-party`;
|
|
3358
|
+
return defaultCategorizeEntry(entry);
|
|
3359
|
+
};
|
|
2914
3360
|
};
|
|
2915
3361
|
const loadSourceMaps = async (patterns) => {
|
|
2916
3362
|
const paths = (await Promise.all(patterns.map((pattern) => Array.fromAsync(glob(pattern))))).flat();
|
|
@@ -2937,25 +3383,17 @@ const resolveSourceMapSources = (sourceMap, path) => {
|
|
|
2937
3383
|
//#endregion
|
|
2938
3384
|
//#region src/cli/index.ts
|
|
2939
3385
|
try {
|
|
2940
|
-
const {
|
|
2941
|
-
if (help) await printHelpTopic(
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
const forcedFormat = profileFormat === void 0 ? void 0 : requireFormat(profileFormat);
|
|
2946
|
-
if (!filePath && process.stdin.isTTY) await printHelpTopic(void 0, {
|
|
2947
|
-
pager,
|
|
2948
|
-
color
|
|
2949
|
-
});
|
|
2950
|
-
await writeOutput(await highlightMarkdown(convertToMarkdown(await readInput(filePath), forcedFormat, await buildOptions({
|
|
3386
|
+
const { help, output: outputPath, format: profileFormat, topN, cwd, thirdParty, sourceMaps, pager, file: filePath } = parseArgs();
|
|
3387
|
+
if (help !== void 0) await printHelpTopic(typeof help === `string` ? help : void 0, { pager });
|
|
3388
|
+
const forcedFormat = profileFormat === void 0 ? void 0 : formats.get(profileFormat);
|
|
3389
|
+
if (!filePath && process.stdin.isTTY) await printHelpTopic(void 0, { pager });
|
|
3390
|
+
const [data, options] = await Promise.all([openInputAsBlob(filePath), buildOptions({
|
|
2951
3391
|
topN,
|
|
2952
3392
|
cwd,
|
|
2953
3393
|
thirdParty,
|
|
2954
3394
|
sourceMaps
|
|
2955
|
-
}))
|
|
2956
|
-
|
|
2957
|
-
color
|
|
2958
|
-
}), outputPath, { pager });
|
|
3395
|
+
})]);
|
|
3396
|
+
await writeOutput(await highlightMarkdown(await convertToMarkdown(data, forcedFormat, options), { outputPath }), outputPath, { pager });
|
|
2959
3397
|
} catch (error) {
|
|
2960
3398
|
reportError(error);
|
|
2961
3399
|
}
|