Skip to content

Build your personal knowledge base with Trilium Notes

docs(skills): add analyzing-backend-bundle skill

Elian Doranaf32e1a159bf
diff --git a/.claude/skills/analyzing-backend-bundle/SKILL.md b/.claude/skills/analyzing-backend-bundle/SKILL.md
new file mode 100644
index 0000000000..5d065e0fb5
--- /dev/null
+++ b/.claude/skills/analyzing-backend-bundle/SKILL.md
@@ -0,0 +1,119 @@
+---
+name: analyzing-backend-bundle
+description: Use when analyzing the server/desktop backend bundle — "what does the server load at startup?", "is <dependency> lazy on the backend?", "why is <package> in the startup set?", "how big is the eager set?", chunk analysis after adding a dynamic-import seam, backend memory profiling (RSS, retained script source, heap), or any before/after comparison for backend lazy-loading. Records what a bundle actually loads at boot, joins it with the esbuild metafile, and explains why each package is eager. Don't write a new throwaway module-hook logger, metafile joiner, or heap-snapshot parser — all already live here.
+---
+
+# Analyzing the backend bundle
+
+The backend bundles (`apps/server/dist`, `apps/desktop/dist`) are esbuild ESM output with
+code splitting: an entry plus `chunks/`, where a chunk loads only when a dynamic `import()`
+first needs it. Every megabyte the process loads at startup costs three ways, permanently:
+
+- **Retained source** (~1 MB heap per loaded MB): V8 keeps each loaded script's source string
+ for the life of the script. Double that for a chunk containing any character above U+00FF —
+ esbuild escapes strings (`charset: "ascii"`) but emits regex literals verbatim, and one raw
+ Arabic digit stores the whole chunk two-byte.
+- **Parser high-water** (~5 B native per loaded byte, cold start): V8's parse of the loaded
+ code peaks in malloc'd memory that glibc keeps as dirty pages after it is freed.
+ `NODE_COMPILE_CACHE` roughly halves it on warm starts.
+- **Bytecode and metadata** in the JS heap.
+
+Reference points (2026-08, Node 22, real 146 MB DB): the monolithic 14.6 MB CJS bundle cost
+221 MB RSS / 77 MB heap; the split ESM build loading 9 MB at startup cost 135 MB / 54 MB.
+So the question that matters is never "how big is the bundle" but **"how much of it loads at
+startup"** — and the tools here answer it with runtime evidence, not static guessing.
+
+## Tools
+
+All in this folder, zero dependencies. `record` and `profile-bundle` boot the real server, so
+they need the usual environment (adapt paths; use a scratch copy of a real `document.db` for
+realistic becca numbers, or an empty dir for setup-mode):
+
+```bash
+ENV="TRILIUM_ENV=production TRILIUM_DATA_DIR=<scratch>/data TRILIUM_PORT=8123 \
+ TRILIUM_RESOURCE_DIR=$PWD/apps/server/dist"
+
+# 1. Record which dist/ files the server loads at startup (ground truth):
+env $ENV node .claude/skills/analyzing-backend-bundle/analyze-bundle.mjs record \
+ --bundle apps/server/dist/main.mjs --out /tmp/loaded.txt --port 8123
+
+# 2. Join with the metafile: eager vs lazy totals, per package, biggest eager chunks:
+node .claude/skills/analyzing-backend-bundle/analyze-bundle.mjs startup \
+ --meta <meta.json> --loaded /tmp/loaded.txt
+
+# 3. Explain WHY a package is eager (shortest static import chain from the entry):
+node .claude/skills/analyzing-backend-bundle/analyze-bundle.mjs why \
+ --meta <meta.json> iconv-lite undici
+
+# 4. Whole-bundle composition, no boot needed:
+node .claude/skills/analyzing-backend-bundle/analyze-bundle.mjs packages --meta <meta.json>
+
+# Memory numbers (RSS/heap post-GC; add --snapshot for a heap snapshot):
+env $ENV node --expose-gc .claude/skills/analyzing-backend-bundle/profile-bundle.cjs \
+ apps/server/dist/main.mjs --port 8123 --snapshot /tmp/s.heapsnapshot
+
+# What the heap actually retains (proves which chunk sources are resident):
+node --max-old-space-size=8192 .claude/skills/analyzing-backend-bundle/heap-strings.mjs \
+ /tmp/s.heapsnapshot
+```
+
+The desktop bundle embeds the same server code, so server recordings generalize to it;
+`record`/`profile-bundle` cannot boot `apps/desktop/dist/main.mjs` under plain node (it
+imports `electron`), but `packages` and `why` work on its metafile directly.
+
+## Getting the metafile
+
+`buildBackend()` writes `dist/meta.json`, and **the last call in the app's build script
+wins** — after `pnpm server:build` it describes `image_worker.cjs`, not main. To get the
+main bundle's metafile, temporarily leave only the `main.ts` `buildBackend` call in
+`apps/server/scripts/build.ts`, run the build, and save `dist/meta.json` elsewhere before
+restoring. (Making buildBackend write per-entry metafiles is the real fix if this grates.)
+
+## Interpreting the results
+
+- **Eagerness is decided only by the recording.** The metafile marks every dynamic-import
+ target chunk with `entryPoint` (240 of 286 outputs in the first analysis), so any static
+ reasoning that consults `entryPoint`, or assumes "chunk = lazy", overcounts. Conversely the
+ static-reachability closure *undercounts*: a dynamic import executed during boot loads its
+ chunk anyway.
+- **"NOT statically reachable" + present in the startup set** is that second pattern and is
+ the best kind of finding: the seam already exists, boot-time code defeats it. Find the
+ dynamic import that runs at startup and defer it to first use (example: the `/mcp` route
+ registering the MCP SDK at boot instead of on first request).
+- **Chunks load as units.** A package can be "lazy" in source but ride in a chunk shared
+ with eager code; `startup`'s biggest-chunks table shows each chunk's dominant input so
+ this is visible.
+- **A `why` chain through an absurd path is a stubbing opportunity** — e.g. highlight.js
+ reached via `sanitize-html → postcss/lib/terminal-highlight` (postcss's terminal error
+ pretty-printer). An esbuild alias to a stub kills such an edge at build level.
+
+## Fix patterns, by constraint
+
+| Situation | Fix |
+|---|---|
+| Used only inside an `async` function | Move the import into it: `const { x } = await import("pkg")` (the pattern in `pdf_processor.ts`, `office_processor.ts`, `claude_agent.ts`) |
+| Loaded at boot by a dynamic import | Keep the registration eager, import the payload in the request handler on first use |
+| Consumed synchronously (script API, sucrase transpile) | Per-call import is impossible — preload conditionally at startup behind the feature's flag (backend scripting is off by default) |
+| Pulled by a dep's edge that never runs meaningfully | esbuild `alias`/stub for that one file |
+
+After any fix: re-run `record` + `startup` and compare the eager total, and check no chunk
+in the new startup set carries characters above U+00FF (`grep -lP '[^\x00-\xFF]'` over the
+loaded chunks; `heap-strings.mjs` shows a ~2x source string when one slips through).
+
+## Gotchas
+
+- `NODE_V8_COVERAGE` does not capture the loaded-script list here (the dump held only node
+ internals) — the module hook (`loghook.cjs`, preloaded by `record`) is the reliable tool.
+- The server handles SIGTERM without exiting (DB close), so anything that boots it must
+ escalate to SIGKILL — `record` does; a hand-rolled runner that waits on `exit` after
+ SIGTERM hangs and leaks an orphaned server.
+- `__dirname` in ESM output is defined by the buildBackend banner and resolves to the
+ **bundle root even inside `chunks/`** — bundled code locates `preload.cjs`,
+ `image_worker.cjs` and assets relative to the entry. Don't "simplify" the banner; which
+ chunk a module lands in must not change what `__dirname` means.
+- Heap snapshots for a ~55 MB heap parse fine with `--max-old-space-size=8192`; write them
+ only when needed (`--snapshot`), they're ~70-90 MB on disk.
+
+Related skills: **measure-startup-requests** (the client-side counterpart),
+**profiling-client-performance** (renderer-side cost), **developing-electron-desktop**
+(desktop launch specifics when verifying a change in the real app).
diff --git a/.claude/skills/analyzing-backend-bundle/analyze-bundle.mjs b/.claude/skills/analyzing-backend-bundle/analyze-bundle.mjs
new file mode 100644
index 0000000000..a14800450c
--- /dev/null
+++ b/.claude/skills/analyzing-backend-bundle/analyze-bundle.mjs
@@ -0,0 +1,247 @@
+// Bundle analysis for the backend ESM builds (server, desktop main).
+//
+// record — boot a bundle and record which dist/ files it loads
+// startup — join a recording with the esbuild metafile: eager vs lazy, per package
+// why — shortest static import path from the entry to a package (why is it eager?)
+// packages — whole-bundle composition per package (no recording needed)
+//
+// See SKILL.md for the workflow and the interpretation guide.
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import http from "node:http";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const [cmd, ...args] = process.argv.slice(2);
+
+const flag = (name, fallback) => {
+ const i = args.indexOf(name);
+ return i >= 0 ? args[i + 1] : fallback;
+};
+
+const commands = { record, startup, why, packages };
+if (!commands[cmd]) {
+ console.error(`usage:
+ node analyze-bundle.mjs record --bundle <main.mjs> --out <loaded.txt> [--port 8123] [--settle 20]
+ node analyze-bundle.mjs startup --meta <meta.json> --loaded <loaded.txt> [--top 20]
+ node analyze-bundle.mjs why --meta <meta.json> <package-substring> [more...]
+ node analyze-bundle.mjs packages --meta <meta.json> [--top 25]`);
+ process.exit(1);
+}
+await commands[cmd]();
+
+/** Boots the bundle with the module-load hook preloaded and records dist/ loads. */
+async function record() {
+ const bundle = path.resolve(flag("--bundle"));
+ const out = path.resolve(flag("--out", "loaded-modules.txt"));
+ const port = flag("--port");
+ const settle = Number(flag("--settle", "20"));
+ const hook = path.join(path.dirname(fileURLToPath(import.meta.url)), "loghook.cjs");
+
+ fs.writeFileSync(out, "");
+ const loader = bundle.endsWith(".mjs")
+ ? `import(${JSON.stringify("file://" + bundle)})`
+ : `require(${JSON.stringify(bundle)})`;
+ const child = spawn(process.execPath, ["--require", hook, "-e", loader], {
+ env: { ...process.env, LOAD_LOG: out },
+ stdio: "ignore",
+ });
+
+ if (port) {
+ await waitForHttp(port, 120);
+ await sleep(5000);
+ } else {
+ await sleep(settle * 1000);
+ }
+ // The server handles SIGTERM (closes the DB) without exiting, so escalate
+ // to SIGKILL after giving the close a moment.
+ child.kill("SIGTERM");
+ await new Promise((resolve) => {
+ child.on("exit", resolve);
+ setTimeout(() => {
+ child.kill("SIGKILL");
+ resolve();
+ }, 3000);
+ });
+
+ const lines = [...new Set(fs.readFileSync(out, "utf8").split("\n").filter(Boolean))].sort();
+ fs.writeFileSync(out, lines.join("\n") + "\n");
+ console.log(`${lines.length} dist files loaded at startup -> ${out}`);
+}
+
+function waitForHttp(port, retries) {
+ return new Promise((resolve) => {
+ const attempt = (left) => {
+ if (left <= 0) {
+ console.error("server never became ready; recording what loaded anyway");
+ resolve();
+ return;
+ }
+ const req = http.get({ host: "127.0.0.1", port, path: "/" }, (res) => {
+ res.resume();
+ resolve();
+ });
+ req.on("error", () => setTimeout(() => attempt(left - 1), 500));
+ };
+ attempt(retries);
+ });
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+/**
+ * Joins metafile output keys with recorded file URLs on their trailing two
+ * path segments ("chunks/x.mjs", "dist/main.mjs"), since the metafile is
+ * repo-relative and the recording is absolute.
+ */
+function tailKey(p) {
+ return p.split("/").slice(-2).join("/");
+}
+
+function loadJoin() {
+ const meta = JSON.parse(fs.readFileSync(flag("--meta"), "utf8"));
+ const loadedTails = new Set(
+ fs.readFileSync(flag("--loaded"), "utf8").split("\n").filter(Boolean).map(tailKey)
+ );
+ return { meta, isLoaded: (outKey) => loadedTails.has(tailKey(outKey)) };
+}
+
+function pkgOf(file) {
+ const m = file.match(/node_modules\/(@[^/]+\/[^/]+|[^/@][^/]*)/g);
+ if (m) {
+ return m[m.length - 1].replace("node_modules/", "");
+ }
+ if (file.startsWith("packages/") || file.startsWith("apps/")) {
+ return file.split("/").slice(0, 2).join("/");
+ }
+ return file;
+}
+
+function kb(n) {
+ return (n / 1024).toFixed(0).padStart(7) + " KB";
+}
+
+/** Eager/lazy split from a recording: totals, per package, biggest loaded chunks. */
+async function startup() {
+ const { meta, isLoaded } = loadJoin();
+ const top = Number(flag("--top", "20"));
+ let eagerTotal = 0;
+ let lazyTotal = 0;
+ let eagerCount = 0;
+ const eagerByPkg = new Map();
+ const lazyByPkg = new Map();
+ const eagerChunks = [];
+
+ for (const [out, v] of Object.entries(meta.outputs)) {
+ if (!/\.(mjs|cjs|js)$/.test(out)) {
+ continue;
+ }
+ // CAUTION: v.entryPoint is set on every dynamic-import target (most
+ // chunks), so it must not be used to decide eagerness — only the
+ // recording can.
+ const eager = isLoaded(out);
+ for (const [inp, iv] of Object.entries(v.inputs ?? {})) {
+ const map = eager ? eagerByPkg : lazyByPkg;
+ map.set(pkgOf(inp), (map.get(pkgOf(inp)) ?? 0) + iv.bytesInOutput);
+ }
+ if (eager) {
+ eagerTotal += v.bytes;
+ eagerCount++;
+ eagerChunks.push([out, v]);
+ } else {
+ lazyTotal += v.bytes;
+ }
+ }
+
+ const mb = (n) => (n / 1048576).toFixed(2);
+ console.log(`startup-loaded: ${mb(eagerTotal)} MB in ${eagerCount} files; stays lazy: ${mb(lazyTotal)} MB`);
+ console.log("\n=== top packages in the startup-loaded set ===");
+ for (const [pkg, sz] of [...eagerByPkg.entries()].sort((a, b) => b[1] - a[1]).slice(0, top)) {
+ console.log(`${kb(sz)} ${pkg}`);
+ }
+ console.log("\n=== top packages that stay lazy ===");
+ for (const [pkg, sz] of [...lazyByPkg.entries()].sort((a, b) => b[1] - a[1]).slice(0, top)) {
+ console.log(`${kb(sz)} ${pkg}`);
+ }
+ console.log("\n=== biggest startup-loaded chunks (dominant input) ===");
+ eagerChunks.sort((a, b) => b[1].bytes - a[1].bytes);
+ for (const [out, v] of eagerChunks.slice(0, top)) {
+ const dominant = Object.entries(v.inputs ?? {}).sort((a, b) => b[1].bytesInOutput - a[1].bytesInOutput)[0];
+ console.log(`${kb(v.bytes)} ${tailKey(out)} <- ${dominant ? dominant[0] : "?"}`);
+ }
+}
+
+/** Finds the true entry input: the one output that is not under chunks/. */
+function findEntryInput(meta) {
+ const override = flag("--entry");
+ if (override) {
+ return override;
+ }
+ for (const [out, v] of Object.entries(meta.outputs)) {
+ if (/\.(mjs|cjs|js)$/.test(out) && !out.includes("/chunks/") && v.entryPoint) {
+ return v.entryPoint;
+ }
+ }
+ throw new Error("no entry output found; pass --entry <input path>");
+}
+
+/** BFS over static edges only — a dynamic-import edge is a lazy boundary. */
+function staticReachability(meta) {
+ const entry = findEntryInput(meta);
+ const prev = new Map([[entry, null]]);
+ const queue = [entry];
+ while (queue.length) {
+ const cur = queue.shift();
+ for (const imp of meta.inputs[cur]?.imports ?? []) {
+ if (imp.kind === "dynamic-import" || imp.external || !meta.inputs[imp.path] || prev.has(imp.path)) {
+ continue;
+ }
+ prev.set(imp.path, cur);
+ queue.push(imp.path);
+ }
+ }
+ return prev;
+}
+
+/** Explains why packages are eager: the shortest static import chain from the entry. */
+async function why() {
+ const meta = JSON.parse(fs.readFileSync(flag("--meta"), "utf8"));
+ const prev = staticReachability(meta);
+ const needles = args.filter((a) => !a.startsWith("--") && a !== flag("--meta") && a !== flag("--entry"));
+ for (const needle of needles) {
+ const target = [...prev.keys()].find((k) => k.includes(needle));
+ if (!target) {
+ console.log(`\n${needle}: NOT statically reachable.`);
+ console.log(" If it still loads at boot (per a recording), a dynamic import runs during startup — find and defer that call.");
+ continue;
+ }
+ const chain = [];
+ for (let n = target; n; n = prev.get(n)) {
+ chain.unshift(n);
+ }
+ console.log(`\n${needle}: eager via`);
+ for (const p of chain) {
+ console.log(" " + p);
+ }
+ }
+}
+
+/** Whole-bundle composition, no recording needed. */
+async function packages() {
+ const meta = JSON.parse(fs.readFileSync(flag("--meta"), "utf8"));
+ const top = Number(flag("--top", "25"));
+ const byPkg = new Map();
+ let total = 0;
+ for (const v of Object.values(meta.outputs)) {
+ for (const [inp, iv] of Object.entries(v.inputs ?? {})) {
+ byPkg.set(pkgOf(inp), (byPkg.get(pkgOf(inp)) ?? 0) + iv.bytesInOutput);
+ total += iv.bytesInOutput;
+ }
+ }
+ console.log(`total bundled: ${(total / 1048576).toFixed(2)} MB`);
+ for (const [pkg, sz] of [...byPkg.entries()].sort((a, b) => b[1] - a[1]).slice(0, top)) {
+ console.log(`${kb(sz)} ${pkg}`);
+ }
+}
diff --git a/.claude/skills/analyzing-backend-bundle/heap-strings.mjs b/.claude/skills/analyzing-backend-bundle/heap-strings.mjs
new file mode 100644
index 0000000000..a784ff9099
--- /dev/null
+++ b/.claude/skills/analyzing-backend-bundle/heap-strings.mjs
@@ -0,0 +1,70 @@
+// Aggregates a V8 .heapsnapshot by node type and lists the largest strings,
+// classifying retained script sources — the proof of what the process keeps
+// in heap for each loaded bundle/chunk.
+//
+// node --max-old-space-size=8192 heap-strings.mjs <file.heapsnapshot> [--min-kb 128]
+import fs from "node:fs";
+
+const snapPath = process.argv[2];
+const minIdx = process.argv.indexOf("--min-kb");
+const minBytes = (minIdx >= 0 ? Number(process.argv[minIdx + 1]) : 128) * 1024;
+
+console.error("parsing snapshot...");
+const snap = JSON.parse(fs.readFileSync(snapPath, "utf8"));
+
+const meta = snap.snapshot.meta;
+const nodeTypes = meta.node_types[0];
+const fieldCount = meta.node_fields.length;
+const idxType = meta.node_fields.indexOf("type");
+const idxName = meta.node_fields.indexOf("name");
+const idxSelfSize = meta.node_fields.indexOf("self_size");
+
+const byType = new Map();
+const big = [];
+for (let i = 0; i < snap.nodes.length; i += fieldCount) {
+ const type = nodeTypes[snap.nodes[i + idxType]];
+ const size = snap.nodes[i + idxSelfSize];
+ const agg = byType.get(type) ?? { count: 0, size: 0 };
+ agg.count++;
+ agg.size += size;
+ byType.set(type, agg);
+ if (size >= minBytes) {
+ big.push({ type, size, nameIdx: snap.nodes[i + idxName] });
+ }
+}
+
+const totalSize = [...byType.values()].reduce((a, b) => a + b.size, 0);
+console.log(`total self_size: ${(totalSize / 1048576).toFixed(1)} MB, nodes: ${snap.nodes.length / fieldCount}`);
+console.log("\n=== self_size by node type ===");
+for (const [type, agg] of [...byType.entries()].sort((a, b) => b[1].size - a[1].size)) {
+ console.log(`${(agg.size / 1048576).toFixed(2).padStart(8)} MB ${String(agg.count).padStart(8)} nodes ${type}`);
+}
+
+// The buildBackend banners open every bundle/chunk, so a retained source
+// string is recognizable by its first characters.
+const SOURCE_PREFIXES = [
+ "const __bundleImportMetaUrl", // CJS bundle
+ "import { createRequire as __bundleCreateRequire", // ESM bundle/chunk
+];
+const isSource = (s) => SOURCE_PREFIXES.some((p) => s.startsWith(p));
+
+big.sort((a, b) => b.size - a.size);
+let sourceBytes = 0;
+let sourceCount = 0;
+console.log(`\n=== strings >= ${(minBytes / 1024).toFixed(0)} KB ===`);
+for (const n of big) {
+ if (!n.type.includes("string")) {
+ continue;
+ }
+ const s = snap.strings[n.nameIdx] ?? "";
+ if (isSource(s)) {
+ sourceBytes += n.size;
+ sourceCount++;
+ }
+ // A one-byte source string weighs ~its file size; two-byte weighs double —
+ // if a source string is ~2x its chunk's size on disk, the chunk contains
+ // characters above U+00FF (see SKILL.md).
+ const label = isSource(s) ? "SCRIPT SOURCE" : "string";
+ console.log(`${(n.size / 1048576).toFixed(2).padStart(8)} MB ${label.padEnd(14)} ${s.replace(/\s+/g, " ").slice(0, 90)}`);
+}
+console.log(`\nretained script source: ${(sourceBytes / 1048576).toFixed(2)} MB in ${sourceCount} strings`);
diff --git a/.claude/skills/analyzing-backend-bundle/loghook.cjs b/.claude/skills/analyzing-backend-bundle/loghook.cjs
new file mode 100644
index 0000000000..447570a3d6
--- /dev/null
+++ b/.claude/skills/analyzing-backend-bundle/loghook.cjs
@@ -0,0 +1,15 @@
+// Records every module the process loads into the file named by LOAD_LOG.
+// Preloaded via `node --require`; analyze-bundle.mjs record does this for you.
+// Only files under a dist/ directory are recorded — node built-ins and the
+// hook's own machinery are noise for bundle analysis.
+const { registerHooks } = require("node:module");
+const fs = require("fs");
+
+registerHooks({
+ load(url, context, nextLoad) {
+ if (url.includes("/dist/") && process.env.LOAD_LOG) {
+ fs.appendFileSync(process.env.LOAD_LOG, url + "\n");
+ }
+ return nextLoad(url, context);
+ }
+});
diff --git a/.claude/skills/analyzing-backend-bundle/profile-bundle.cjs b/.claude/skills/analyzing-backend-bundle/profile-bundle.cjs
new file mode 100644
index 0000000000..9ee6beeb6b
--- /dev/null
+++ b/.claude/skills/analyzing-backend-bundle/profile-bundle.cjs
@@ -0,0 +1,82 @@
+// Boots a backend bundle, waits for it to serve HTTP, then records memory
+// statistics (and optionally a heap snapshot) and exits.
+//
+// node --expose-gc profile-bundle.cjs <bundle> [--port 8123] [--stats out.json] [--snapshot out.heapsnapshot]
+//
+// The caller supplies the TRILIUM_* environment (see SKILL.md). Run with
+// --expose-gc so the post-GC numbers are meaningful. Without --port the
+// script settles on a fixed 20 s timer instead of polling.
+const v8 = require("v8");
+const http = require("http");
+const fs = require("fs");
+const { pathToFileURL } = require("url");
+
+const args = process.argv.slice(2);
+const bundle = args[0];
+const flag = (name) => {
+ const i = args.indexOf(name);
+ return i >= 0 ? args[i + 1] : undefined;
+};
+const port = flag("--port");
+const statsOut = flag("--stats") || "memory-stats.json";
+const snapshotOut = flag("--snapshot");
+
+if (!bundle) {
+ console.error("usage: node --expose-gc profile-bundle.cjs <bundle.mjs|bundle.cjs> [--port N] [--stats f] [--snapshot f]");
+ process.exit(1);
+}
+
+function collectStats(label) {
+ return {
+ label,
+ memoryUsage: process.memoryUsage(),
+ heapStatistics: v8.getHeapStatistics(),
+ heapCodeStatistics: v8.getHeapCodeStatistics(),
+ };
+}
+
+const stats = [collectStats("baseline (before load)")];
+
+if (bundle.endsWith(".mjs")) {
+ import(pathToFileURL(bundle).href);
+} else {
+ require(bundle);
+}
+
+function waitForServer(retries) {
+ if (retries <= 0) {
+ console.error("server never became ready; collecting anyway");
+ finish();
+ return;
+ }
+ const req = http.get({ host: "127.0.0.1", port, path: "/" }, (res) => {
+ res.resume();
+ console.log(`server responded with ${res.statusCode}, settling 15s...`);
+ setTimeout(finish, 15000);
+ });
+ req.on("error", () => setTimeout(() => waitForServer(retries - 1), 500));
+}
+
+function finish() {
+ stats.push(collectStats("after startup (pre-GC)"));
+ if (global.gc) {
+ for (let i = 0; i < 3; i++) global.gc();
+ }
+ stats.push(collectStats("after startup (post-GC)"));
+ fs.writeFileSync(statsOut, JSON.stringify(stats, null, 2));
+ const last = stats[stats.length - 1];
+ const mb = (n) => (n / 1048576).toFixed(1) + " MB";
+ console.log(`rss=${mb(last.memoryUsage.rss)} heapUsed=${mb(last.memoryUsage.heapUsed)} heapTotal=${mb(last.memoryUsage.heapTotal)} (details: ${statsOut})`);
+ if (snapshotOut) {
+ console.log("writing heap snapshot...");
+ v8.writeHeapSnapshot(snapshotOut);
+ console.log(`snapshot: ${snapshotOut} (${fs.statSync(snapshotOut).size} bytes)`);
+ }
+ process.exit(0);
+}
+
+if (port) {
+ setTimeout(() => waitForServer(120), 2000);
+} else {
+ setTimeout(finish, 20000);
+}