@yetanotheraryan/coldstart 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aryan Tiwari
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,261 @@
1
+ // src/tracer.ts
2
+ import { monitorEventLoopDelay } from "perf_hooks";
3
+ var Tracer = class {
4
+ events = [];
5
+ startTime = performance.now();
6
+ histogram = null;
7
+ constructor() {
8
+ try {
9
+ this.histogram = monitorEventLoopDelay({ resolution: 5 });
10
+ this.histogram.enable();
11
+ } catch {
12
+ this.histogram = null;
13
+ }
14
+ }
15
+ /**
16
+ * Called by cjs.ts for every require() interception.
17
+ * Appends to the flat event list — tree is built lazily on report().
18
+ */
19
+ record(event) {
20
+ this.events.push(event);
21
+ }
22
+ /**
23
+ * Mark startup as complete and return the full report.
24
+ * Call this after your server/app signals it's ready.
25
+ */
26
+ report() {
27
+ const totalStartupMs = performance.now() - this.startTime;
28
+ if (this.histogram) {
29
+ this.histogram.disable();
30
+ }
31
+ const tree = this.buildTree();
32
+ const flat = this.flatten(tree).sort((a, b) => b.inclusiveMs - a.inclusiveMs);
33
+ const slowest = [...flat].filter((n) => !n.cached && !n.isBuiltin).sort((a, b) => b.exclusiveMs - a.exclusiveMs).slice(0, 10);
34
+ const nodeModuleTime = flat.filter((n) => n.isNodeModule && !n.cached).reduce((sum, n) => sum + n.exclusiveMs, 0);
35
+ const firstPartyTime = flat.filter((n) => !n.isNodeModule && !n.isBuiltin && !n.cached).reduce((sum, n) => sum + n.exclusiveMs, 0);
36
+ return {
37
+ totalStartupMs,
38
+ eventLoop: {
39
+ maxBlockMs: this.histogram ? this.histogram.max / 1e6 : 0,
40
+ meanBlockMs: this.histogram ? this.histogram.mean / 1e6 : 0,
41
+ p99BlockMs: this.histogram ? this.histogram.percentile(99) / 1e6 : 0
42
+ },
43
+ tree,
44
+ flat,
45
+ slowest,
46
+ nodeModuleTime,
47
+ firstPartyTime,
48
+ totalModulesLoaded: this.events.length,
49
+ cachedModulesCount: this.events.filter((e) => e.cached).length
50
+ };
51
+ }
52
+ /**
53
+ * Build the parent→child tree from the flat event list.
54
+ *
55
+ * Strategy:
56
+ * 1. Create a ModuleNode for each event
57
+ * 2. Wire children to parents using parentPath
58
+ * 3. Compute exclusive time = inclusive - sum(children inclusive)
59
+ * 4. Assign depth via BFS from roots
60
+ */
61
+ buildTree() {
62
+ const nodes = this.events.map((e) => ({
63
+ id: e.id,
64
+ request: e.request,
65
+ resolvedPath: e.resolvedPath,
66
+ parentPath: e.parentPath,
67
+ inclusiveMs: e.durationMs,
68
+ exclusiveMs: e.durationMs,
69
+ // will be adjusted below
70
+ cached: e.cached,
71
+ isNodeModule: e.isNodeModule,
72
+ isBuiltin: e.isBuiltin,
73
+ children: [],
74
+ depth: 0
75
+ }));
76
+ const byPath = /* @__PURE__ */ new Map();
77
+ for (const node of nodes) {
78
+ const existing = byPath.get(node.resolvedPath) ?? [];
79
+ existing.push(node);
80
+ byPath.set(node.resolvedPath, existing);
81
+ }
82
+ const roots = [];
83
+ for (const node of nodes) {
84
+ if (node.parentPath === "<entry>") {
85
+ roots.push(node);
86
+ continue;
87
+ }
88
+ const parentNodes = byPath.get(node.parentPath);
89
+ if (parentNodes && parentNodes.length > 0) {
90
+ parentNodes[parentNodes.length - 1].children.push(node);
91
+ } else {
92
+ roots.push(node);
93
+ }
94
+ }
95
+ const computeExclusive = (node) => {
96
+ for (const child of node.children) {
97
+ computeExclusive(child);
98
+ }
99
+ const childrenInclusiveSum = node.children.reduce(
100
+ (sum, c) => sum + c.inclusiveMs,
101
+ 0
102
+ );
103
+ node.exclusiveMs = Math.max(0, node.inclusiveMs - childrenInclusiveSum);
104
+ };
105
+ for (const root of roots) {
106
+ computeExclusive(root);
107
+ }
108
+ const assignDepth = (node, depth) => {
109
+ node.depth = depth;
110
+ for (const child of node.children) {
111
+ assignDepth(child, depth + 1);
112
+ }
113
+ };
114
+ for (const root of roots) {
115
+ assignDepth(root, 0);
116
+ }
117
+ return roots;
118
+ }
119
+ /**
120
+ * Flatten the tree into a list (pre-order DFS).
121
+ */
122
+ flatten(nodes) {
123
+ const result = [];
124
+ const visit = (node) => {
125
+ result.push(node);
126
+ for (const child of node.children) {
127
+ visit(child);
128
+ }
129
+ };
130
+ for (const node of nodes) {
131
+ visit(node);
132
+ }
133
+ return result;
134
+ }
135
+ /**
136
+ * Reset — useful for testing multiple startups in the same process.
137
+ */
138
+ reset() {
139
+ this.events = [];
140
+ this.startTime = performance.now();
141
+ if (this.histogram) {
142
+ this.histogram.reset();
143
+ this.histogram.enable();
144
+ }
145
+ }
146
+ /** Expose raw events for testing */
147
+ getRawEvents() {
148
+ return [...this.events];
149
+ }
150
+ };
151
+ var tracer = new Tracer();
152
+
153
+ // src/cjs.ts
154
+ import { Module } from "module";
155
+ var originalLoad = Module._load;
156
+ var callStack = [];
157
+ Module._load = function coldstartLoad(request, parent, isMain) {
158
+ let resolvedFilename;
159
+ try {
160
+ resolvedFilename = Module._resolveFilename(request, parent, isMain);
161
+ } catch {
162
+ return originalLoad.apply(this, arguments);
163
+ }
164
+ const isCached = !!Module._cache[resolvedFilename];
165
+ const isBuiltin = Module.isBuiltin?.(request) ?? isBuiltinModule(request);
166
+ const parentFilename = callStack.length > 0 ? callStack[callStack.length - 1] : parent?.filename ?? "<entry>";
167
+ callStack.push(resolvedFilename);
168
+ const startTime = performance.now();
169
+ let result;
170
+ try {
171
+ result = originalLoad.apply(this, arguments);
172
+ } finally {
173
+ callStack.pop();
174
+ if (!isBuiltin) {
175
+ const duration = performance.now() - startTime;
176
+ tracer.record({
177
+ id: resolvedFilename,
178
+ request,
179
+ // original string passed to require()
180
+ resolvedPath: resolvedFilename,
181
+ parentPath: parentFilename,
182
+ durationMs: duration,
183
+ startTime,
184
+ cached: isCached,
185
+ isNodeModule: resolvedFilename.includes("node_modules"),
186
+ isBuiltin: false
187
+ });
188
+ }
189
+ }
190
+ return result;
191
+ };
192
+ var originalResolveFilename = Module._resolveFilename;
193
+ Module._resolveFilename = function coldstartResolve(request, parent, isMain, options) {
194
+ if (Module.isBuiltin?.(request) ?? isBuiltinModule(request)) {
195
+ const parentFilename = callStack.length > 0 ? callStack[callStack.length - 1] : parent?.filename ?? "<entry>";
196
+ tracer.record({
197
+ id: `builtin:${request}`,
198
+ request,
199
+ resolvedPath: `builtin:${request}`,
200
+ parentPath: parentFilename,
201
+ durationMs: 0,
202
+ startTime: performance.now(),
203
+ cached: true,
204
+ isNodeModule: false,
205
+ isBuiltin: true
206
+ });
207
+ }
208
+ return originalResolveFilename.apply(this, arguments);
209
+ };
210
+ function isBuiltinModule(name) {
211
+ const builtins = /* @__PURE__ */ new Set([
212
+ "assert",
213
+ "async_hooks",
214
+ "buffer",
215
+ "child_process",
216
+ "cluster",
217
+ "console",
218
+ "constants",
219
+ "crypto",
220
+ "dgram",
221
+ "diagnostics_channel",
222
+ "dns",
223
+ "domain",
224
+ "events",
225
+ "fs",
226
+ "http",
227
+ "http2",
228
+ "https",
229
+ "inspector",
230
+ "module",
231
+ "net",
232
+ "os",
233
+ "path",
234
+ "perf_hooks",
235
+ "process",
236
+ "punycode",
237
+ "querystring",
238
+ "readline",
239
+ "repl",
240
+ "stream",
241
+ "string_decoder",
242
+ "sys",
243
+ "timers",
244
+ "tls",
245
+ "trace_events",
246
+ "tty",
247
+ "url",
248
+ "util",
249
+ "v8",
250
+ "vm",
251
+ "wasi",
252
+ "worker_threads",
253
+ "zlib"
254
+ ]);
255
+ const stripped = name.startsWith("node:") ? name.slice(5) : name;
256
+ return builtins.has(stripped);
257
+ }
258
+
259
+ export {
260
+ tracer
261
+ };
@@ -0,0 +1,12 @@
1
+ // node_modules/tsup/assets/esm_shims.js
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ var getFilename = () => fileURLToPath(import.meta.url);
5
+ var getDirname = () => path.dirname(getFilename());
6
+ var __dirname = /* @__PURE__ */ getDirname();
7
+ var __filename = /* @__PURE__ */ getFilename();
8
+
9
+ export {
10
+ __dirname,
11
+ __filename
12
+ };
@@ -0,0 +1,170 @@
1
+ // src/reporter/text.ts
2
+ var BAR_WIDTH = 18;
3
+ var ANSI_RESET = "\x1B[0m";
4
+ var ANSI_RED = "\x1B[31m";
5
+ var ANSI_YELLOW = "\x1B[33m";
6
+ var ANSI_GREEN = "\x1B[32m";
7
+ var ANSI_DIM = "\x1B[2m";
8
+ function renderTextReport(report, options = {}) {
9
+ const color = options.color ?? true;
10
+ const barWidth = options.barWidth ?? BAR_WIDTH;
11
+ const showSummary = options.showSummary ?? true;
12
+ const displayTree = collapseDisplayNoise(report.tree);
13
+ const maxInclusiveMs = Math.max(
14
+ 1,
15
+ ...report.flat.filter((node) => !node.cached).map((node) => node.inclusiveMs)
16
+ );
17
+ const lines = [
18
+ `coldstart - ${formatDuration(report.totalStartupMs)} total startup`,
19
+ ""
20
+ ];
21
+ for (let index = 0; index < displayTree.length; index += 1) {
22
+ const isLastRoot = index === displayTree.length - 1;
23
+ const root = displayTree[index];
24
+ lines.push(...renderNode(root, "", isLastRoot, maxInclusiveMs, barWidth, color));
25
+ }
26
+ if (showSummary) {
27
+ if (displayTree.length > 0) {
28
+ lines.push("");
29
+ }
30
+ lines.push(
31
+ `${dim("event loop")} max ${formatDuration(report.eventLoop.maxBlockMs)}, p99 ${formatDuration(report.eventLoop.p99BlockMs)}, mean ${formatDuration(report.eventLoop.meanBlockMs)}`,
32
+ `${dim("modules")} ${report.totalModulesLoaded} total, ${report.cachedModulesCount} cached`,
33
+ `${dim("time split")} ${formatDuration(report.firstPartyTime)} first-party, ${formatDuration(report.nodeModuleTime)} node_modules`
34
+ );
35
+ }
36
+ return lines.join("\n");
37
+ function dim(value) {
38
+ return colorize(value, ANSI_DIM, color);
39
+ }
40
+ }
41
+ function collapseDisplayNoise(nodes) {
42
+ const result = [];
43
+ const seen = /* @__PURE__ */ new Set();
44
+ for (const node of nodes) {
45
+ const collapsedChildren = collapseDisplayNoise(node.children);
46
+ const collapsedNode = {
47
+ ...node,
48
+ children: collapsedChildren
49
+ };
50
+ if (shouldCollapseBuiltinNode(collapsedNode)) {
51
+ const key = [
52
+ collapsedNode.request,
53
+ collapsedNode.depth
54
+ ].join("|");
55
+ if (seen.has(key)) {
56
+ continue;
57
+ }
58
+ seen.add(key);
59
+ }
60
+ result.push(collapsedNode);
61
+ }
62
+ return result;
63
+ }
64
+ function shouldCollapseBuiltinNode(node) {
65
+ return node.isBuiltin && node.cached && node.inclusiveMs === 0 && node.children.length === 0;
66
+ }
67
+ function renderNode(node, prefix, isLast, maxInclusiveMs, barWidth, color) {
68
+ const branch = prefix.length === 0 ? isLast ? "\u2514\u2500 " : "\u250C\u2500 " : `${prefix}${isLast ? "\u2514\u2500 " : "\u251C\u2500 "}`;
69
+ const nextPrefix = prefix.length === 0 ? isLast ? " " : "\u2502 " : `${prefix}${isLast ? " " : "\u2502 "}`;
70
+ const label = formatLabel(node);
71
+ const duration = formatDuration(node.inclusiveMs).padStart(6);
72
+ const durationColor = getDurationColor(node.inclusiveMs);
73
+ const bar = renderBar(node.inclusiveMs, maxInclusiveMs, barWidth);
74
+ const suffix = node.inclusiveMs >= 100 ? ` ${colorize("! slow", ANSI_RED, color)}` : "";
75
+ const line = `${branch}${label.padEnd(18)} ${colorize(duration, durationColor, color)} ${colorize(bar, durationColor, color)}${suffix}`;
76
+ const lines = [line];
77
+ for (let index = 0; index < node.children.length; index += 1) {
78
+ const child = node.children[index];
79
+ const isLastChild = index === node.children.length - 1;
80
+ lines.push(...renderNode(child, nextPrefix, isLastChild, maxInclusiveMs, barWidth, color));
81
+ }
82
+ return lines;
83
+ }
84
+ function formatLabel(node) {
85
+ if (node.isBuiltin) {
86
+ return node.request.replace(/^node:/, "");
87
+ }
88
+ if (node.isNodeModule) {
89
+ return packageNameFromRequest(node.request);
90
+ }
91
+ const normalizedPath = normalizeModulePath(node);
92
+ const segments = normalizedPath.split("/");
93
+ const base = segments[segments.length - 1] ?? "";
94
+ return base.length > 0 ? base : node.request;
95
+ }
96
+ function normalizeModulePath(node) {
97
+ if (looksLikeRelativeRequest(node.request)) {
98
+ return node.request.replace(/\\/g, "/");
99
+ }
100
+ if (node.resolvedPath.startsWith("file://")) {
101
+ try {
102
+ return decodeURIComponent(new URL(node.resolvedPath).pathname).replace(/\\/g, "/");
103
+ } catch {
104
+ return node.resolvedPath.replace(/\\/g, "/");
105
+ }
106
+ }
107
+ return node.resolvedPath.replace(/\\/g, "/");
108
+ }
109
+ function looksLikeRelativeRequest(request) {
110
+ return request.startsWith("./") || request.startsWith("../") || request.startsWith("/");
111
+ }
112
+ function packageNameFromRequest(request) {
113
+ if (request.startsWith("@")) {
114
+ const [scope, name2] = request.split("/");
115
+ return name2 ? `${scope}/${name2}` : request;
116
+ }
117
+ const [name] = request.split("/");
118
+ return name || request;
119
+ }
120
+ function renderBar(durationMs, maxInclusiveMs, barWidth) {
121
+ const filled = Math.max(1, Math.round(durationMs / maxInclusiveMs * barWidth));
122
+ return `${"\u2588".repeat(Math.min(barWidth, filled))}${"\u2591".repeat(Math.max(0, barWidth - filled))}`;
123
+ }
124
+ function formatDuration(valueMs) {
125
+ if (!Number.isFinite(valueMs)) {
126
+ return "0ms";
127
+ }
128
+ if (valueMs >= 1e3) {
129
+ return `${Math.round(valueMs)}ms`;
130
+ }
131
+ if (valueMs >= 100) {
132
+ return `${Math.round(valueMs)}ms`;
133
+ }
134
+ if (valueMs >= 10) {
135
+ return `${valueMs.toFixed(1).replace(/\.0$/, "")}ms`;
136
+ }
137
+ return `${valueMs.toFixed(2).replace(/0+$/, "").replace(/\.$/, "")}ms`;
138
+ }
139
+ function getDurationColor(durationMs) {
140
+ if (durationMs > 100) {
141
+ return ANSI_RED;
142
+ }
143
+ if (durationMs >= 20) {
144
+ return ANSI_YELLOW;
145
+ }
146
+ return ANSI_GREEN;
147
+ }
148
+ function colorize(value, code, enabled) {
149
+ if (!enabled) {
150
+ return value;
151
+ }
152
+ return `${code}${value}${ANSI_RESET}`;
153
+ }
154
+
155
+ // src/reporter/json.ts
156
+ function renderJsonReport(report, options = {}) {
157
+ return `${JSON.stringify(report, jsonReplacer, options.pretty === false ? 0 : 2)}
158
+ `;
159
+ }
160
+ function jsonReplacer(_key, value) {
161
+ if (typeof value === "number" && !Number.isFinite(value)) {
162
+ return 0;
163
+ }
164
+ return value;
165
+ }
166
+
167
+ export {
168
+ renderTextReport,
169
+ renderJsonReport
170
+ };
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node