bugstack-sdk 2.0.2 → 2.2.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/CHANGELOG.md +87 -0
- package/README.md +421 -346
- package/bin/bugstack.cjs +6 -0
- package/dist/adapters/express/index.d.mts +2 -2
- package/dist/adapters/express/index.d.ts +2 -2
- package/dist/adapters/express/index.js +130 -15
- package/dist/adapters/express/index.js.map +1 -1
- package/dist/adapters/express/index.mjs +130 -15
- package/dist/adapters/express/index.mjs.map +1 -1
- package/dist/adapters/generic/index.d.mts +2 -2
- package/dist/adapters/generic/index.d.ts +2 -2
- package/dist/adapters/generic/index.js +66 -5
- package/dist/adapters/generic/index.js.map +1 -1
- package/dist/adapters/generic/index.mjs +66 -5
- package/dist/adapters/generic/index.mjs.map +1 -1
- package/dist/adapters/nextjs/index.d.mts +2 -2
- package/dist/adapters/nextjs/index.d.ts +2 -2
- package/dist/adapters/nextjs/index.js +72 -7
- package/dist/adapters/nextjs/index.js.map +1 -1
- package/dist/adapters/nextjs/index.mjs +72 -7
- package/dist/adapters/nextjs/index.mjs.map +1 -1
- package/dist/build/cli.d.mts +2 -0
- package/dist/build/cli.d.ts +2 -0
- package/dist/build/cli.js +256 -0
- package/dist/build/cli.js.map +1 -0
- package/dist/build/cli.mjs +254 -0
- package/dist/build/cli.mjs.map +1 -0
- package/dist/build/upload.d.mts +82 -0
- package/dist/build/upload.d.ts +82 -0
- package/dist/build/upload.js +163 -0
- package/dist/build/upload.js.map +1 -0
- package/dist/build/upload.mjs +161 -0
- package/dist/build/upload.mjs.map +1 -0
- package/dist/{client-9EMqVMOl.d.mts → client-DoqE7sNh.d.mts} +42 -1
- package/dist/{client-9EMqVMOl.d.ts → client-DoqE7sNh.d.ts} +42 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +73 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +73 -8
- package/dist/index.mjs.map +1 -1
- package/dist/next-config/index.d.mts +56 -0
- package/dist/next-config/index.d.ts +56 -0
- package/dist/next-config/index.js +28 -0
- package/dist/next-config/index.js.map +1 -0
- package/dist/next-config/index.mjs +23 -0
- package/dist/next-config/index.mjs.map +1 -0
- package/package.json +23 -9
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var promises = require('fs/promises');
|
|
4
|
+
var path = require('path');
|
|
5
|
+
var child_process = require('child_process');
|
|
6
|
+
|
|
7
|
+
// src/build/upload.ts
|
|
8
|
+
var DEFAULT_SERVER_DIR = ".next/server";
|
|
9
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
10
|
+
var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
|
|
11
|
+
var ENDPOINT_PATH = "/api/sourcemaps/upload";
|
|
12
|
+
function resolveRelease(explicit) {
|
|
13
|
+
if (explicit !== void 0) return explicit;
|
|
14
|
+
const fromEnv = process.env.BUGSTACK_RELEASE || process.env.RENDER_GIT_COMMIT || process.env.VERCEL_GIT_COMMIT_SHA || process.env.GITHUB_SHA;
|
|
15
|
+
if (fromEnv) return fromEnv;
|
|
16
|
+
try {
|
|
17
|
+
return child_process.execSync("git rev-parse HEAD", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function resolveEndpoint(explicit) {
|
|
23
|
+
const base = explicit || process.env.BUGSTACK_ENDPOINT || (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);
|
|
24
|
+
if (!base) return null;
|
|
25
|
+
const normalised = base.replace(/\/+$/, "").replace(/\/api\/capture$/, "").replace(/\/capture$/, "");
|
|
26
|
+
return normalised + ENDPOINT_PATH;
|
|
27
|
+
}
|
|
28
|
+
async function walk(dir) {
|
|
29
|
+
let entries;
|
|
30
|
+
try {
|
|
31
|
+
entries = await promises.readdir(dir, { withFileTypes: true });
|
|
32
|
+
} catch (err) {
|
|
33
|
+
if (err.code === "ENOENT") return [];
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
const out = [];
|
|
37
|
+
for (const entry of entries) {
|
|
38
|
+
const path$1 = path.join(dir, entry.name);
|
|
39
|
+
if (entry.isDirectory()) {
|
|
40
|
+
out.push(...await walk(path$1));
|
|
41
|
+
} else if (entry.name.endsWith(".map")) {
|
|
42
|
+
out.push(path$1);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
async function pool(items, workers, fn) {
|
|
48
|
+
const results = new Array(items.length);
|
|
49
|
+
let i = 0;
|
|
50
|
+
const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {
|
|
51
|
+
while (i < items.length) {
|
|
52
|
+
const idx = i++;
|
|
53
|
+
results[idx] = await fn(items[idx]);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
await Promise.all(runners);
|
|
57
|
+
return results;
|
|
58
|
+
}
|
|
59
|
+
function bundleFileFor(mapPath, serverDir) {
|
|
60
|
+
return path.relative(serverDir, mapPath).replace(/\.map$/, "").split(path.sep).join("/");
|
|
61
|
+
}
|
|
62
|
+
async function uploadSourceMaps(options = {}) {
|
|
63
|
+
const apiKey = options.apiKey || process.env.BUGSTACK_PROJECT_API_KEY || process.env.BUGSTACK_API_KEY;
|
|
64
|
+
const endpoint = resolveEndpoint(options.endpoint);
|
|
65
|
+
const release = resolveRelease(options.release);
|
|
66
|
+
const serverDir = options.serverDir || DEFAULT_SERVER_DIR;
|
|
67
|
+
const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
|
|
68
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
69
|
+
const log = options.log || ((m) => console.log(m));
|
|
70
|
+
const warn = options.warn || ((m) => console.warn(m));
|
|
71
|
+
if (!apiKey) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly."
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
if (!endpoint) {
|
|
77
|
+
throw new Error(
|
|
78
|
+
"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly."
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
const start = Date.now();
|
|
82
|
+
const mapFiles = await walk(serverDir);
|
|
83
|
+
if (mapFiles.length === 0) {
|
|
84
|
+
log(
|
|
85
|
+
`[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`
|
|
86
|
+
);
|
|
87
|
+
return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };
|
|
88
|
+
}
|
|
89
|
+
log(
|
|
90
|
+
`[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || "none"})...`
|
|
91
|
+
);
|
|
92
|
+
const results = await pool(mapFiles, concurrency, async (mapPath) => {
|
|
93
|
+
const bundleFile = bundleFileFor(mapPath, serverDir);
|
|
94
|
+
const stats = await promises.stat(mapPath);
|
|
95
|
+
if (stats.size > maxBytes) {
|
|
96
|
+
return {
|
|
97
|
+
ok: false,
|
|
98
|
+
bundleFile,
|
|
99
|
+
bytes: 0,
|
|
100
|
+
skipped: true,
|
|
101
|
+
error: `Skipped \u2014 ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const mapJson = await promises.readFile(mapPath, "utf8");
|
|
105
|
+
try {
|
|
106
|
+
const res = await fetch(endpoint, {
|
|
107
|
+
method: "POST",
|
|
108
|
+
headers: {
|
|
109
|
+
"Content-Type": "application/json",
|
|
110
|
+
"X-BugStack-API-Key": apiKey
|
|
111
|
+
},
|
|
112
|
+
body: JSON.stringify({ bundleFile, mapJson, release })
|
|
113
|
+
});
|
|
114
|
+
if (!res.ok) {
|
|
115
|
+
const text = await res.text().catch(() => "");
|
|
116
|
+
return {
|
|
117
|
+
ok: false,
|
|
118
|
+
bundleFile,
|
|
119
|
+
bytes: 0,
|
|
120
|
+
skipped: false,
|
|
121
|
+
error: `HTTP ${res.status} ${text.slice(0, 200)}`
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
return { ok: true, bundleFile, bytes: stats.size, skipped: false };
|
|
125
|
+
} catch (err) {
|
|
126
|
+
return {
|
|
127
|
+
ok: false,
|
|
128
|
+
bundleFile,
|
|
129
|
+
bytes: 0,
|
|
130
|
+
skipped: false,
|
|
131
|
+
error: err instanceof Error ? err.message : String(err)
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
const uploaded = results.filter((r) => r.ok).length;
|
|
136
|
+
const skipped = results.filter((r) => !r.ok && r.skipped).length;
|
|
137
|
+
const failed = results.length - uploaded - skipped;
|
|
138
|
+
const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);
|
|
139
|
+
const failures = results.filter((r) => !r.ok && !r.skipped).map((r) => ({ bundleFile: r.bundleFile, error: r.error }));
|
|
140
|
+
const elapsedMs = Date.now() - start;
|
|
141
|
+
log(
|
|
142
|
+
`[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(
|
|
143
|
+
1
|
|
144
|
+
)}MB) in ${(elapsedMs / 1e3).toFixed(1)}s.`
|
|
145
|
+
);
|
|
146
|
+
if (skipped > 0) {
|
|
147
|
+
warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);
|
|
148
|
+
}
|
|
149
|
+
if (failures.length > 0) {
|
|
150
|
+
warn(`[bugstack] ${failures.length} upload(s) failed:`);
|
|
151
|
+
for (const f of failures.slice(0, 10)) {
|
|
152
|
+
warn(` - ${f.bundleFile}: ${f.error}`);
|
|
153
|
+
}
|
|
154
|
+
if (failures.length > 10) {
|
|
155
|
+
warn(` \u2026and ${failures.length - 10} more`);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
exports.uploadSourceMaps = uploadSourceMaps;
|
|
162
|
+
//# sourceMappingURL=upload.js.map
|
|
163
|
+
//# sourceMappingURL=upload.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/build/upload.ts"],"names":["execSync","readdir","path","join","relative","sep","stat","readFile"],"mappings":";;;;;;;AAiFA,IAAM,kBAAA,GAAqB,cAAA;AAC3B,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,iBAAA,GAAoB,IAAI,IAAA,GAAO,IAAA;AACrC,IAAM,aAAA,GAAgB,wBAAA;AAEtB,SAAS,eAAe,QAAA,EAAyC;AAC/D,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA,MAAM,OAAA,GACJ,OAAA,CAAQ,GAAA,CAAI,gBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,iBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,qBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,UAAA;AACd,EAAA,IAAI,SAAS,OAAO,OAAA;AACpB,EAAA,IAAI;AACF,IAAA,OAAOA,sBAAA,CAAS,oBAAA,EAAsB,EAAE,KAAA,EAAO,CAAC,QAAA,EAAU,MAAA,EAAQ,QAAQ,CAAA,EAAG,CAAA,CAC1E,QAAA,GACA,IAAA,EAAK;AAAA,EACV,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEA,SAAS,gBAAgB,QAAA,EAAkC;AACzD,EAAA,MAAM,IAAA,GACJ,QAAA,IACA,OAAA,CAAQ,GAAA,CAAI,iBAAA,KACX,QAAQ,GAAA,CAAI,iBAAA,GAAoB,OAAA,CAAQ,GAAA,CAAI,iBAAA,GAAoB,IAAA,CAAA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A,IAAA,CAAK,CAAA,WAAA,EAAc,QAAA,CAAS,MAAM,CAAA,kBAAA,CAAoB,CAAA;AACtD,IAAA,KAAA,MAAW,CAAA,IAAK,QAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,EAAG;AACrC,MAAA,IAAA,CAAK,OAAO,CAAA,CAAE,UAAU,CAAA,EAAA,EAAK,CAAA,CAAE,KAAK,CAAA,CAAE,CAAA;AAAA,IACxC;AACA,IAAA,IAAI,QAAA,CAAS,SAAS,EAAA,EAAI;AACxB,MAAA,IAAA,CAAK,CAAA,YAAA,EAAU,QAAA,CAAS,MAAA,GAAS,EAAE,CAAA,KAAA,CAAO,CAAA;AAAA,IAC5C;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,MAAA,EAAQ,UAAA,EAAY,WAAW,QAAA,EAAS;AACtE","file":"upload.js","sourcesContent":["/**\r\n * Build-time source map uploader.\r\n *\r\n * Walks a directory of compiled output looking for `.map` files and POSTs\r\n * each one to the bugstack source-map ingest endpoint. The companion\r\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\r\n * Next.js server bundles; once uploaded, the orchestrator can resolve\r\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\r\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\r\n * generate fixes for bundled errors.\r\n *\r\n * This module is import-safe in any Node 18+ environment. It uses no\r\n * runtime dependencies — `node:fs/promises` + global `fetch`.\r\n */\r\n\r\nimport { readdir, readFile, stat } from \"node:fs/promises\";\r\nimport { join, relative, sep } from \"node:path\";\r\nimport { execSync } from \"node:child_process\";\r\n\r\nexport interface UploadSourceMapsOptions {\r\n /**\r\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\r\n * BUGSTACK_API_KEY when not supplied explicitly.\r\n */\r\n apiKey?: string;\r\n\r\n /**\r\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\r\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\r\n * `/api/sourcemaps/upload` to whatever base it gets.\r\n */\r\n endpoint?: string;\r\n\r\n /**\r\n * Release identifier (typically a commit SHA). Lets multiple deploys\r\n * coexist in the source-map table so old errors still resolve against\r\n * old maps. Auto-detected in this order:\r\n * 1. BUGSTACK_RELEASE\r\n * 2. RENDER_GIT_COMMIT\r\n * 3. VERCEL_GIT_COMMIT_SHA\r\n * 4. GITHUB_SHA\r\n * 5. `git rev-parse HEAD` (when a git checkout is present)\r\n */\r\n release?: string | null;\r\n\r\n /**\r\n * Directory to walk for `.map` files. Defaults to `.next/server`.\r\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\r\n */\r\n serverDir?: string;\r\n\r\n /**\r\n * Max concurrent uploads. Higher means faster builds, more pressure on\r\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\r\n */\r\n concurrency?: number;\r\n\r\n /**\r\n * Per-file size cap in bytes. Maps larger than this are skipped with a\r\n * warning rather than failing. Default 8 MiB — covers typical\r\n * `.next/server/chunks/*.js.map` outputs comfortably.\r\n */\r\n maxBytes?: number;\r\n\r\n /**\r\n * Logger. Defaults to console. Pass a no-op logger to silence the\r\n * \"[bugstack] …\" lines in scripted environments.\r\n */\r\n log?: (message: string) => void;\r\n warn?: (message: string) => void;\r\n}\r\n\r\nexport interface UploadResult {\r\n uploaded: number;\r\n skipped: number;\r\n failed: number;\r\n totalBytes: number;\r\n elapsedMs: number;\r\n failures: Array<{ bundleFile: string; error: string }>;\r\n}\r\n\r\nconst DEFAULT_SERVER_DIR = \".next/server\";\r\nconst DEFAULT_CONCURRENCY = 6;\r\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\r\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\r\n\r\nfunction resolveRelease(explicit?: string | null): string | null {\r\n if (explicit !== undefined) return explicit;\r\n const fromEnv =\r\n process.env.BUGSTACK_RELEASE ||\r\n process.env.RENDER_GIT_COMMIT ||\r\n process.env.VERCEL_GIT_COMMIT_SHA ||\r\n process.env.GITHUB_SHA;\r\n if (fromEnv) return fromEnv;\r\n try {\r\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\r\n .toString()\r\n .trim();\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction resolveEndpoint(explicit?: string): string | null {\r\n const base =\r\n explicit ||\r\n process.env.BUGSTACK_ENDPOINT ||\r\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\r\n if (!base) return null;\r\n // Strip trailing slashes + any trailing /api/capture or /capture so the\r\n // same env var that points the SDK at ingestion also works for sourcemaps.\r\n const normalised = base\r\n .replace(/\\/+$/, \"\")\r\n .replace(/\\/api\\/capture$/, \"\")\r\n .replace(/\\/capture$/, \"\");\r\n return normalised + ENDPOINT_PATH;\r\n}\r\n\r\nasync function walk(dir: string): Promise<string[]> {\r\n let entries;\r\n try {\r\n entries = await readdir(dir, { withFileTypes: true });\r\n } catch (err) {\r\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\r\n throw err;\r\n }\r\n const out: string[] = [];\r\n for (const entry of entries) {\r\n const path = join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n out.push(...(await walk(path)));\r\n } else if (entry.name.endsWith(\".map\")) {\r\n out.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nasync function pool<T, R>(\r\n items: T[],\r\n workers: number,\r\n fn: (item: T) => Promise<R>,\r\n): Promise<R[]> {\r\n const results: R[] = new Array(items.length);\r\n let i = 0;\r\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\r\n while (i < items.length) {\r\n const idx = i++;\r\n results[idx] = await fn(items[idx]);\r\n }\r\n });\r\n await Promise.all(runners);\r\n return results;\r\n}\r\n\r\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\r\n // Strip the serverDir prefix and the .map suffix; normalise Windows\r\n // backslashes so the bundleFile key stored on the server is portable\r\n // regardless of where the build ran.\r\n return relative(serverDir, mapPath)\r\n .replace(/\\.map$/, \"\")\r\n .split(sep)\r\n .join(\"/\");\r\n}\r\n\r\n/**\r\n * Upload every `.map` file under `serverDir` to the bugstack source-map\r\n * endpoint. Tolerant: never throws on individual file failures, returns\r\n * a summary the caller can decide what to do with.\r\n *\r\n * Throws only on hard configuration errors (no API key, no resolvable\r\n * endpoint, serverDir totally missing).\r\n */\r\nexport async function uploadSourceMaps(\r\n options: UploadSourceMapsOptions = {},\r\n): Promise<UploadResult> {\r\n const apiKey =\r\n options.apiKey ||\r\n process.env.BUGSTACK_PROJECT_API_KEY ||\r\n process.env.BUGSTACK_API_KEY;\r\n const endpoint = resolveEndpoint(options.endpoint);\r\n const release = resolveRelease(options.release);\r\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\r\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\r\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\r\n const log = options.log || ((m: string) => console.log(m));\r\n const warn = options.warn || ((m: string) => console.warn(m));\r\n\r\n if (!apiKey) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\r\n );\r\n }\r\n if (!endpoint) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\r\n );\r\n }\r\n\r\n const start = Date.now();\r\n const mapFiles = await walk(serverDir);\r\n\r\n if (mapFiles.length === 0) {\r\n log(\r\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\r\n );\r\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\r\n }\r\n\r\n log(\r\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\r\n );\r\n\r\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\r\n const bundleFile = bundleFileFor(mapPath, serverDir);\r\n const stats = await stat(mapPath);\r\n if (stats.size > maxBytes) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: true,\r\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\r\n };\r\n }\r\n const mapJson = await readFile(mapPath, \"utf8\");\r\n try {\r\n const res = await fetch(endpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": apiKey,\r\n },\r\n body: JSON.stringify({ bundleFile, mapJson, release }),\r\n });\r\n if (!res.ok) {\r\n const text = await res.text().catch(() => \"\");\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\r\n };\r\n }\r\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\r\n } catch (err) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n });\r\n\r\n const uploaded = results.filter((r) => r.ok).length;\r\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\r\n const failed = results.length - uploaded - skipped;\r\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\r\n const failures = results\r\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\r\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\r\n const elapsedMs = Date.now() - start;\r\n\r\n log(\r\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\r\n 1,\r\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\r\n );\r\n if (skipped > 0) {\r\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\r\n }\r\n if (failures.length > 0) {\r\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\r\n for (const f of failures.slice(0, 10)) {\r\n warn(` - ${f.bundleFile}: ${f.error}`);\r\n }\r\n if (failures.length > 10) {\r\n warn(` …and ${failures.length - 10} more`);\r\n }\r\n }\r\n\r\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\r\n}\r\n"]}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { readdir, stat, readFile } from 'fs/promises';
|
|
2
|
+
import { join, relative, sep } from 'path';
|
|
3
|
+
import { execSync } from 'child_process';
|
|
4
|
+
|
|
5
|
+
// src/build/upload.ts
|
|
6
|
+
var DEFAULT_SERVER_DIR = ".next/server";
|
|
7
|
+
var DEFAULT_CONCURRENCY = 6;
|
|
8
|
+
var DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
|
|
9
|
+
var ENDPOINT_PATH = "/api/sourcemaps/upload";
|
|
10
|
+
function resolveRelease(explicit) {
|
|
11
|
+
if (explicit !== void 0) return explicit;
|
|
12
|
+
const fromEnv = process.env.BUGSTACK_RELEASE || process.env.RENDER_GIT_COMMIT || process.env.VERCEL_GIT_COMMIT_SHA || process.env.GITHUB_SHA;
|
|
13
|
+
if (fromEnv) return fromEnv;
|
|
14
|
+
try {
|
|
15
|
+
return execSync("git rev-parse HEAD", { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
|
|
16
|
+
} catch {
|
|
17
|
+
return null;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function resolveEndpoint(explicit) {
|
|
21
|
+
const base = explicit || process.env.BUGSTACK_ENDPOINT || (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);
|
|
22
|
+
if (!base) return null;
|
|
23
|
+
const normalised = base.replace(/\/+$/, "").replace(/\/api\/capture$/, "").replace(/\/capture$/, "");
|
|
24
|
+
return normalised + ENDPOINT_PATH;
|
|
25
|
+
}
|
|
26
|
+
async function walk(dir) {
|
|
27
|
+
let entries;
|
|
28
|
+
try {
|
|
29
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if (err.code === "ENOENT") return [];
|
|
32
|
+
throw err;
|
|
33
|
+
}
|
|
34
|
+
const out = [];
|
|
35
|
+
for (const entry of entries) {
|
|
36
|
+
const path = join(dir, entry.name);
|
|
37
|
+
if (entry.isDirectory()) {
|
|
38
|
+
out.push(...await walk(path));
|
|
39
|
+
} else if (entry.name.endsWith(".map")) {
|
|
40
|
+
out.push(path);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
async function pool(items, workers, fn) {
|
|
46
|
+
const results = new Array(items.length);
|
|
47
|
+
let i = 0;
|
|
48
|
+
const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {
|
|
49
|
+
while (i < items.length) {
|
|
50
|
+
const idx = i++;
|
|
51
|
+
results[idx] = await fn(items[idx]);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
await Promise.all(runners);
|
|
55
|
+
return results;
|
|
56
|
+
}
|
|
57
|
+
function bundleFileFor(mapPath, serverDir) {
|
|
58
|
+
return relative(serverDir, mapPath).replace(/\.map$/, "").split(sep).join("/");
|
|
59
|
+
}
|
|
60
|
+
async function uploadSourceMaps(options = {}) {
|
|
61
|
+
const apiKey = options.apiKey || process.env.BUGSTACK_PROJECT_API_KEY || process.env.BUGSTACK_API_KEY;
|
|
62
|
+
const endpoint = resolveEndpoint(options.endpoint);
|
|
63
|
+
const release = resolveRelease(options.release);
|
|
64
|
+
const serverDir = options.serverDir || DEFAULT_SERVER_DIR;
|
|
65
|
+
const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
|
|
66
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
67
|
+
const log = options.log || ((m) => console.log(m));
|
|
68
|
+
const warn = options.warn || ((m) => console.warn(m));
|
|
69
|
+
if (!apiKey) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly."
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
if (!endpoint) {
|
|
75
|
+
throw new Error(
|
|
76
|
+
"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly."
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
const start = Date.now();
|
|
80
|
+
const mapFiles = await walk(serverDir);
|
|
81
|
+
if (mapFiles.length === 0) {
|
|
82
|
+
log(
|
|
83
|
+
`[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`
|
|
84
|
+
);
|
|
85
|
+
return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };
|
|
86
|
+
}
|
|
87
|
+
log(
|
|
88
|
+
`[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || "none"})...`
|
|
89
|
+
);
|
|
90
|
+
const results = await pool(mapFiles, concurrency, async (mapPath) => {
|
|
91
|
+
const bundleFile = bundleFileFor(mapPath, serverDir);
|
|
92
|
+
const stats = await stat(mapPath);
|
|
93
|
+
if (stats.size > maxBytes) {
|
|
94
|
+
return {
|
|
95
|
+
ok: false,
|
|
96
|
+
bundleFile,
|
|
97
|
+
bytes: 0,
|
|
98
|
+
skipped: true,
|
|
99
|
+
error: `Skipped \u2014 ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const mapJson = await readFile(mapPath, "utf8");
|
|
103
|
+
try {
|
|
104
|
+
const res = await fetch(endpoint, {
|
|
105
|
+
method: "POST",
|
|
106
|
+
headers: {
|
|
107
|
+
"Content-Type": "application/json",
|
|
108
|
+
"X-BugStack-API-Key": apiKey
|
|
109
|
+
},
|
|
110
|
+
body: JSON.stringify({ bundleFile, mapJson, release })
|
|
111
|
+
});
|
|
112
|
+
if (!res.ok) {
|
|
113
|
+
const text = await res.text().catch(() => "");
|
|
114
|
+
return {
|
|
115
|
+
ok: false,
|
|
116
|
+
bundleFile,
|
|
117
|
+
bytes: 0,
|
|
118
|
+
skipped: false,
|
|
119
|
+
error: `HTTP ${res.status} ${text.slice(0, 200)}`
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
return { ok: true, bundleFile, bytes: stats.size, skipped: false };
|
|
123
|
+
} catch (err) {
|
|
124
|
+
return {
|
|
125
|
+
ok: false,
|
|
126
|
+
bundleFile,
|
|
127
|
+
bytes: 0,
|
|
128
|
+
skipped: false,
|
|
129
|
+
error: err instanceof Error ? err.message : String(err)
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
const uploaded = results.filter((r) => r.ok).length;
|
|
134
|
+
const skipped = results.filter((r) => !r.ok && r.skipped).length;
|
|
135
|
+
const failed = results.length - uploaded - skipped;
|
|
136
|
+
const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);
|
|
137
|
+
const failures = results.filter((r) => !r.ok && !r.skipped).map((r) => ({ bundleFile: r.bundleFile, error: r.error }));
|
|
138
|
+
const elapsedMs = Date.now() - start;
|
|
139
|
+
log(
|
|
140
|
+
`[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(
|
|
141
|
+
1
|
|
142
|
+
)}MB) in ${(elapsedMs / 1e3).toFixed(1)}s.`
|
|
143
|
+
);
|
|
144
|
+
if (skipped > 0) {
|
|
145
|
+
warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);
|
|
146
|
+
}
|
|
147
|
+
if (failures.length > 0) {
|
|
148
|
+
warn(`[bugstack] ${failures.length} upload(s) failed:`);
|
|
149
|
+
for (const f of failures.slice(0, 10)) {
|
|
150
|
+
warn(` - ${f.bundleFile}: ${f.error}`);
|
|
151
|
+
}
|
|
152
|
+
if (failures.length > 10) {
|
|
153
|
+
warn(` \u2026and ${failures.length - 10} more`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export { uploadSourceMaps };
|
|
160
|
+
//# sourceMappingURL=upload.mjs.map
|
|
161
|
+
//# sourceMappingURL=upload.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/build/upload.ts"],"names":[],"mappings":";;;;;AAiFA,IAAM,kBAAA,GAAqB,cAAA;AAC3B,IAAM,mBAAA,GAAsB,CAAA;AAC5B,IAAM,iBAAA,GAAoB,IAAI,IAAA,GAAO,IAAA;AACrC,IAAM,aAAA,GAAgB,wBAAA;AAEtB,SAAS,eAAe,QAAA,EAAyC;AAC/D,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA,MAAM,OAAA,GACJ,OAAA,CAAQ,GAAA,CAAI,gBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,iBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,qBAAA,IACZ,OAAA,CAAQ,GAAA,CAAI,UAAA;AACd,EAAA,IAAI,SAAS,OAAO,OAAA;AACpB,EAAA,IAAI;AACF,IAAA,OAAO,QAAA,CAAS,oBAAA,EAAsB,EAAE,KAAA,EAAO,CAAC,QAAA,EAAU,MAAA,EAAQ,QAAQ,CAAA,EAAG,CAAA,CAC1E,QAAA,GACA,IAAA,EAAK;AAAA,EACV,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEA,SAAS,gBAAgB,QAAA,EAAkC;AACzD,EAAA,MAAM,IAAA,GACJ,QAAA,IACA,OAAA,CAAQ,GAAA,CAAI,iBAAA,KACX,QAAQ,GAAA,CAAI,iBAAA,GAAoB,OAAA,CAAQ,GAAA,CAAI,iBAAA,GAAoB,IAAA,CAAA;AACnE,EAAA,IAAI,CAAC,MAAM,OAAO,IAAA;AAGlB,E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AAoB,CAAA;AACtD,IAAA,KAAA,MAAW,CAAA,IAAK,QAAA,CAAS,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,EAAG;AACrC,MAAA,IAAA,CAAK,OAAO,CAAA,CAAE,UAAU,CAAA,EAAA,EAAK,CAAA,CAAE,KAAK,CAAA,CAAE,CAAA;AAAA,IACxC;AACA,IAAA,IAAI,QAAA,CAAS,SAAS,EAAA,EAAI;AACxB,MAAA,IAAA,CAAK,CAAA,YAAA,EAAU,QAAA,CAAS,MAAA,GAAS,EAAE,CAAA,KAAA,CAAO,CAAA;AAAA,IAC5C;AAAA,EACF;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,OAAA,EAAS,MAAA,EAAQ,UAAA,EAAY,WAAW,QAAA,EAAS;AACtE","file":"upload.mjs","sourcesContent":["/**\r\n * Build-time source map uploader.\r\n *\r\n * Walks a directory of compiled output looking for `.map` files and POSTs\r\n * each one to the bugstack source-map ingest endpoint. The companion\r\n * `bugstack-sdk/next-config` wrapper enables emission of these maps for\r\n * Next.js server bundles; once uploaded, the orchestrator can resolve\r\n * production stack frames like \".next/server/chunks/8393.js:1:8734\" back\r\n * to source-file positions (\"app/api/orders/route.ts:42:5\") and actually\r\n * generate fixes for bundled errors.\r\n *\r\n * This module is import-safe in any Node 18+ environment. It uses no\r\n * runtime dependencies — `node:fs/promises` + global `fetch`.\r\n */\r\n\r\nimport { readdir, readFile, stat } from \"node:fs/promises\";\r\nimport { join, relative, sep } from \"node:path\";\r\nimport { execSync } from \"node:child_process\";\r\n\r\nexport interface UploadSourceMapsOptions {\r\n /**\r\n * Project SDK key. Required. Reads BUGSTACK_PROJECT_API_KEY or\r\n * BUGSTACK_API_KEY when not supplied explicitly.\r\n */\r\n apiKey?: string;\r\n\r\n /**\r\n * Base URL of the bugstack ingest service. Reads BUGSTACK_ENDPOINT or\r\n * derives from ERROR_SERVICE_URL when not supplied. The uploader appends\r\n * `/api/sourcemaps/upload` to whatever base it gets.\r\n */\r\n endpoint?: string;\r\n\r\n /**\r\n * Release identifier (typically a commit SHA). Lets multiple deploys\r\n * coexist in the source-map table so old errors still resolve against\r\n * old maps. Auto-detected in this order:\r\n * 1. BUGSTACK_RELEASE\r\n * 2. RENDER_GIT_COMMIT\r\n * 3. VERCEL_GIT_COMMIT_SHA\r\n * 4. GITHUB_SHA\r\n * 5. `git rev-parse HEAD` (when a git checkout is present)\r\n */\r\n release?: string | null;\r\n\r\n /**\r\n * Directory to walk for `.map` files. Defaults to `.next/server`.\r\n * Override for non-Next projects (e.g. `dist` for tsc, `build` for CRA).\r\n */\r\n serverDir?: string;\r\n\r\n /**\r\n * Max concurrent uploads. Higher means faster builds, more pressure on\r\n * the ingest endpoint. Default 6 — tuned for Render's typical bandwidth.\r\n */\r\n concurrency?: number;\r\n\r\n /**\r\n * Per-file size cap in bytes. Maps larger than this are skipped with a\r\n * warning rather than failing. Default 8 MiB — covers typical\r\n * `.next/server/chunks/*.js.map` outputs comfortably.\r\n */\r\n maxBytes?: number;\r\n\r\n /**\r\n * Logger. Defaults to console. Pass a no-op logger to silence the\r\n * \"[bugstack] …\" lines in scripted environments.\r\n */\r\n log?: (message: string) => void;\r\n warn?: (message: string) => void;\r\n}\r\n\r\nexport interface UploadResult {\r\n uploaded: number;\r\n skipped: number;\r\n failed: number;\r\n totalBytes: number;\r\n elapsedMs: number;\r\n failures: Array<{ bundleFile: string; error: string }>;\r\n}\r\n\r\nconst DEFAULT_SERVER_DIR = \".next/server\";\r\nconst DEFAULT_CONCURRENCY = 6;\r\nconst DEFAULT_MAX_BYTES = 8 * 1024 * 1024;\r\nconst ENDPOINT_PATH = \"/api/sourcemaps/upload\";\r\n\r\nfunction resolveRelease(explicit?: string | null): string | null {\r\n if (explicit !== undefined) return explicit;\r\n const fromEnv =\r\n process.env.BUGSTACK_RELEASE ||\r\n process.env.RENDER_GIT_COMMIT ||\r\n process.env.VERCEL_GIT_COMMIT_SHA ||\r\n process.env.GITHUB_SHA;\r\n if (fromEnv) return fromEnv;\r\n try {\r\n return execSync(\"git rev-parse HEAD\", { stdio: [\"ignore\", \"pipe\", \"ignore\"] })\r\n .toString()\r\n .trim();\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nfunction resolveEndpoint(explicit?: string): string | null {\r\n const base =\r\n explicit ||\r\n process.env.BUGSTACK_ENDPOINT ||\r\n (process.env.ERROR_SERVICE_URL ? process.env.ERROR_SERVICE_URL : null);\r\n if (!base) return null;\r\n // Strip trailing slashes + any trailing /api/capture or /capture so the\r\n // same env var that points the SDK at ingestion also works for sourcemaps.\r\n const normalised = base\r\n .replace(/\\/+$/, \"\")\r\n .replace(/\\/api\\/capture$/, \"\")\r\n .replace(/\\/capture$/, \"\");\r\n return normalised + ENDPOINT_PATH;\r\n}\r\n\r\nasync function walk(dir: string): Promise<string[]> {\r\n let entries;\r\n try {\r\n entries = await readdir(dir, { withFileTypes: true });\r\n } catch (err) {\r\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\r\n throw err;\r\n }\r\n const out: string[] = [];\r\n for (const entry of entries) {\r\n const path = join(dir, entry.name);\r\n if (entry.isDirectory()) {\r\n out.push(...(await walk(path)));\r\n } else if (entry.name.endsWith(\".map\")) {\r\n out.push(path);\r\n }\r\n }\r\n return out;\r\n}\r\n\r\nasync function pool<T, R>(\r\n items: T[],\r\n workers: number,\r\n fn: (item: T) => Promise<R>,\r\n): Promise<R[]> {\r\n const results: R[] = new Array(items.length);\r\n let i = 0;\r\n const runners = Array.from({ length: Math.min(workers, items.length) }, async () => {\r\n while (i < items.length) {\r\n const idx = i++;\r\n results[idx] = await fn(items[idx]);\r\n }\r\n });\r\n await Promise.all(runners);\r\n return results;\r\n}\r\n\r\nfunction bundleFileFor(mapPath: string, serverDir: string): string {\r\n // Strip the serverDir prefix and the .map suffix; normalise Windows\r\n // backslashes so the bundleFile key stored on the server is portable\r\n // regardless of where the build ran.\r\n return relative(serverDir, mapPath)\r\n .replace(/\\.map$/, \"\")\r\n .split(sep)\r\n .join(\"/\");\r\n}\r\n\r\n/**\r\n * Upload every `.map` file under `serverDir` to the bugstack source-map\r\n * endpoint. Tolerant: never throws on individual file failures, returns\r\n * a summary the caller can decide what to do with.\r\n *\r\n * Throws only on hard configuration errors (no API key, no resolvable\r\n * endpoint, serverDir totally missing).\r\n */\r\nexport async function uploadSourceMaps(\r\n options: UploadSourceMapsOptions = {},\r\n): Promise<UploadResult> {\r\n const apiKey =\r\n options.apiKey ||\r\n process.env.BUGSTACK_PROJECT_API_KEY ||\r\n process.env.BUGSTACK_API_KEY;\r\n const endpoint = resolveEndpoint(options.endpoint);\r\n const release = resolveRelease(options.release);\r\n const serverDir = options.serverDir || DEFAULT_SERVER_DIR;\r\n const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);\r\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;\r\n const log = options.log || ((m: string) => console.log(m));\r\n const warn = options.warn || ((m: string) => console.warn(m));\r\n\r\n if (!apiKey) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing project API key. Set BUGSTACK_PROJECT_API_KEY or pass {apiKey} explicitly.\",\r\n );\r\n }\r\n if (!endpoint) {\r\n throw new Error(\r\n \"uploadSourceMaps: missing endpoint. Set BUGSTACK_ENDPOINT (or ERROR_SERVICE_URL) or pass {endpoint} explicitly.\",\r\n );\r\n }\r\n\r\n const start = Date.now();\r\n const mapFiles = await walk(serverDir);\r\n\r\n if (mapFiles.length === 0) {\r\n log(\r\n `[bugstack] No .map files found under ${serverDir}. Make sure withBugstack() is wrapping your next.config or that source-map emission is otherwise enabled.`,\r\n );\r\n return { uploaded: 0, skipped: 0, failed: 0, totalBytes: 0, elapsedMs: 0, failures: [] };\r\n }\r\n\r\n log(\r\n `[bugstack] Uploading ${mapFiles.length} source map(s) to ${endpoint} (release=${release || \"none\"})...`,\r\n );\r\n\r\n const results = await pool(mapFiles, concurrency, async (mapPath) => {\r\n const bundleFile = bundleFileFor(mapPath, serverDir);\r\n const stats = await stat(mapPath);\r\n if (stats.size > maxBytes) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: true,\r\n error: `Skipped — ${(stats.size / 1024 / 1024).toFixed(1)}MB exceeds maxBytes`,\r\n };\r\n }\r\n const mapJson = await readFile(mapPath, \"utf8\");\r\n try {\r\n const res = await fetch(endpoint, {\r\n method: \"POST\",\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n \"X-BugStack-API-Key\": apiKey,\r\n },\r\n body: JSON.stringify({ bundleFile, mapJson, release }),\r\n });\r\n if (!res.ok) {\r\n const text = await res.text().catch(() => \"\");\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: `HTTP ${res.status} ${text.slice(0, 200)}`,\r\n };\r\n }\r\n return { ok: true as const, bundleFile, bytes: stats.size, skipped: false };\r\n } catch (err) {\r\n return {\r\n ok: false as const,\r\n bundleFile,\r\n bytes: 0,\r\n skipped: false,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n });\r\n\r\n const uploaded = results.filter((r) => r.ok).length;\r\n const skipped = results.filter((r) => !r.ok && r.skipped).length;\r\n const failed = results.length - uploaded - skipped;\r\n const totalBytes = results.reduce((n, r) => n + (r.ok ? r.bytes : 0), 0);\r\n const failures = results\r\n .filter((r): r is Extract<typeof r, { ok: false }> => !r.ok && !r.skipped)\r\n .map((r) => ({ bundleFile: r.bundleFile, error: r.error }));\r\n const elapsedMs = Date.now() - start;\r\n\r\n log(\r\n `[bugstack] Uploaded ${uploaded}/${results.length} maps (${(totalBytes / 1024 / 1024).toFixed(\r\n 1,\r\n )}MB) in ${(elapsedMs / 1000).toFixed(1)}s.`,\r\n );\r\n if (skipped > 0) {\r\n warn(`[bugstack] Skipped ${skipped} map(s) over the size cap.`);\r\n }\r\n if (failures.length > 0) {\r\n warn(`[bugstack] ${failures.length} upload(s) failed:`);\r\n for (const f of failures.slice(0, 10)) {\r\n warn(` - ${f.bundleFile}: ${f.error}`);\r\n }\r\n if (failures.length > 10) {\r\n warn(` …and ${failures.length - 10} more`);\r\n }\r\n }\r\n\r\n return { uploaded, skipped, failed, totalBytes, elapsedMs, failures };\r\n}\r\n"]}
|
|
@@ -92,6 +92,28 @@ interface ErrorCaptureConfig {
|
|
|
92
92
|
* Can be used to modify or enrich error data
|
|
93
93
|
*/
|
|
94
94
|
beforeSend?: (error: CapturedError) => CapturedError | null;
|
|
95
|
+
/**
|
|
96
|
+
* Drop browser chunk-load errors (ChunkLoadError, "Loading chunk N failed",
|
|
97
|
+
* "Failed to fetch dynamically imported module") **entirely**, including
|
|
98
|
+
* from the lightweight telemetry counter.
|
|
99
|
+
*
|
|
100
|
+
* By default we don't drop — we route them to the chunk-errors telemetry
|
|
101
|
+
* endpoint instead of the main fix pipeline. That keeps them out of the
|
|
102
|
+
* orchestrator (where they'd waste LLM cycles on unfixable bundle URLs)
|
|
103
|
+
* while still surfacing CDN/build outages on the dashboard via spike
|
|
104
|
+
* detection.
|
|
105
|
+
*
|
|
106
|
+
* Set to `true` to disable the telemetry path as well.
|
|
107
|
+
* @default false
|
|
108
|
+
*/
|
|
109
|
+
dropChunkErrors?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Endpoint to receive lightweight chunk-error telemetry. Defaults to
|
|
112
|
+
* deriving from `endpoint`: `/api/capture` → `/api/chunk-errors`,
|
|
113
|
+
* or `/capture` → `/chunk-errors`. Override only if your error service
|
|
114
|
+
* lives behind a different host/path for telemetry vs. main capture.
|
|
115
|
+
*/
|
|
116
|
+
chunkErrorsEndpoint?: string;
|
|
95
117
|
}
|
|
96
118
|
/**
|
|
97
119
|
* Resolved configuration with all defaults applied
|
|
@@ -114,6 +136,8 @@ interface ResolvedConfig {
|
|
|
114
136
|
debug: boolean;
|
|
115
137
|
shouldCapture?: (error: Error, request: NextRequest) => boolean;
|
|
116
138
|
beforeSend?: (error: CapturedError) => CapturedError | null;
|
|
139
|
+
dropChunkErrors: boolean;
|
|
140
|
+
chunkErrorsEndpoint: string;
|
|
117
141
|
}
|
|
118
142
|
/**
|
|
119
143
|
* Captured error data sent to the error service
|
|
@@ -589,6 +613,12 @@ declare class ErrorCaptureClient {
|
|
|
589
613
|
* @returns Promise that resolves to true on success
|
|
590
614
|
*/
|
|
591
615
|
private sendErrorToService;
|
|
616
|
+
/**
|
|
617
|
+
* Forward a chunk-load error to the lightweight telemetry endpoint.
|
|
618
|
+
* Fire-and-forget — never throws, never retries, never logs loud. The
|
|
619
|
+
* point is to count these without spending real money on them.
|
|
620
|
+
*/
|
|
621
|
+
private sendChunkErrorTelemetry;
|
|
592
622
|
/**
|
|
593
623
|
* Get the resolved configuration
|
|
594
624
|
*/
|
|
@@ -618,5 +648,16 @@ declare class ErrorCaptureClient {
|
|
|
618
648
|
private logError;
|
|
619
649
|
}
|
|
620
650
|
declare const BugStackClient: typeof ErrorCaptureClient;
|
|
651
|
+
/**
|
|
652
|
+
* Recognise the family of "browser failed to load a code-split chunk" errors.
|
|
653
|
+
* Webpack and Vite emit slightly different messages; the regex covers both.
|
|
654
|
+
*
|
|
655
|
+
* Exported (via re-export from index.ts) so callers can reuse the same check
|
|
656
|
+
* in their own error boundaries when deciding whether to soft-reload.
|
|
657
|
+
*/
|
|
658
|
+
declare function isChunkLoadError(error: {
|
|
659
|
+
name?: string;
|
|
660
|
+
message?: string;
|
|
661
|
+
}): boolean;
|
|
621
662
|
|
|
622
|
-
export { BugStackClient as B, type CapturedError as C,
|
|
663
|
+
export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, type RouteOptions as b, type BugStackConfig as c, ErrorDeduplicator as d, type ErrorReportPayload as e, type ResolvedConfig as f, RetryQueue as g, type SourceContext as h, isChunkLoadError as i };
|
|
@@ -92,6 +92,28 @@ interface ErrorCaptureConfig {
|
|
|
92
92
|
* Can be used to modify or enrich error data
|
|
93
93
|
*/
|
|
94
94
|
beforeSend?: (error: CapturedError) => CapturedError | null;
|
|
95
|
+
/**
|
|
96
|
+
* Drop browser chunk-load errors (ChunkLoadError, "Loading chunk N failed",
|
|
97
|
+
* "Failed to fetch dynamically imported module") **entirely**, including
|
|
98
|
+
* from the lightweight telemetry counter.
|
|
99
|
+
*
|
|
100
|
+
* By default we don't drop — we route them to the chunk-errors telemetry
|
|
101
|
+
* endpoint instead of the main fix pipeline. That keeps them out of the
|
|
102
|
+
* orchestrator (where they'd waste LLM cycles on unfixable bundle URLs)
|
|
103
|
+
* while still surfacing CDN/build outages on the dashboard via spike
|
|
104
|
+
* detection.
|
|
105
|
+
*
|
|
106
|
+
* Set to `true` to disable the telemetry path as well.
|
|
107
|
+
* @default false
|
|
108
|
+
*/
|
|
109
|
+
dropChunkErrors?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Endpoint to receive lightweight chunk-error telemetry. Defaults to
|
|
112
|
+
* deriving from `endpoint`: `/api/capture` → `/api/chunk-errors`,
|
|
113
|
+
* or `/capture` → `/chunk-errors`. Override only if your error service
|
|
114
|
+
* lives behind a different host/path for telemetry vs. main capture.
|
|
115
|
+
*/
|
|
116
|
+
chunkErrorsEndpoint?: string;
|
|
95
117
|
}
|
|
96
118
|
/**
|
|
97
119
|
* Resolved configuration with all defaults applied
|
|
@@ -114,6 +136,8 @@ interface ResolvedConfig {
|
|
|
114
136
|
debug: boolean;
|
|
115
137
|
shouldCapture?: (error: Error, request: NextRequest) => boolean;
|
|
116
138
|
beforeSend?: (error: CapturedError) => CapturedError | null;
|
|
139
|
+
dropChunkErrors: boolean;
|
|
140
|
+
chunkErrorsEndpoint: string;
|
|
117
141
|
}
|
|
118
142
|
/**
|
|
119
143
|
* Captured error data sent to the error service
|
|
@@ -589,6 +613,12 @@ declare class ErrorCaptureClient {
|
|
|
589
613
|
* @returns Promise that resolves to true on success
|
|
590
614
|
*/
|
|
591
615
|
private sendErrorToService;
|
|
616
|
+
/**
|
|
617
|
+
* Forward a chunk-load error to the lightweight telemetry endpoint.
|
|
618
|
+
* Fire-and-forget — never throws, never retries, never logs loud. The
|
|
619
|
+
* point is to count these without spending real money on them.
|
|
620
|
+
*/
|
|
621
|
+
private sendChunkErrorTelemetry;
|
|
592
622
|
/**
|
|
593
623
|
* Get the resolved configuration
|
|
594
624
|
*/
|
|
@@ -618,5 +648,16 @@ declare class ErrorCaptureClient {
|
|
|
618
648
|
private logError;
|
|
619
649
|
}
|
|
620
650
|
declare const BugStackClient: typeof ErrorCaptureClient;
|
|
651
|
+
/**
|
|
652
|
+
* Recognise the family of "browser failed to load a code-split chunk" errors.
|
|
653
|
+
* Webpack and Vite emit slightly different messages; the regex covers both.
|
|
654
|
+
*
|
|
655
|
+
* Exported (via re-export from index.ts) so callers can reuse the same check
|
|
656
|
+
* in their own error boundaries when deciding whether to soft-reload.
|
|
657
|
+
*/
|
|
658
|
+
declare function isChunkLoadError(error: {
|
|
659
|
+
name?: string;
|
|
660
|
+
message?: string;
|
|
661
|
+
}): boolean;
|
|
621
662
|
|
|
622
|
-
export { BugStackClient as B, type CapturedError as C,
|
|
663
|
+
export { BugStackClient as B, type CapturedError as C, type ErrorCaptureConfig as E, type NextRouteHandler as N, type RouteContext as R, type StackFrame as S, ErrorCaptureClient as a, type RouteOptions as b, type BugStackConfig as c, ErrorDeduplicator as d, type ErrorReportPayload as e, type ResolvedConfig as f, RetryQueue as g, type SourceContext as h, isChunkLoadError as i };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CapturedError,
|
|
2
|
-
export { B as BugStackClient,
|
|
1
|
+
import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-DoqE7sNh.mjs';
|
|
2
|
+
export { B as BugStackClient, c as BugStackConfig, E as ErrorCaptureConfig, d as ErrorDeduplicator, e as ErrorReportPayload, N as NextRouteHandler, f as ResolvedConfig, g as RetryQueue, R as RouteContext, b as RouteOptions, h as SourceContext, i as isChunkLoadError } from './client-DoqE7sNh.mjs';
|
|
3
3
|
export { withBugStack, withErrorCapture } from './adapters/nextjs/index.mjs';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CapturedError,
|
|
2
|
-
export { B as BugStackClient,
|
|
1
|
+
import { C as CapturedError, a as ErrorCaptureClient, S as StackFrame } from './client-DoqE7sNh.js';
|
|
2
|
+
export { B as BugStackClient, c as BugStackConfig, E as ErrorCaptureConfig, d as ErrorDeduplicator, e as ErrorReportPayload, N as NextRouteHandler, f as ResolvedConfig, g as RetryQueue, R as RouteContext, b as RouteOptions, h as SourceContext, i as isChunkLoadError } from './client-DoqE7sNh.js';
|
|
3
3
|
export { withBugStack, withErrorCapture } from './adapters/nextjs/index.js';
|
|
4
4
|
import 'next/server';
|
|
5
5
|
|