@glasstrace/sdk 0.14.2 → 0.16.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.
Files changed (84) hide show
  1. package/README.md +84 -1
  2. package/dist/adapters/drizzle.js +2 -5
  3. package/dist/adapters/drizzle.js.map +1 -1
  4. package/dist/{chunk-PD2SKFQQ.js → chunk-55FBXXER.js} +4 -8
  5. package/dist/{chunk-PD2SKFQQ.js.map → chunk-55FBXXER.js.map} +1 -1
  6. package/dist/chunk-5C2TJFLB.js +851 -0
  7. package/dist/chunk-5C2TJFLB.js.map +1 -0
  8. package/dist/{chunk-YMEXDDTA.js → chunk-7JBKXSBU.js} +3 -99
  9. package/dist/chunk-7JBKXSBU.js.map +1 -0
  10. package/dist/{chunk-2LDBR3F3.js → chunk-BANTDXUT.js} +15 -74
  11. package/dist/chunk-BANTDXUT.js.map +1 -0
  12. package/dist/{chunk-WV3NIPWJ.js → chunk-CTJI2YKA.js} +23 -288
  13. package/dist/chunk-CTJI2YKA.js.map +1 -0
  14. package/dist/{chunk-WK7MPK2T.js → chunk-DQ25VOKK.js} +1 -89
  15. package/dist/chunk-DQ25VOKK.js.map +1 -0
  16. package/dist/{chunk-BL3YDC6V.js → chunk-DXRZKKSO.js} +1 -6
  17. package/dist/{chunk-BL3YDC6V.js.map → chunk-DXRZKKSO.js.map} +1 -1
  18. package/dist/{chunk-BGZ7J74D.js → chunk-NSBPE2FW.js} +2 -16
  19. package/dist/chunk-O63DJKIJ.js +460 -0
  20. package/dist/chunk-O63DJKIJ.js.map +1 -0
  21. package/dist/{chunk-ECEN724Y.js → chunk-TM5NKZTO.js} +4 -8
  22. package/dist/{chunk-ECEN724Y.js.map → chunk-TM5NKZTO.js.map} +1 -1
  23. package/dist/chunk-VUZCLMIX.js +57 -0
  24. package/dist/chunk-VUZCLMIX.js.map +1 -0
  25. package/dist/{chunk-OSXIUKD5.js → chunk-WZXVS2EO.js} +1 -6
  26. package/dist/{chunk-OSXIUKD5.js.map → chunk-WZXVS2EO.js.map} +1 -1
  27. package/dist/{chunk-ARAOZCZT.js → chunk-XNDHQN4S.js} +122 -24
  28. package/dist/chunk-XNDHQN4S.js.map +1 -0
  29. package/dist/cli/init.cjs +1110 -255
  30. package/dist/cli/init.cjs.map +1 -1
  31. package/dist/cli/init.d.cts +86 -1
  32. package/dist/cli/init.d.ts +86 -1
  33. package/dist/cli/init.js +277 -66
  34. package/dist/cli/init.js.map +1 -1
  35. package/dist/cli/mcp-add.cjs +16 -16
  36. package/dist/cli/mcp-add.cjs.map +1 -1
  37. package/dist/cli/mcp-add.js +12 -13
  38. package/dist/cli/mcp-add.js.map +1 -1
  39. package/dist/cli/status.cjs +2 -2
  40. package/dist/cli/status.js +4 -7
  41. package/dist/cli/status.js.map +1 -1
  42. package/dist/cli/uninit.cjs +138 -20
  43. package/dist/cli/uninit.cjs.map +1 -1
  44. package/dist/cli/uninit.d.cts +38 -8
  45. package/dist/cli/uninit.d.ts +38 -8
  46. package/dist/cli/uninit.js +8 -5
  47. package/dist/cli/validate.cjs +135 -0
  48. package/dist/cli/validate.cjs.map +1 -0
  49. package/dist/cli/validate.d.cts +60 -0
  50. package/dist/cli/validate.d.ts +60 -0
  51. package/dist/cli/validate.js +100 -0
  52. package/dist/cli/validate.js.map +1 -0
  53. package/dist/{esm-MDK7CZID.js → esm-KBPHCVB4.js} +3 -3
  54. package/dist/{getMachineId-bsd-4NIRBWME.js → getMachineId-bsd-345PYXFX.js} +4 -7
  55. package/dist/{getMachineId-bsd-4NIRBWME.js.map → getMachineId-bsd-345PYXFX.js.map} +1 -1
  56. package/dist/{getMachineId-darwin-2XNOCCJQ.js → getMachineId-darwin-5L2D25AD.js} +4 -7
  57. package/dist/{getMachineId-darwin-2XNOCCJQ.js.map → getMachineId-darwin-5L2D25AD.js.map} +1 -1
  58. package/dist/{getMachineId-linux-V6YSQEY7.js → getMachineId-linux-KJR4P5HN.js} +3 -6
  59. package/dist/{getMachineId-linux-V6YSQEY7.js.map → getMachineId-linux-KJR4P5HN.js.map} +1 -1
  60. package/dist/{getMachineId-unsupported-4FKBJNVO.js → getMachineId-unsupported-NDNXDYDY.js} +3 -6
  61. package/dist/{getMachineId-unsupported-4FKBJNVO.js.map → getMachineId-unsupported-NDNXDYDY.js.map} +1 -1
  62. package/dist/{getMachineId-win-WLRZBKVG.js → getMachineId-win-T7PJNJXG.js} +4 -7
  63. package/dist/{getMachineId-win-WLRZBKVG.js.map → getMachineId-win-T7PJNJXG.js.map} +1 -1
  64. package/dist/index.cjs +519 -494
  65. package/dist/index.cjs.map +1 -1
  66. package/dist/index.d.cts +47 -6
  67. package/dist/index.d.ts +47 -6
  68. package/dist/index.js +250 -719
  69. package/dist/index.js.map +1 -1
  70. package/dist/{monorepo-YILKGQXQ.js → monorepo-N5Z63XP7.js} +4 -4
  71. package/dist/{source-map-uploader-3GWUQDTS.js → source-map-uploader-MUZPI2S5.js} +5 -4
  72. package/dist/source-map-uploader-MUZPI2S5.js.map +1 -0
  73. package/package.json +6 -4
  74. package/dist/chunk-2LDBR3F3.js.map +0 -1
  75. package/dist/chunk-ARAOZCZT.js.map +0 -1
  76. package/dist/chunk-BGZ7J74D.js.map +0 -1
  77. package/dist/chunk-UPS5BGER.js +0 -182
  78. package/dist/chunk-UPS5BGER.js.map +0 -1
  79. package/dist/chunk-WK7MPK2T.js.map +0 -1
  80. package/dist/chunk-WV3NIPWJ.js.map +0 -1
  81. package/dist/chunk-YMEXDDTA.js.map +0 -1
  82. /package/dist/{esm-MDK7CZID.js.map → chunk-NSBPE2FW.js.map} +0 -0
  83. /package/dist/{monorepo-YILKGQXQ.js.map → esm-KBPHCVB4.js.map} +0 -0
  84. /package/dist/{source-map-uploader-3GWUQDTS.js.map → monorepo-N5Z63XP7.js.map} +0 -0
@@ -1,76 +1,21 @@
1
+ import {
2
+ isProductionDisabled,
3
+ resolveConfig
4
+ } from "./chunk-VUZCLMIX.js";
1
5
  import {
2
6
  PresignedUploadResponseSchema,
3
7
  SourceMapManifestResponseSchema,
4
8
  SourceMapUploadResponseSchema
5
- } from "./chunk-YMEXDDTA.js";
9
+ } from "./chunk-7JBKXSBU.js";
6
10
  import {
7
- __require,
8
- init_esm_shims
9
- } from "./chunk-BGZ7J74D.js";
11
+ __require
12
+ } from "./chunk-NSBPE2FW.js";
10
13
 
11
14
  // src/source-map-uploader.ts
12
- init_esm_shims();
13
- import * as fs from "fs/promises";
14
- import * as path from "path";
15
- import * as crypto from "crypto";
16
- import { execFileSync } from "child_process";
17
-
18
- // src/console-capture.ts
19
- init_esm_shims();
20
-
21
- // src/nudge/error-nudge.ts
22
- init_esm_shims();
23
-
24
- // src/env-detection.ts
25
- init_esm_shims();
26
- var DEFAULT_ENDPOINT = "https://api.glasstrace.dev";
27
- function readEnvVars() {
28
- return {
29
- GLASSTRACE_API_KEY: process.env.GLASSTRACE_API_KEY?.trim() || void 0,
30
- GLASSTRACE_FORCE_ENABLE: process.env.GLASSTRACE_FORCE_ENABLE,
31
- GLASSTRACE_ENV: process.env.GLASSTRACE_ENV,
32
- GLASSTRACE_COVERAGE_MAP: process.env.GLASSTRACE_COVERAGE_MAP,
33
- NODE_ENV: process.env.NODE_ENV,
34
- VERCEL_ENV: process.env.VERCEL_ENV
35
- };
36
- }
37
- function resolveConfig(options) {
38
- const env = readEnvVars();
39
- return {
40
- apiKey: options?.apiKey ?? env.GLASSTRACE_API_KEY,
41
- endpoint: options?.endpoint ?? DEFAULT_ENDPOINT,
42
- forceEnable: options?.forceEnable ?? env.GLASSTRACE_FORCE_ENABLE === "true",
43
- verbose: options?.verbose ?? false,
44
- environment: env.GLASSTRACE_ENV,
45
- coverageMapEnabled: env.GLASSTRACE_COVERAGE_MAP === "true",
46
- nodeEnv: env.NODE_ENV,
47
- vercelEnv: env.VERCEL_ENV
48
- };
49
- }
50
- function isProductionDisabled(config) {
51
- if (config.forceEnable) {
52
- return false;
53
- }
54
- if (config.nodeEnv === "production") {
55
- return true;
56
- }
57
- if (config.vercelEnv === "production") {
58
- return true;
59
- }
60
- return false;
61
- }
62
- function isAnonymousMode(config) {
63
- if (config.apiKey === void 0) {
64
- return true;
65
- }
66
- if (config.apiKey.trim() === "") {
67
- return true;
68
- }
69
- if (config.apiKey.startsWith("gt_anon_")) {
70
- return true;
71
- }
72
- return false;
73
- }
15
+ import * as fs from "node:fs/promises";
16
+ import * as path from "node:path";
17
+ import * as crypto from "node:crypto";
18
+ import { execFileSync } from "node:child_process";
74
19
 
75
20
  // src/nudge/error-nudge.ts
76
21
  var hasFired = false;
@@ -79,8 +24,8 @@ function sanitize(input) {
79
24
  }
80
25
  function markerFileExists() {
81
26
  try {
82
- const fs2 = __require("fs");
83
- const path2 = __require("path");
27
+ const fs2 = __require("node:fs");
28
+ const path2 = __require("node:path");
84
29
  const markerPath = path2.join(process.cwd(), ".glasstrace", "mcp-connected");
85
30
  return fs2.existsSync(markerPath);
86
31
  } catch {
@@ -133,7 +78,7 @@ function isSdkMessage(args) {
133
78
  async function installConsoleCapture() {
134
79
  if (installed) return;
135
80
  try {
136
- otelApi = await import("./esm-MDK7CZID.js");
81
+ otelApi = await import("./esm-KBPHCVB4.js");
137
82
  } catch {
138
83
  otelApi = null;
139
84
  }
@@ -486,10 +431,6 @@ async function uploadSourceMapsAuto(apiKey, endpoint, buildHash, maps, options)
486
431
  }
487
432
 
488
433
  export {
489
- readEnvVars,
490
- resolveConfig,
491
- isProductionDisabled,
492
- isAnonymousMode,
493
434
  maybeShowMcpNudge,
494
435
  installConsoleCapture,
495
436
  sdkLog,
@@ -506,4 +447,4 @@ export {
506
447
  uploadSourceMapsPresigned,
507
448
  uploadSourceMapsAuto
508
449
  };
509
- //# sourceMappingURL=chunk-2LDBR3F3.js.map
450
+ //# sourceMappingURL=chunk-BANTDXUT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/source-map-uploader.ts","../src/nudge/error-nudge.ts","../src/console-capture.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport * as path from \"node:path\";\nimport * as crypto from \"node:crypto\";\nimport { execFileSync } from \"node:child_process\";\nimport { sdkLog } from \"./console-capture.js\";\nimport {\n SourceMapUploadResponseSchema,\n type SourceMapUploadResponse,\n PresignedUploadResponseSchema,\n type PresignedUploadResponse,\n SourceMapManifestResponseSchema,\n type SourceMapManifestResponse,\n} from \"@glasstrace/protocol\";\n\nexport interface SourceMapEntry {\n filePath: string;\n content: string;\n}\n\n/**\n * Metadata for a discovered source map file, without its content loaded.\n * Used by the streaming upload flow to defer file reads until upload time.\n */\nexport interface SourceMapFileInfo {\n /** Relative path to the compiled JS file (`.map` extension stripped). */\n filePath: string;\n /** Absolute path on disk for reading the file content on demand. */\n absolutePath: string;\n /** File size in bytes. */\n sizeBytes: number;\n}\n\n/** Threshold (50 MB) above which a single source map triggers a warning. */\nconst LARGE_FILE_WARNING_BYTES = 50 * 1024 * 1024;\n\n/**\n * Recursively discovers all `.map` files in the given build directory.\n * Returns metadata only — file content is NOT read into memory.\n */\nexport async function discoverSourceMapFiles(\n buildDir: string,\n): Promise<SourceMapFileInfo[]> {\n // Resolve to absolute so absolutePath in results is always absolute,\n // even when buildDir is relative (e.g. \".next\").\n const resolvedDir = path.resolve(buildDir);\n const results: SourceMapFileInfo[] = [];\n\n try {\n await walkDirMetadata(resolvedDir, resolvedDir, results);\n } catch {\n // Directory doesn't exist or is unreadable — return empty\n return [];\n }\n\n // Warn about oversized source map files\n for (const file of results) {\n if (file.sizeBytes >= LARGE_FILE_WARNING_BYTES) {\n const sizeMB = (file.sizeBytes / (1024 * 1024)).toFixed(1);\n sdkLog(\n \"warn\",\n `[glasstrace] Large source map detected: ${file.filePath} (${sizeMB}MB). Consider enabling source map compression.`,\n );\n }\n }\n\n return results;\n}\n\nasync function walkDirMetadata(\n baseDir: string,\n currentDir: string,\n results: SourceMapFileInfo[],\n): Promise<void> {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(currentDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n const fullPath = path.join(currentDir, entry.name);\n\n if (entry.isDirectory()) {\n await walkDirMetadata(baseDir, fullPath, results);\n } else if (entry.isFile() && entry.name.endsWith(\".map\")) {\n try {\n const stat = await fs.stat(fullPath);\n const relativePath = path.relative(baseDir, fullPath).replace(/\\\\/g, \"/\");\n // Strip the trailing .map extension so the key matches the compiled\n // JS path that the runtime uses for stack-frame lookups (e.g.\n // \"static/chunks/main.js\" instead of \"static/chunks/main.js.map\").\n const compiledPath = relativePath.replace(/\\.map$/, \"\");\n results.push({\n filePath: compiledPath,\n absolutePath: fullPath,\n sizeBytes: stat.size,\n });\n } catch {\n // Skip unreadable files\n }\n }\n }\n}\n\n/**\n * Reads the content of a single source map file from disk.\n */\nasync function readSourceMapContent(absolutePath: string): Promise<string> {\n return fs.readFile(absolutePath, \"utf-8\");\n}\n\n/**\n * Recursively finds all .map files in the given build directory.\n * Returns relative paths and file contents.\n *\n * @deprecated Prefer {@link discoverSourceMapFiles} to avoid loading all\n * source maps into memory simultaneously.\n */\nexport async function collectSourceMaps(\n buildDir: string,\n): Promise<SourceMapEntry[]> {\n const fileInfos = await discoverSourceMapFiles(buildDir);\n const results: SourceMapEntry[] = [];\n\n for (const info of fileInfos) {\n try {\n const content = await readSourceMapContent(info.absolutePath);\n results.push({ filePath: info.filePath, content });\n } catch {\n // Skip unreadable files — consistent with previous behavior\n }\n }\n\n return results;\n}\n\n/**\n * Computes a build hash for source map uploads.\n *\n * First tries `git rev-parse HEAD` to get the git commit SHA.\n * On failure, falls back to a deterministic content hash:\n * sort source map file paths alphabetically, concatenate each as\n * `{relativePath}\\n{fileLength}\\n{fileContent}`, then SHA-256 the result.\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (streaming, reads on demand).\n */\nexport async function computeBuildHash(\n maps?: SourceMapEntry[] | SourceMapFileInfo[],\n): Promise<string> {\n // Try git first\n try {\n const sha = execFileSync(\"git\", [\"rev-parse\", \"HEAD\"], { encoding: \"utf-8\" }).trim();\n if (sha) {\n return sha;\n }\n } catch {\n // Git not available, fall through to content hash\n }\n\n // Fallback: content-based hash\n const sortedMaps = [...(maps ?? [])].sort((a, b) =>\n a.filePath.localeCompare(b.filePath),\n );\n\n const hash = crypto.createHash(\"sha256\");\n\n for (const m of sortedMaps) {\n let content: string;\n if (\"content\" in m) {\n content = m.content;\n } else {\n try {\n content = await readSourceMapContent(m.absolutePath);\n } catch {\n // Skip unreadable files — consistent with collectSourceMaps behavior\n continue;\n }\n }\n hash.update(`${m.filePath}\\n${content.length}\\n${content}`);\n }\n\n return hash.digest(\"hex\");\n}\n\n/**\n * Uploads source maps to the ingestion API.\n *\n * POSTs to `{endpoint}/v1/source-maps` with the API key, build hash,\n * and file entries. Validates the response against SourceMapUploadResponseSchema.\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (deferred reads). With `SourceMapFileInfo[]`,\n * file content is read at upload time rather than at discovery time.\n * Note: the legacy endpoint sends all files in a single JSON body, so\n * peak memory is similar — the benefit is deferring reads past discovery.\n */\nexport async function uploadSourceMaps(\n apiKey: string,\n endpoint: string,\n buildHash: string,\n maps: SourceMapEntry[] | SourceMapFileInfo[],\n): Promise<SourceMapUploadResponse> {\n // Read files on demand — for SourceMapEntry[], content is already available;\n // for SourceMapFileInfo[], each file is read individually to limit memory.\n // Individual reads are guarded so one transient failure (deleted file,\n // permission change) does not abort the entire upload.\n const files: Array<{ filePath: string; sourceMap: string }> = [];\n for (const m of maps) {\n try {\n const content = \"content\" in m\n ? m.content\n : await readSourceMapContent(m.absolutePath);\n files.push({ filePath: m.filePath, sourceMap: content });\n } catch {\n sdkLog(\"warn\", `[glasstrace] Skipping unreadable source map: ${m.filePath}`);\n }\n }\n\n const body = {\n buildHash,\n files,\n };\n\n const baseUrl = stripTrailingSlashes(endpoint);\n const response = await fetch(`${baseUrl}/v1/source-maps`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n // Consume the response body to release the connection back to the pool.\n // Without this, the underlying TCP socket stays allocated until GC, which\n // causes connection pool exhaustion under sustained error conditions.\n // Wrapped in try-catch so a stream error doesn't mask the HTTP status error.\n try { await response.text(); } catch { /* body drain is best-effort */ }\n throw new Error(\n `Source map upload failed: ${String(response.status)} ${response.statusText}`,\n );\n }\n\n const json: unknown = await response.json();\n return SourceMapUploadResponseSchema.parse(json);\n}\n\n// ---------------------------------------------------------------------------\n// Presigned source map upload (3-phase flow for large builds)\n// ---------------------------------------------------------------------------\n\n/** Builds at or above this byte size route to the presigned upload flow. */\nexport const PRESIGNED_THRESHOLD_BYTES = 4_500_000;\n\n/** Signature for the blob upload function, injectable for testing. */\nexport type BlobUploader = (\n clientToken: string,\n pathname: string,\n content: string,\n) => Promise<{ url: string; size: number }>;\n\n/**\n * Strips trailing slashes from a URL string.\n * Uses an iterative approach to avoid regex (CodeQL js/polynomial-redos).\n */\nfunction stripTrailingSlashes(url: string): string {\n let result = url;\n while (result.endsWith(\"/\")) {\n result = result.slice(0, -1);\n }\n return result;\n}\n\n/**\n * Phase 1: Request presigned upload tokens from the ingestion API.\n *\n * POSTs to `{endpoint}/v1/source-maps/presign` with the build hash and\n * file metadata. Returns presigned tokens for each file that the client\n * uses to upload directly to blob storage.\n */\nexport async function requestPresignedTokens(\n apiKey: string,\n endpoint: string,\n buildHash: string,\n files: Array<{ filePath: string; sizeBytes: number }>,\n): Promise<PresignedUploadResponse> {\n const baseUrl = stripTrailingSlashes(endpoint);\n const response = await fetch(`${baseUrl}/v1/source-maps/presign`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ buildHash, files }),\n });\n\n if (!response.ok) {\n try { await response.text(); } catch { /* body drain is best-effort */ }\n throw new Error(\n `Presigned token request failed: ${String(response.status)} ${response.statusText}`,\n );\n }\n\n const json: unknown = await response.json();\n return PresignedUploadResponseSchema.parse(json);\n}\n\n/** Shape of the subset of `@vercel/blob/client` the SDK consumes. */\ntype BlobClientModule = {\n put: (\n pathname: string,\n body: Blob,\n options: { access: string; token: string },\n ) => Promise<{ url: string }>;\n};\n\n/**\n * Loads `@vercel/blob/client` at runtime using the `Function()`-based\n * dynamic-import evasion trick.\n *\n * The indirection hides the specifier from static bundler analysis — webpack,\n * tsup, esbuild, and rollup all resolve literal `await import(\"...\")` targets\n * at build time and would raise `Module not found` for consumers without\n * `@vercel/blob` installed (it is an optional peer dependency). See DISC-1255.\n *\n * **CSP note:** `Function()` is semantically equivalent to `eval()` and will\n * trigger `unsafe-eval` CSP violations in restricted environments. Source-map\n * upload only runs in Node.js at build time, so CSP does not apply here. The\n * same caveat documented on `tryImport` in `otel-config.ts` applies if this\n * code is ever re-used in a browser-equivalent runtime.\n *\n * Exported for internal test injection via {@link _setBlobClientLoaderForTesting}\n * only; not part of the public API.\n */\nasync function defaultBlobClientLoader(): Promise<BlobClientModule> {\n const dynamicImport = Function(\"id\", \"return import(id)\") as (\n id: string,\n ) => Promise<BlobClientModule>;\n return dynamicImport(\"@vercel/blob/client\");\n}\n\nlet _blobClientLoader: () => Promise<BlobClientModule> = defaultBlobClientLoader;\n\n/**\n * Replaces the blob client loader. For test use only.\n *\n * The production loader uses a `Function()`-based dynamic import to evade\n * static bundler analysis (DISC-1255), which in turn bypasses Vitest's\n * module-mock interceptor. Tests that need to stub `@vercel/blob/client`\n * call this helper to install a fake loader, then restore the default\n * with {@link _resetBlobClientLoaderForTesting}.\n *\n * @internal\n */\nexport function _setBlobClientLoaderForTesting(\n loader: () => Promise<BlobClientModule>,\n): void {\n _blobClientLoader = loader;\n}\n\n/**\n * Restores the default `@vercel/blob/client` loader. For test use only.\n *\n * @internal\n */\nexport function _resetBlobClientLoaderForTesting(): void {\n _blobClientLoader = defaultBlobClientLoader;\n}\n\n/**\n * Phase 2: Upload a single source map to blob storage using a presigned token.\n *\n * Dynamically imports `@vercel/blob/client` via {@link defaultBlobClientLoader}\n * to avoid bundling the optional peer dependency. Throws a descriptive error\n * if the package is not installed.\n */\nexport async function uploadToBlob(\n clientToken: string,\n pathname: string,\n content: string,\n): Promise<{ url: string; size: number }> {\n let mod: BlobClientModule;\n try {\n mod = await _blobClientLoader();\n } catch (err) {\n // Distinguish \"not installed\" from other import errors\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ERR_MODULE_NOT_FOUND\" || code === \"MODULE_NOT_FOUND\") {\n throw new Error(\n \"Presigned upload requires @vercel/blob. Install it: npm install @vercel/blob\",\n );\n }\n throw err;\n }\n\n const result = await mod.put(pathname, new Blob([content]), {\n access: \"public\",\n token: clientToken,\n });\n\n return { url: result.url, size: Buffer.byteLength(content, \"utf-8\") };\n}\n\n/**\n * Phase 3: Submit the upload manifest to finalize a presigned upload.\n *\n * POSTs to `{endpoint}/v1/source-maps/manifest` with the upload ID,\n * build hash, and blob URLs for each uploaded file. The backend activates\n * the source maps for stack trace resolution.\n */\nexport async function submitManifest(\n apiKey: string,\n endpoint: string,\n uploadId: string,\n buildHash: string,\n files: Array<{ filePath: string; sizeBytes: number; blobUrl: string }>,\n): Promise<SourceMapManifestResponse> {\n const baseUrl = stripTrailingSlashes(endpoint);\n const response = await fetch(`${baseUrl}/v1/source-maps/manifest`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({ uploadId, buildHash, files }),\n });\n\n if (!response.ok) {\n try { await response.text(); } catch { /* body drain is best-effort */ }\n throw new Error(\n `Source map manifest submission failed: ${String(response.status)} ${response.statusText}`,\n );\n }\n\n const json: unknown = await response.json();\n return SourceMapManifestResponseSchema.parse(json);\n}\n\n/**\n * Orchestrates the 3-phase presigned upload flow.\n *\n * 1. Requests presigned tokens for all source map files\n * 2. Uploads each file to blob storage with a concurrency limit of 5,\n * reading file content from disk just before each upload\n * 3. Submits the manifest to finalize the upload\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (streaming, reads on demand).\n *\n * Accepts an optional `blobUploader` for test injection; defaults to\n * {@link uploadToBlob}.\n */\nexport async function uploadSourceMapsPresigned(\n apiKey: string,\n endpoint: string,\n buildHash: string,\n maps: SourceMapEntry[] | SourceMapFileInfo[],\n blobUploader: BlobUploader = uploadToBlob,\n): Promise<SourceMapManifestResponse> {\n if (maps.length === 0) {\n throw new Error(\"No source maps to upload\");\n }\n\n // Determine file metadata for the presign request\n const fileMetadata = maps.map((m) => ({\n filePath: m.filePath,\n sizeBytes: \"content\" in m\n ? Buffer.byteLength(m.content, \"utf-8\")\n : m.sizeBytes,\n }));\n\n // Phase 1: request presigned tokens\n const presigned = await requestPresignedTokens(\n apiKey, endpoint, buildHash, fileMetadata,\n );\n\n // Build a lookup map for O(1) access by filePath\n const mapsByPath = new Map(maps.map((m) => [m.filePath, m]));\n\n if (mapsByPath.size !== maps.length) {\n throw new Error(\"Duplicate filePath entries in source maps\");\n }\n\n // Validate all tokens have matching entries before starting any uploads.\n for (const token of presigned.files) {\n if (!mapsByPath.has(token.filePath)) {\n throw new Error(\n `Presigned token for \"${token.filePath}\" has no matching source map entry`,\n );\n }\n }\n\n // Phase 2: upload to blob storage in chunks of CONCURRENCY.\n // File content is read from disk just before each upload to avoid\n // holding all source maps in memory simultaneously.\n const CONCURRENCY = 5;\n const uploadResults: Array<{ filePath: string; sizeBytes: number; blobUrl: string }> = [];\n\n for (let i = 0; i < presigned.files.length; i += CONCURRENCY) {\n const chunk = presigned.files.slice(i, i + CONCURRENCY);\n const chunkResults = await Promise.all(\n chunk.map(async (token) => {\n const entry = mapsByPath.get(token.filePath)!;\n let content: string;\n if (\"content\" in entry) {\n content = entry.content;\n } else {\n try {\n content = await readSourceMapContent(entry.absolutePath);\n } catch {\n sdkLog(\"warn\", `[glasstrace] Skipping unreadable source map: ${token.filePath}`);\n return null;\n }\n }\n const result = await blobUploader(token.clientToken, token.pathname, content);\n return {\n filePath: token.filePath,\n sizeBytes: result.size,\n blobUrl: result.url,\n };\n }),\n );\n for (const r of chunkResults) {\n if (r !== null) {\n uploadResults.push(r);\n }\n }\n }\n\n // Phase 3: submit manifest\n return submitManifest(apiKey, endpoint, presigned.uploadId, buildHash, uploadResults);\n}\n\n/**\n * Options for {@link uploadSourceMapsAuto}, primarily used for test injection.\n */\nexport interface AutoUploadOptions {\n /** Override blob availability check (for testing). */\n checkBlobAvailable?: () => Promise<boolean>;\n /** Override blob uploader (for testing). */\n blobUploader?: BlobUploader;\n}\n\n/**\n * Automatically routes source map uploads based on total build size.\n *\n * - Below {@link PRESIGNED_THRESHOLD_BYTES}: uses the legacy single-request\n * {@link uploadSourceMaps} endpoint.\n * - At or above the threshold: checks if `@vercel/blob` is available and\n * uses the presigned 3-phase flow. Falls back to legacy with a warning\n * if the package is not installed.\n *\n * Accepts either `SourceMapEntry[]` (legacy, in-memory) or\n * `SourceMapFileInfo[]` (streaming, reads on demand).\n */\nexport async function uploadSourceMapsAuto(\n apiKey: string,\n endpoint: string,\n buildHash: string,\n maps: SourceMapEntry[] | SourceMapFileInfo[],\n options?: AutoUploadOptions,\n): Promise<SourceMapUploadResponse | SourceMapManifestResponse> {\n if (maps.length === 0) {\n throw new Error(\"No source maps to upload\");\n }\n\n const totalBytes = maps.reduce(\n (sum, m) => {\n const bytes = \"content\" in m\n ? Buffer.byteLength(m.content, \"utf-8\")\n : m.sizeBytes;\n return sum + bytes;\n },\n 0,\n );\n\n if (totalBytes < PRESIGNED_THRESHOLD_BYTES) {\n return uploadSourceMaps(apiKey, endpoint, buildHash, maps);\n }\n\n // Check if @vercel/blob is available. Uses the shared blob client loader\n // (which goes through the `Function()` evasion trick) so webpack / tsup /\n // esbuild do not resolve `@vercel/blob/client` at build time (DISC-1255).\n const checkAvailable = options?.checkBlobAvailable ?? (async () => {\n try {\n await _blobClientLoader();\n return true;\n } catch {\n return false;\n }\n });\n\n const blobAvailable = await checkAvailable();\n\n if (blobAvailable) {\n return uploadSourceMapsPresigned(\n apiKey, endpoint, buildHash, maps, options?.blobUploader,\n );\n }\n\n // Fall back to legacy upload with a warning\n sdkLog(\"warn\",\n `[glasstrace] Build exceeds 4.5MB (${String(totalBytes)} bytes). Install @vercel/blob for ` +\n `presigned uploads to avoid serverless body size limits. Falling back to legacy upload.`\n );\n\n return uploadSourceMaps(apiKey, endpoint, buildHash, maps);\n}\n","import { resolveConfig, isProductionDisabled } from \"../env-detection.js\";\n\n/**\n * Module-level flag ensuring the nudge fires at most once per process.\n */\nlet hasFired = false;\n\n/**\n * Strips control characters (except space) from a string to prevent\n * terminal escape sequence injection via error summaries written to stderr.\n */\nfunction sanitize(input: string): string {\n // eslint-disable-next-line no-control-regex\n return input.replace(/[\\x00-\\x1f\\x7f]/g, \"\");\n}\n\n/**\n * Checks whether the MCP marker file exists using synchronous filesystem\n * APIs. Returns `false` when `node:fs` or `node:path` cannot be resolved\n * (non-Node environments) or on any I/O error.\n */\nfunction markerFileExists(): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const fs = require(\"node:fs\") as typeof import(\"node:fs\");\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const path = require(\"node:path\") as typeof import(\"node:path\");\n const markerPath = path.join(process.cwd(), \".glasstrace\", \"mcp-connected\");\n return fs.existsSync(markerPath);\n } catch {\n // node:fs/node:path unavailable, permission denied, ENOENT from\n // cwd(), or other error — treat as not connected\n return false;\n }\n}\n\n/**\n * Shows a one-time stderr nudge when the SDK captures its first error\n * and the MCP connection marker file is absent.\n *\n * The nudge is suppressed when:\n * - It has already fired in this process\n * - The `.glasstrace/mcp-connected` marker file exists at the project root\n * - The environment is detected as production (and force-enable is off)\n *\n * Uses `process.stderr.write()` instead of `console.error()` to avoid\n * being captured by OpenTelemetry console instrumentation.\n */\nexport function maybeShowMcpNudge(errorSummary: string): void {\n if (hasFired) {\n return;\n }\n\n // Production check — suppress silently, but remember the decision\n // so subsequent calls fast-exit via hasFired without re-running I/O.\n const config = resolveConfig();\n if (isProductionDisabled(config)) {\n hasFired = true;\n return;\n }\n\n // Check for MCP connection marker file.\n if (markerFileExists()) {\n hasFired = true;\n return;\n }\n\n // Fire the nudge exactly once\n hasFired = true;\n\n const safe = sanitize(errorSummary);\n process.stderr.write(\n `[glasstrace] Error captured: ${safe}\\n` +\n ` Debug with AI: ask your agent \"What's the latest Glasstrace error?\"\\n` +\n ` Not connected? Run: npx glasstrace mcp add\\n`,\n );\n}\n","/**\n * Console error/warn capture module.\n *\n * When enabled, monkey-patches `console.error` and `console.warn` to record\n * their output as OTel span events on the currently active span. SDK-internal\n * log messages (prefixed with \"[glasstrace]\") are never captured.\n */\n\nimport { maybeShowMcpNudge } from \"./nudge/error-nudge.js\";\n\n/**\n * Module-level flag to suppress capture of SDK-internal log messages.\n * Set to `true` before calling `console.warn`/`console.error` from SDK code,\n * then reset to `false` immediately after.\n */\nexport let isGlasstraceLog = false;\n\n/** Saved reference to the original `console.error`. */\nlet originalError: typeof console.error | null = null;\n\n/** Saved reference to the original `console.warn`. */\nlet originalWarn: typeof console.warn | null = null;\n\n/** Whether the console capture is currently installed. */\nlet installed = false;\n\n/** Cached OTel API module reference, resolved at install time. */\nlet otelApi: typeof import(\"@opentelemetry/api\") | null = null;\n\n/**\n * Formats console arguments into a single string for span event attributes.\n * Uses best-effort serialization: strings pass through, Errors preserve their\n * stack trace, and other values are JSON-stringified with a String() fallback.\n */\nfunction formatArgs(args: unknown[]): string {\n return args\n .map((arg) => {\n if (typeof arg === \"string\") return arg;\n if (arg instanceof Error) return arg.stack ?? arg.message;\n try {\n return JSON.stringify(arg);\n } catch {\n return String(arg);\n }\n })\n .join(\" \");\n}\n\n/**\n * Returns `true` if the first argument is a string starting with \"[glasstrace]\".\n * Used to skip capture of SDK-internal log messages without requiring every\n * call site to set the `isGlasstraceLog` flag.\n */\nfunction isSdkMessage(args: unknown[]): boolean {\n return typeof args[0] === \"string\" && args[0].startsWith(\"[glasstrace]\");\n}\n\n/**\n * Installs console capture by replacing `console.error` and `console.warn`\n * with wrappers that record span events on the active OTel span.\n *\n * Must be called after OTel is configured so the API module is available.\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport async function installConsoleCapture(): Promise<void> {\n if (installed) return;\n\n // Resolve OTel API at install time via dynamic import so that:\n // 1. tsup inlines @opentelemetry/api into the bundle (it's in noExternal)\n // 2. vitest's vi.doMock can intercept this import for testing\n try {\n otelApi = await import(\"@opentelemetry/api\");\n } catch {\n otelApi = null;\n }\n\n originalError = console.error;\n originalWarn = console.warn;\n installed = true;\n\n console.error = (...args: unknown[]) => {\n // Always call the original first to preserve developer experience\n originalError!.apply(console, args);\n\n // Skip SDK-internal messages and flagged messages\n if (isGlasstraceLog || isSdkMessage(args)) return;\n\n if (otelApi) {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (span) {\n const formattedMessage = formatArgs(args);\n span.addEvent(\"console.error\", {\n \"console.message\": formattedMessage,\n });\n // Show one-time MCP connection nudge on first captured error\n try {\n maybeShowMcpNudge(formattedMessage);\n } catch {\n // Never allow the monkey-patched console.error wrapper to throw\n }\n }\n }\n };\n\n console.warn = (...args: unknown[]) => {\n originalWarn!.apply(console, args);\n\n if (isGlasstraceLog || isSdkMessage(args)) return;\n\n if (otelApi) {\n const span = otelApi.trace.getSpan(otelApi.context.active());\n if (span) {\n span.addEvent(\"console.warn\", {\n \"console.message\": formatArgs(args),\n });\n }\n }\n };\n}\n\n/**\n * Restores the original `console.error` and `console.warn` methods.\n * Primarily intended for use in tests.\n */\nexport function uninstallConsoleCapture(): void {\n if (!installed) return;\n\n if (originalError) console.error = originalError;\n if (originalWarn) console.warn = originalWarn;\n\n originalError = null;\n originalWarn = null;\n otelApi = null;\n installed = false;\n}\n\n/**\n * Logs a message from SDK-internal code without triggering console capture.\n *\n * Use this helper in new SDK code instead of bare `console.warn(...)` calls\n * to prevent SDK log messages from being recorded as user-facing span events.\n *\n * @param level - The console log level to use.\n * @param message - The message to log.\n */\nexport function sdkLog(level: \"warn\" | \"info\" | \"error\", message: string): void {\n isGlasstraceLog = true;\n try {\n console[level](message);\n } finally {\n isGlasstraceLog = false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,YAAY;AACxB,SAAS,oBAAoB;;;ACE7B,IAAI,WAAW;AAMf,SAAS,SAAS,OAAuB;AAEvC,SAAO,MAAM,QAAQ,oBAAoB,EAAE;AAC7C;AAOA,SAAS,mBAA4B;AACnC,MAAI;AAEF,UAAMA,MAAK,UAAQ,SAAS;AAE5B,UAAMC,QAAO,UAAQ,WAAW;AAChC,UAAM,aAAaA,MAAK,KAAK,QAAQ,IAAI,GAAG,eAAe,eAAe;AAC1E,WAAOD,IAAG,WAAW,UAAU;AAAA,EACjC,QAAQ;AAGN,WAAO;AAAA,EACT;AACF;AAcO,SAAS,kBAAkB,cAA4B;AAC5D,MAAI,UAAU;AACZ;AAAA,EACF;AAIA,QAAM,SAAS,cAAc;AAC7B,MAAI,qBAAqB,MAAM,GAAG;AAChC,eAAW;AACX;AAAA,EACF;AAGA,MAAI,iBAAiB,GAAG;AACtB,eAAW;AACX;AAAA,EACF;AAGA,aAAW;AAEX,QAAM,OAAO,SAAS,YAAY;AAClC,UAAQ,OAAO;AAAA,IACb,gCAAgC,IAAI;AAAA;AAAA;AAAA;AAAA,EAGtC;AACF;;;AC7DO,IAAI,kBAAkB;AAG7B,IAAI,gBAA6C;AAGjD,IAAI,eAA2C;AAG/C,IAAI,YAAY;AAGhB,IAAI,UAAsD;AAO1D,SAAS,WAAW,MAAyB;AAC3C,SAAO,KACJ,IAAI,CAAC,QAAQ;AACZ,QAAI,OAAO,QAAQ,SAAU,QAAO;AACpC,QAAI,eAAe,MAAO,QAAO,IAAI,SAAS,IAAI;AAClD,QAAI;AACF,aAAO,KAAK,UAAU,GAAG;AAAA,IAC3B,QAAQ;AACN,aAAO,OAAO,GAAG;AAAA,I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_CONFIG_NAMES
3
- } from "./chunk-BL3YDC6V.js";
4
- import {
5
- init_esm_shims
6
- } from "./chunk-BGZ7J74D.js";
7
-
8
- // src/cli/scaffolder.ts
9
- init_esm_shims();
10
- import { createHash } from "crypto";
11
- import * as fs from "fs";
12
- import * as path from "path";
13
- function identityFingerprint(token) {
14
- return `sha256:${createHash("sha256").update(token).digest("hex")}`;
15
- }
16
- function hasRegisterGlasstraceCall(content) {
17
- return content.split("\n").some((line) => {
18
- const uncommented = line.replace(/\/\/.*$/, "");
19
- return /\bregisterGlasstrace\s*\(/.test(uncommented);
20
- });
21
- }
22
- function injectRegisterGlasstrace(content) {
23
- if (hasRegisterGlasstraceCall(content)) {
24
- return { injected: false, content };
25
- }
26
- const registerFnRegex = /export\s+(?:async\s+)?function\s+register\s*\([^)]*\)\s*\{/;
27
- const match = registerFnRegex.exec(content);
28
- if (!match) {
29
- return { injected: false, content };
30
- }
31
- const afterBrace = content.slice(match.index + match[0].length);
32
- const indentMatch = /\n([ \t]+)/.exec(afterBrace);
33
- const indent = indentMatch ? indentMatch[1] : " ";
34
- const importLine = 'import { registerGlasstrace } from "@glasstrace/sdk";\n';
35
- const hasGlasstraceImport = content.includes("@glasstrace/sdk");
36
- const insertPoint = match.index + match[0].length;
37
- const callInjection = `
38
- ${indent}// Glasstrace must be registered before other instrumentation
39
- ${indent}registerGlasstrace();
40
- `;
41
- let modified;
42
- if (hasGlasstraceImport) {
43
- const importRegex = /import\s*\{([^}]+)\}\s*from\s*["']@glasstrace\/sdk["']/;
44
- const importMatch = importRegex.exec(content);
45
- if (importMatch) {
46
- const specifiers = importMatch[1];
47
- const alreadyImported = specifiers.split(",").some((s) => s.trim() === "registerGlasstrace");
48
- if (alreadyImported) {
49
- modified = content.slice(0, insertPoint) + callInjection + content.slice(insertPoint);
50
- } else {
51
- const existingImports = specifiers.trimEnd();
52
- const separator = existingImports.endsWith(",") ? " " : ", ";
53
- const updatedImport = `import { ${existingImports.trim()}${separator}registerGlasstrace } from "@glasstrace/sdk"`;
54
- modified = content.replace(importMatch[0], updatedImport);
55
- const newMatch = registerFnRegex.exec(modified);
56
- if (newMatch) {
57
- const newInsertPoint = newMatch.index + newMatch[0].length;
58
- modified = modified.slice(0, newInsertPoint) + callInjection + modified.slice(newInsertPoint);
59
- }
60
- }
61
- } else {
62
- modified = importLine + content;
63
- const newMatch = registerFnRegex.exec(modified);
64
- if (newMatch) {
65
- const newInsertPoint = newMatch.index + newMatch[0].length;
66
- modified = modified.slice(0, newInsertPoint) + callInjection + modified.slice(newInsertPoint);
67
- }
68
- }
69
- } else {
70
- modified = importLine + content.slice(0, insertPoint) + callInjection + content.slice(insertPoint);
71
- }
72
- return { injected: true, content: modified };
73
- }
74
- async function scaffoldInstrumentation(projectRoot) {
75
- const filePath = path.join(projectRoot, "instrumentation.ts");
76
- if (!fs.existsSync(filePath)) {
77
- const content = `import { registerGlasstrace } from "@glasstrace/sdk";
78
-
79
- export async function register() {
80
- // Glasstrace must be registered before Prisma instrumentation
81
- // to ensure all ORM spans are captured correctly.
82
- // If you use @prisma/instrumentation, import it after this call.
83
- registerGlasstrace();
84
- }
85
- `;
86
- fs.writeFileSync(filePath, content, "utf-8");
87
- return { action: "created" };
88
- }
89
- const existing = fs.readFileSync(filePath, "utf-8");
90
- if (hasRegisterGlasstraceCall(existing)) {
91
- return { action: "already-registered" };
92
- }
93
- const result = injectRegisterGlasstrace(existing);
94
- if (result.injected) {
95
- fs.writeFileSync(filePath, result.content, "utf-8");
96
- return { action: "injected" };
97
- }
98
- return { action: "unrecognized" };
99
- }
100
- async function scaffoldNextConfig(projectRoot) {
101
- let configPath;
102
- let configName;
103
- for (const name of NEXT_CONFIG_NAMES) {
104
- const candidate = path.join(projectRoot, name);
105
- if (fs.existsSync(candidate)) {
106
- configPath = candidate;
107
- configName = name;
108
- break;
109
- }
110
- }
111
- if (configPath === void 0 || configName === void 0) {
112
- return null;
113
- }
114
- const existing = fs.readFileSync(configPath, "utf-8");
115
- if (existing.trim().length === 0) {
116
- return { modified: false, reason: "empty-file" };
117
- }
118
- if (existing.includes("withGlasstraceConfig")) {
119
- return { modified: false, reason: "already-wrapped" };
120
- }
121
- const isESM = configName.endsWith(".ts") || configName.endsWith(".mjs");
122
- if (isESM) {
123
- const importLine = 'import { withGlasstraceConfig } from "@glasstrace/sdk";\n';
124
- const wrapResult2 = wrapExport(existing);
125
- if (!wrapResult2.wrapped) {
126
- return { modified: false, reason: "no-export" };
127
- }
128
- const modified2 = importLine + "\n" + wrapResult2.content;
129
- fs.writeFileSync(configPath, modified2, "utf-8");
130
- return { modified: true };
131
- }
132
- const requireLine = 'const { withGlasstraceConfig } = require("@glasstrace/sdk");\n';
133
- const wrapResult = wrapCJSExport(existing);
134
- if (!wrapResult.wrapped) {
135
- return { modified: false, reason: "no-export" };
136
- }
137
- const modified = requireLine + "\n" + wrapResult.content;
138
- fs.writeFileSync(configPath, modified, "utf-8");
139
- return { modified: true };
140
- }
141
- function wrapExport(content) {
142
- const marker = "export default";
143
- const idx = content.lastIndexOf(marker);
144
- if (idx === -1) {
145
- return { content, wrapped: false };
146
- }
147
- const preamble = content.slice(0, idx);
148
- const exprRaw = content.slice(idx + marker.length);
149
- const expr = exprRaw.trim().replace(/;?\s*$/, "");
150
- if (expr.length === 0) {
151
- return { content, wrapped: false };
152
- }
153
- return {
154
- content: preamble + `export default withGlasstraceConfig(${expr});
155
- `,
156
- wrapped: true
157
- };
158
- }
159
- function wrapCJSExport(content) {
160
- const cjsMarker = "module.exports";
161
- const cjsIdx = content.lastIndexOf(cjsMarker);
162
- if (cjsIdx === -1) {
163
- return { content, wrapped: false };
164
- }
165
- const preamble = content.slice(0, cjsIdx);
166
- const afterMarker = content.slice(cjsIdx + cjsMarker.length);
167
- const eqMatch = /^\s*=\s*/.exec(afterMarker);
168
- if (!eqMatch) {
169
- return { content, wrapped: false };
170
- }
171
- const exprRaw = afterMarker.slice(eqMatch[0].length);
172
- const expr = exprRaw.trim().replace(/;?\s*$/, "");
173
- if (expr.length === 0) {
174
- return { content, wrapped: false };
175
- }
176
- return {
177
- content: preamble + `module.exports = withGlasstraceConfig(${expr});
178
- `,
179
- wrapped: true
180
- };
181
- }
182
- async function scaffoldEnvLocal(projectRoot) {
183
- const filePath = path.join(projectRoot, ".env.local");
184
- if (fs.existsSync(filePath)) {
185
- const existing = fs.readFileSync(filePath, "utf-8");
186
- if (/^\s*#?\s*GLASSTRACE_API_KEY\s*=/m.test(existing)) {
187
- return false;
188
- }
189
- const separator = existing.endsWith("\n") ? "" : "\n";
190
- fs.writeFileSync(filePath, existing + separator + "# GLASSTRACE_API_KEY=your_key_here\n", "utf-8");
191
- return true;
192
- }
193
- fs.writeFileSync(filePath, "# GLASSTRACE_API_KEY=your_key_here\n", "utf-8");
194
- return true;
195
- }
196
- async function addCoverageMapEnv(projectRoot) {
197
- const filePath = path.join(projectRoot, ".env.local");
198
- if (!fs.existsSync(filePath)) {
199
- fs.writeFileSync(filePath, "GLASSTRACE_COVERAGE_MAP=true\n", "utf-8");
200
- return true;
201
- }
202
- const existing = fs.readFileSync(filePath, "utf-8");
203
- const keyRegex = /^(\s*GLASSTRACE_COVERAGE_MAP\s*=\s*)(.*)$/m;
204
- const keyMatch = keyRegex.exec(existing);
205
- if (keyMatch) {
206
- const currentValue = keyMatch[2].trim();
207
- if (currentValue === "true") {
208
- return false;
209
- }
210
- const updated = existing.replace(keyRegex, `${keyMatch[1]}true`);
211
- fs.writeFileSync(filePath, updated, "utf-8");
212
- return true;
213
- }
214
- const separator = existing.endsWith("\n") ? "" : "\n";
215
- fs.writeFileSync(filePath, existing + separator + "GLASSTRACE_COVERAGE_MAP=true\n", "utf-8");
216
- return true;
217
- }
218
- async function scaffoldGitignore(projectRoot) {
219
- const filePath = path.join(projectRoot, ".gitignore");
220
- if (fs.existsSync(filePath)) {
221
- const existing = fs.readFileSync(filePath, "utf-8");
222
- const lines = existing.split("\n").map((l) => l.trim());
223
- if (lines.includes(".glasstrace/")) {
224
- return false;
225
- }
226
- const separator = existing.endsWith("\n") ? "" : "\n";
227
- fs.writeFileSync(filePath, existing + separator + ".glasstrace/\n", "utf-8");
228
- return true;
229
- }
230
- fs.writeFileSync(filePath, ".glasstrace/\n", "utf-8");
231
- return true;
232
- }
233
- async function scaffoldMcpMarker(projectRoot, anonKey) {
234
- const dirPath = path.join(projectRoot, ".glasstrace");
235
- const markerPath = path.join(dirPath, "mcp-connected");
236
- const keyHash = identityFingerprint(anonKey);
237
- if (fs.existsSync(markerPath)) {
238
- try {
239
- const existing = JSON.parse(fs.readFileSync(markerPath, "utf-8"));
240
- if (existing.keyHash === keyHash) {
241
- return false;
242
- }
243
- } catch {
244
- }
245
- }
246
- fs.mkdirSync(dirPath, { recursive: true, mode: 448 });
247
- const marker = JSON.stringify(
248
- { keyHash, configuredAt: (/* @__PURE__ */ new Date()).toISOString() },
249
- null,
250
- 2
251
- );
252
- fs.writeFileSync(markerPath, marker, { mode: 384 });
253
- fs.chmodSync(markerPath, 384);
254
- return true;
255
- }
256
-
257
1
  // src/agent-detection/detect.ts
258
- init_esm_shims();
259
- import { execFile } from "child_process";
260
- import { access, stat } from "fs/promises";
261
- import { dirname, join as join2, resolve } from "path";
262
- import { homedir } from "os";
263
- import { constants } from "fs";
2
+ import { execFile } from "node:child_process";
3
+ import { access, stat } from "node:fs/promises";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { homedir } from "node:os";
6
+ import { constants } from "node:fs";
264
7
  var AGENT_RULES = [
265
8
  {
266
9
  name: "claude",
267
10
  markers: [".claude", "CLAUDE.md"],
268
- mcpConfigPath: (dir) => join2(dir, ".mcp.json"),
269
- infoFilePath: (dir) => join2(dir, "CLAUDE.md"),
11
+ mcpConfigPath: (dir) => join(dir, ".mcp.json"),
12
+ infoFilePath: (dir) => join(dir, "CLAUDE.md"),
270
13
  cliBinary: "claude",
271
14
  registrationCommand: "npx glasstrace mcp add --agent claude"
272
15
  },
273
16
  {
274
17
  name: "codex",
275
18
  markers: ["codex.md", ".codex"],
276
- mcpConfigPath: (dir) => join2(dir, ".codex", "config.toml"),
277
- infoFilePath: (dir) => join2(dir, "codex.md"),
19
+ mcpConfigPath: (dir) => join(dir, ".codex", "config.toml"),
20
+ infoFilePath: (dir) => join(dir, "codex.md"),
278
21
  cliBinary: "codex",
279
22
  registrationCommand: "npx glasstrace mcp add --agent codex"
280
23
  },
281
24
  {
282
25
  name: "gemini",
283
26
  markers: [".gemini"],
284
- mcpConfigPath: (dir) => join2(dir, ".gemini", "settings.json"),
27
+ mcpConfigPath: (dir) => join(dir, ".gemini", "settings.json"),
285
28
  infoFilePath: () => null,
286
29
  cliBinary: "gemini",
287
30
  registrationCommand: "npx glasstrace mcp add --agent gemini"
@@ -289,23 +32,23 @@ var AGENT_RULES = [
289
32
  {
290
33
  name: "cursor",
291
34
  markers: [".cursor", ".cursorrules"],
292
- mcpConfigPath: (dir) => join2(dir, ".cursor", "mcp.json"),
293
- infoFilePath: (dir) => join2(dir, ".cursorrules"),
35
+ mcpConfigPath: (dir) => join(dir, ".cursor", "mcp.json"),
36
+ infoFilePath: (dir) => join(dir, ".cursorrules"),
294
37
  cliBinary: null,
295
38
  registrationCommand: "npx glasstrace mcp add --agent cursor"
296
39
  },
297
40
  {
298
41
  name: "windsurf",
299
42
  markers: [".windsurfrules", ".windsurf"],
300
- mcpConfigPath: () => join2(homedir(), ".codeium", "windsurf", "mcp_config.json"),
301
- infoFilePath: (dir) => join2(dir, ".windsurfrules"),
43
+ mcpConfigPath: () => join(homedir(), ".codeium", "windsurf", "mcp_config.json"),
44
+ infoFilePath: (dir) => join(dir, ".windsurfrules"),
302
45
  cliBinary: null,
303
46
  registrationCommand: "npx glasstrace mcp add --agent windsurf"
304
47
  }
305
48
  ];
306
- async function pathExists(path2, mode = constants.R_OK) {
49
+ async function pathExists(path, mode = constants.R_OK) {
307
50
  try {
308
- await access(path2, mode);
51
+ await access(path, mode);
309
52
  return true;
310
53
  } catch {
311
54
  return false;
@@ -314,7 +57,7 @@ async function pathExists(path2, mode = constants.R_OK) {
314
57
  async function findGitRoot(startDir) {
315
58
  let current = resolve(startDir);
316
59
  while (true) {
317
- if (await pathExists(join2(current, ".git"), constants.F_OK)) {
60
+ if (await pathExists(join(current, ".git"), constants.F_OK)) {
318
61
  return current;
319
62
  }
320
63
  const parent = dirname(current);
@@ -368,7 +111,7 @@ async function detectAgents(projectRoot) {
368
111
  for (const dir of searchDirs) {
369
112
  let markerFound = false;
370
113
  for (const marker of rule.markers) {
371
- if (await pathExists(join2(dir, marker))) {
114
+ if (await pathExists(join(dir, marker))) {
372
115
  markerFound = true;
373
116
  break;
374
117
  }
@@ -400,7 +143,7 @@ async function detectAgents(projectRoot) {
400
143
  }
401
144
  detected.push({
402
145
  name: "generic",
403
- mcpConfigPath: join2(resolvedRoot, ".glasstrace", "mcp.json"),
146
+ mcpConfigPath: join(resolvedRoot, ".glasstrace", "mcp.json"),
404
147
  infoFilePath: null,
405
148
  cliAvailable: false,
406
149
  registrationCommand: null
@@ -409,7 +152,6 @@ async function detectAgents(projectRoot) {
409
152
  }
410
153
 
411
154
  // src/agent-detection/configs.ts
412
- init_esm_shims();
413
155
  function generateMcpConfig(agent, endpoint, anonKey) {
414
156
  if (!endpoint || endpoint.trim() === "") {
415
157
  throw new Error("endpoint must not be empty");
@@ -572,9 +314,8 @@ ${content}${m.end}
572
314
  }
573
315
 
574
316
  // src/agent-detection/inject.ts
575
- init_esm_shims();
576
- import { chmod, mkdir, readFile, writeFile } from "fs/promises";
577
- import { dirname as dirname2, isAbsolute, join as join3 } from "path";
317
+ import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
318
+ import { dirname as dirname2, isAbsolute, join as join2 } from "node:path";
578
319
  var HTML_START = "<!-- glasstrace:mcp:start -->";
579
320
  var HTML_END = "<!-- glasstrace:mcp:end -->";
580
321
  var HASH_START = "# glasstrace:mcp:start";
@@ -703,7 +444,7 @@ async function injectInfoSection(agent, content, projectRoot) {
703
444
  }
704
445
  }
705
446
  async function updateGitignore(paths, projectRoot) {
706
- const gitignorePath = join3(projectRoot, ".gitignore");
447
+ const gitignorePath = join2(projectRoot, ".gitignore");
707
448
  const relativePaths = paths.filter((p) => !isAbsolute(p));
708
449
  if (relativePaths.length === 0) {
709
450
  return;
@@ -750,12 +491,6 @@ async function updateGitignore(paths, projectRoot) {
750
491
  }
751
492
 
752
493
  export {
753
- scaffoldInstrumentation,
754
- scaffoldNextConfig,
755
- scaffoldEnvLocal,
756
- addCoverageMapEnv,
757
- scaffoldGitignore,
758
- scaffoldMcpMarker,
759
494
  detectAgents,
760
495
  generateMcpConfig,
761
496
  generateInfoSection,
@@ -763,4 +498,4 @@ export {
763
498
  injectInfoSection,
764
499
  updateGitignore
765
500
  };
766
- //# sourceMappingURL=chunk-WV3NIPWJ.js.map
501
+ //# sourceMappingURL=chunk-CTJI2YKA.js.map