From df4194afaabc408ee5d6ed9a15c045012f81ba33 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 3 Nov 2026 06:38:14 -0500 Subject: [PATCH 1/6] build: add reproducible, deploy-safe bundle size report --- .gitignore | 1 + CONTRIBUTING.md | 1 + package.json | 4 +- pnpm-lock.yaml | 226 +++++++++++++++++++++++++++++++++++++++ scripts/bundle-report.sh | 168 +++++++++++++++++++++++++++++ vite.config.ts | 18 +++- 6 files changed, 416 insertions(+), 2 deletions(-) create mode 100755 scripts/bundle-report.sh diff --git a/.gitignore b/.gitignore index dd68020c..d965d387 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ node_modules/ dist/ +dist-report/ mcp/dist/ dist/shared/ *.tsbuildinfo diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9858bcb1..f48f976b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -42,6 +42,7 @@ pnpm run typecheck # TypeScript validation (root + mcp/) pnpm lint # Type-aware lint check (oxlint — root + mcp/) pnpm lint:fix # Auto-fix safe lint findings (oxlint) pnpm run screenshot # Capture dashboard screenshot (saves to docs/) +pnpm bundle:report # Build and print client bundle sizes + top-20 entry modules (deploy-safe) pnpm mcp:serve # Start the MCP server (requires GITHUB_TOKEN) ``` diff --git a/package.json b/package.json index 745585d5..d3b26c50 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,8 @@ "test:status-smoke": "vitest run --config vitest.smoke.config.ts", "screenshot": "pnpm exec playwright test --config playwright.config.screenshot.ts", "mcp:serve": "pnpm --filter github-tracker-mcp dev", - "validate:deploy": "bash scripts/validate-deploy.sh" + "validate:deploy": "bash scripts/validate-deploy.sh", + "bundle:report": "bash scripts/bundle-report.sh" }, "dependencies": { "@kobalte/core": "0.13.14", @@ -49,6 +50,7 @@ "happy-dom": "21.0.4", "oxlint": "1.89.0", "oxlint-tsgolint": "7.0.2004", + "rollup-plugin-visualizer": "7.1.1", "tailwindcss": "4.3.3", "typescript": "7.0.2", "vite": "8.3.4", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9172979e..e1160096 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -242,6 +242,9 @@ importers: oxlint-tsgolint: specifier: 7.0.2004 version: 7.0.2004 + rollup-plugin-visualizer: + specifier: 7.1.1 + version: 7.1.1(rolldown@1.2.15)(rollup@4.65.0) tailwindcss: specifier: 4.3.3 version: 4.3.3 @@ -1781,10 +1784,18 @@ packages: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} + ansi-regex@6.4.0: + resolution: {integrity: sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==} + engines: {node: '>=12'} + ansi-styles@5.2.0: resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} engines: {node: '>=10'} + ansi-styles@6.2.3: + resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} + engines: {node: '>=12'} + any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} @@ -1844,6 +1855,10 @@ packages: resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==} engines: {node: '>=4.0'} + bundle-name@4.1.1: + resolution: {integrity: sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA==} + engines: {node: '>=18'} + bundle-require@5.1.0: resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -1884,6 +1899,10 @@ packages: cjs-module-lexer@1.2.3: resolution: {integrity: sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==} + cliui@9.0.1: + resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==} + engines: {node: '>=20'} + code-block-writer@13.0.3: resolution: {integrity: sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==} @@ -1952,6 +1971,18 @@ packages: supports-color: optional: true + default-browser-id@5.0.1: + resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==} + engines: {node: '>=18'} + + default-browser@5.5.1: + resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==} + engines: {node: '>=18'} + + define-lazy-prop@3.0.0: + resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==} + engines: {node: '>=12'} + depd@2.0.0: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} @@ -1977,6 +2008,9 @@ packages: electron-to-chromium@1.5.463: resolution: {integrity: sha512-nVWNU6ltFjopvOdD44J4zoBkgO0M+WZiFKKFV7EjebOH9z0KNphk6bCEjplXtJofL21ARIuuwWOCsFkBVklm6w==} + emoji-regex@10.6.0: + resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==} + encodeurl@2.0.0: resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} engines: {node: '>= 0.8'} @@ -2102,6 +2136,14 @@ packages: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + + get-east-asian-width@1.7.0: + resolution: {integrity: sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==} + engines: {node: '>=18'} + get-intrinsic@1.3.0: resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} engines: {node: '>= 0.4'} @@ -2158,6 +2200,20 @@ packages: resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} engines: {node: '>= 0.10'} + is-docker@3.0.0: + resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + hasBin: true + + is-in-ssh@1.0.0: + resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==} + engines: {node: '>=20'} + + is-inside-container@1.0.0: + resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==} + engines: {node: '>=14.16'} + hasBin: true + is-promise@4.0.0: resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} @@ -2165,6 +2221,10 @@ packages: resolution: {integrity: sha512-ZhMwEosbFJkA0YhFnNDgTM4ZxDRsS6HqTo7qsZM08fehyRYIYa0yHu5R6mgo1n/8MgaPBXiPimPD77baVFYg+A==} engines: {node: '>=12.13'} + is-wsl@3.1.1: + resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==} + engines: {node: '>=16'} + isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} @@ -2457,6 +2517,10 @@ packages: once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + open@11.0.4: + resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==} + engines: {node: '>=20'} + oxlint-tsgolint@7.0.2004: resolution: {integrity: sha512-vQ9WDF3fiZJvRdSDosNOflerOCOpwol6vWzVDxW76RcU19cjTh7engvkHLvmv+tzedR8fAiJUVUGr6IVZdkzXQ==} hasBin: true @@ -2550,6 +2614,10 @@ packages: resolution: {integrity: sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==} engines: {node: ^10 || ^12 || >=14} + powershell-utils@0.2.1: + resolution: {integrity: sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==} + engines: {node: '>=20'} + pretty-format@27.5.1: resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} @@ -2593,6 +2661,19 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + rollup-plugin-visualizer@7.1.1: + resolution: {integrity: sha512-ThaGiHTU8XW02OkK80TrTHATraJmM9OAduU4otal+7gyXLpYEtmGBLfx5kW+EHvvLwn03YGW2NnwKUIqsYlJAA==} + engines: {node: '>=22'} + hasBin: true + peerDependencies: + rolldown: 1.x || ^1.0.0-beta || ^1.0.0-rc + rollup: 2.x || 3.x || 4.x + peerDependenciesMeta: + rolldown: + optional: true + rollup: + optional: true + rollup@4.65.0: resolution: {integrity: sha512-QVCvQUTGDN6JRwi3jVGCY3H4aTHvi9rX0LyoBMkGUvdh/Z6O51CzcLz85BWZaTCDGhl6ySGqYZs+xI1jmPqGcw==} engines: {node: '>=18.0.0', npm: '>=8.0.0'} @@ -2602,6 +2683,10 @@ packages: resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} engines: {node: '>= 18'} + run-applescript@7.1.0: + resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==} + engines: {node: '>=18'} + safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} @@ -2690,6 +2775,10 @@ packages: resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} + source-map@0.8.0: + resolution: {integrity: sha512-d8EqvL+k/SOXCreS/SUzg2ciyHqBBLcN/yuRjFsbvVhHTE2pgei7oAhmPM7kWFbkX6OSMQfUq4KbkF3au9lhYQ==} + engines: {node: '>= 12'} + statuses@2.0.2: resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} engines: {node: '>= 0.8'} @@ -2697,6 +2786,18 @@ packages: std-env@4.3.0: resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} + string-width@7.2.0: + resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==} + engines: {node: '>=18'} + + string-width@8.3.0: + resolution: {integrity: sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==} + engines: {node: '>=20'} + + strip-ansi@7.2.0: + resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} + engines: {node: '>=12'} + sucrase@3.35.1: resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} engines: {node: '>=16 || 14 >=14.17'} @@ -2951,6 +3052,10 @@ packages: '@cloudflare/workers-types': optional: true + wrap-ansi@9.0.2: + resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==} + engines: {node: '>=18'} + wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} @@ -2978,9 +3083,25 @@ packages: utf-8-validate: optional: true + wsl-utils@1.0.1: + resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==} + engines: {node: '>=20'} + + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yargs-parser@22.0.0: + resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==} + engines: {node: ^20.19.0 || ^22.12.0 || >=23} + + yargs@18.2.0: + resolution: {integrity: sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==} + engines: {node: ^20.19.0 || ^22.12.0 || >=23} + youch-core@0.3.3: resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} @@ -4137,8 +4258,12 @@ snapshots: ansi-regex@5.0.1: {} + ansi-regex@6.4.0: {} + ansi-styles@5.2.0: {} + ansi-styles@6.2.3: {} + any-promise@1.3.0: {} aria-query@5.3.0: @@ -4203,6 +4328,10 @@ snapshots: dependencies: '@types/node': 26.6.5 + bundle-name@4.1.1: + dependencies: + run-applescript: 7.1.0 + bundle-require@5.1.0(esbuild@0.28.2): dependencies: esbuild: 0.28.2 @@ -4234,6 +4363,12 @@ snapshots: cjs-module-lexer@1.2.3: {} + cliui@9.0.1: + dependencies: + string-width: 7.2.0 + strip-ansi: 7.2.0 + wrap-ansi: 9.0.2 + code-block-writer@13.0.3: {} commander@4.1.1: {} @@ -4279,6 +4414,15 @@ snapshots: optionalDependencies: supports-color: 10.2.2 + default-browser-id@5.0.1: {} + + default-browser@5.5.1: + dependencies: + bundle-name: 4.1.1 + default-browser-id: 5.0.1 + + define-lazy-prop@3.0.0: {} + depd@2.0.0: {} dequal@2.0.3: {} @@ -4297,6 +4441,8 @@ snapshots: electron-to-chromium@1.5.463: {} + emoji-regex@10.6.0: {} + encodeurl@2.0.0: {} enhanced-resolve@5.26.0: @@ -4450,6 +4596,10 @@ snapshots: gensync@1.0.0-beta.2: {} + get-caller-file@2.0.5: {} + + get-east-asian-width@1.7.0: {} + get-intrinsic@1.3.0: dependencies: call-bind-apply-helpers: 1.0.2 @@ -4515,10 +4665,22 @@ snapshots: ipaddr.js@1.9.1: {} + is-docker@3.0.0: {} + + is-in-ssh@1.0.0: {} + + is-inside-container@1.0.0: + dependencies: + is-docker: 3.0.0 + is-promise@4.0.0: {} is-what@4.1.16: {} + is-wsl@3.1.1: + dependencies: + is-inside-container: 1.0.0 + isexe@2.0.0: {} jiti@2.7.0: {} @@ -4744,6 +4906,15 @@ snapshots: dependencies: wrappy: 1.0.2 + open@11.0.4: + dependencies: + default-browser: 5.5.1 + define-lazy-prop: 3.0.0 + is-in-ssh: 1.0.0 + is-inside-container: 1.0.0 + powershell-utils: 0.2.1 + wsl-utils: 1.0.1 + oxlint-tsgolint@7.0.2004: optionalDependencies: '@oxlint-tsgolint/darwin-arm64': 7.0.2004 @@ -4828,6 +4999,8 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.2 + powershell-utils@0.2.1: {} + pretty-format@27.5.1: dependencies: ansi-regex: 5.0.1 @@ -4884,6 +5057,16 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.2.15 '@rolldown/binding-win32-x64-msvc': 1.2.15 + rollup-plugin-visualizer@7.1.1(rolldown@1.2.15)(rollup@4.65.0): + dependencies: + open: 11.0.4 + picomatch: 4.0.7 + source-map: 0.8.0 + yargs: 18.2.0 + optionalDependencies: + rolldown: 1.2.15 + rollup: 4.65.0 + rollup@4.65.0: dependencies: '@types/estree': 1.0.9 @@ -4926,6 +5109,8 @@ snapshots: transitivePeerDependencies: - supports-color + run-applescript@7.1.0: {} + safer-buffer@2.1.2: {} semver@6.3.1: {} @@ -5059,10 +5244,27 @@ snapshots: source-map-js@1.2.2: {} + source-map@0.8.0: {} + statuses@2.0.2: {} std-env@4.3.0: {} + string-width@7.2.0: + dependencies: + emoji-regex: 10.6.0 + get-east-asian-width: 1.7.0 + strip-ansi: 7.2.0 + + string-width@8.3.0: + dependencies: + get-east-asian-width: 1.7.0 + strip-ansi: 7.2.0 + + strip-ansi@7.2.0: + dependencies: + ansi-regex: 6.4.0 + sucrase@3.35.1: dependencies: '@jridgewell/gen-mapping': 0.3.13 @@ -5290,14 +5492,38 @@ snapshots: - bufferutil - utf-8-validate + wrap-ansi@9.0.2: + dependencies: + ansi-styles: 6.2.3 + string-width: 7.2.0 + strip-ansi: 7.2.0 + wrappy@1.0.2: {} ws@8.21.0: {} ws@8.22.0: {} + wsl-utils@1.0.1: + dependencies: + is-wsl: 3.1.1 + powershell-utils: 0.2.1 + + y18n@5.0.8: {} + yallist@3.1.1: {} + yargs-parser@22.0.0: {} + + yargs@18.2.0: + dependencies: + cliui: 9.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + string-width: 8.3.0 + y18n: 5.0.8 + yargs-parser: 22.0.0 + youch-core@0.3.3: dependencies: '@poppinss/exception': 1.2.3 diff --git a/scripts/bundle-report.sh b/scripts/bundle-report.sh new file mode 100755 index 00000000..0e29ba7e --- /dev/null +++ b/scripts/bundle-report.sh @@ -0,0 +1,168 @@ +#!/usr/bin/env bash +# Usage: pnpm bundle:report +# Builds the application into dist-report/ with rollup-plugin-visualizer enabled +# for the client environment, prints raw + gzip -9 asset sizes and top-20 entry +# chunk modules, and preserves .wrangler/deploy/config.json so subsequent +# wrangler deploy invocations never ship the report build. +set -euo pipefail + +WRANGLER_CONFIG=".wrangler/deploy/config.json" +WRANGLER_BACKUP=".wrangler/deploy/config.json.bak" +HAD_WRANGLER_CONFIG=0 + +if [[ -f "$WRANGLER_CONFIG" ]]; then + HAD_WRANGLER_CONFIG=1 + cp "$WRANGLER_CONFIG" "$WRANGLER_BACKUP" +fi + +cleanup() { + if [[ "$HAD_WRANGLER_CONFIG" -eq 1 ]]; then + if [[ -f "$WRANGLER_BACKUP" ]]; then + mkdir -p "$(dirname "$WRANGLER_CONFIG")" + mv "$WRANGLER_BACKUP" "$WRANGLER_CONFIG" + fi + else + rm -f "$WRANGLER_CONFIG" "$WRANGLER_BACKUP" + fi +} +trap cleanup EXIT + +BUNDLE_REPORT=1 VITE_SENTRY_DSN=https://public@o0.ingest.sentry.io/0 pnpm exec vite build --outDir dist-report + +node -e ' +const fs = require("node:fs"); +const path = require("node:path"); +const zlib = require("node:zlib"); + +const clientDir = path.join("dist-report", "client"); +if (!fs.existsSync(clientDir)) { + console.error("Missing client build directory:", clientDir); + process.exit(1); +} + +const files = []; +for (const sub of fs.readdirSync(clientDir, { withFileTypes: true })) { + if (!sub.isDirectory()) continue; + const subDir = path.join(clientDir, sub.name); + for (const entry of fs.readdirSync(subDir, { withFileTypes: true })) { + if (!entry.isFile()) continue; + if (!/^.+-[^/]+\.(js|css)$/.test(entry.name)) continue; + const relPath = path.posix.join(sub.name, entry.name); + const fullPath = path.join(subDir, entry.name); + const buf = fs.readFileSync(fullPath); + const rawBytes = buf.length; + const gzipBytes = zlib.gzipSync(buf, { level: 9 }).length; + files.push({ relPath, name: entry.name, ext: path.extname(entry.name), rawBytes, gzipBytes }); + } +} + +files.sort((a, b) => b.rawBytes - a.rawBytes); + +const fmtKb = (bytes) => `${(bytes / 1024).toFixed(2)} KB (${bytes} B)`; + +console.log("\n=== Client Hashed Assets (dist-report/client/*/*-*.{js,css}) ==="); +let totalJsRaw = 0; +let totalJsGzip = 0; +let totalCssRaw = 0; +let totalCssGzip = 0; +let entryAsset = null; + +for (const f of files) { + if (f.ext === ".js") { + totalJsRaw += f.rawBytes; + totalJsGzip += f.gzipBytes; + if (/^index-[^/]+\.js$/.test(f.name)) { + entryAsset = f; + } + } else if (f.ext === ".css") { + totalCssRaw += f.rawBytes; + totalCssGzip += f.gzipBytes; + } + console.log(`${f.relPath.padEnd(48)} raw: ${fmtKb(f.rawBytes).padEnd(22)} gzip-9: ${fmtKb(f.gzipBytes)}`); +} + +const htmlPath = path.join(clientDir, "index.html"); +const initialRelPaths = new Set(); +if (fs.existsSync(htmlPath)) { + const html = fs.readFileSync(htmlPath, "utf8"); + for (const token of html.split(/\s+/)) { + if (token.startsWith("src=") || token.startsWith("href=")) { + const firstQuote = token.indexOf("=") + 1; + const quoteChar = token[firstQuote]; + const endQuote = token.indexOf(quoteChar, firstQuote + 1); + if (endQuote > firstQuote) { + const val = token.slice(firstQuote + 1, endQuote).replace(/^\//, ""); + if (val.endsWith(".js")) initialRelPaths.add(val); + } + } + } +} + +console.log("\n=== Summary ==="); +if (entryAsset) { + console.log(`Entry JS (${entryAsset.relPath}): raw ${fmtKb(entryAsset.rawBytes)} | gzip-9 ${fmtKb(entryAsset.gzipBytes)}`); +} +const bootAssets = files.filter((f) => initialRelPaths.has(f.relPath) || (entryAsset && f.relPath === entryAsset.relPath)); +if (bootAssets.length > 1) { + const bootRaw = bootAssets.reduce((s, f) => s + f.rawBytes, 0); + const bootGzip = bootAssets.reduce((s, f) => s + f.gzipBytes, 0); + console.log(`Initial Boot JS (${bootAssets.map((f) => f.relPath).join(" + ")}): raw ${fmtKb(bootRaw)} | gzip-9 ${fmtKb(bootGzip)}`); +} +console.log(`Total JS: raw ${fmtKb(totalJsRaw)} | gzip-9 ${fmtKb(totalJsGzip)}`); +console.log(`Total CSS: raw ${fmtKb(totalCssRaw)} | gzip-9 ${fmtKb(totalCssGzip)}`); + +const statsPath = path.join("dist-report", "stats.json"); +if (!fs.existsSync(statsPath)) { + console.error("Missing visualizer stats file:", statsPath); + process.exit(1); +} + +const stats = JSON.parse(fs.readFileSync(statsPath, "utf8")); +const nodeMetas = Object.values(stats.nodeMetas || {}); +const nodeParts = stats.nodeParts || {}; + +const bundleIds = new Set(); +for (const meta of nodeMetas) { + for (const bId of Object.keys(meta.moduleParts || {})) { + bundleIds.add(bId); + } +} +const entryBundleId = [...bundleIds].find((id) => /(?:^|\/)index-[^/]+\.js$/.test(id)); +if (!entryBundleId) { + console.error("Could not find entry chunk (index-*.js) in stats.json bundleIds:", [...bundleIds]); + process.exit(1); +} + +const bootBundleIds = [...bundleIds].filter((id) => initialRelPaths.has(id) || id === entryBundleId); +const bootLabel = bootBundleIds.join(" + "); + +const entryModules = []; +let zodEntryBytes = 0; +const zodModules = []; + +for (const meta of nodeMetas) { + let renderedLength = 0; + for (const bId of bootBundleIds) { + const partUid = meta.moduleParts && meta.moduleParts[bId]; + if (!partUid) continue; + const part = nodeParts[partUid]; + if (part && part.renderedLength) renderedLength += part.renderedLength; + } + if (!renderedLength) continue; + entryModules.push({ id: meta.id, renderedLength }); + if (meta.id.includes("/node_modules/zod/") || meta.id.includes("/node_modules/.pnpm/zod@")) { + zodEntryBytes += renderedLength; + zodModules.push({ id: meta.id, renderedLength }); + } +} + +entryModules.sort((a, b) => b.renderedLength - a.renderedLength); + +console.log(`\n=== Top 20 Modules by Rendered Size in Entry/Boot Chunks (${bootLabel}) ===`); +for (const [idx, mod] of entryModules.slice(0, 20).entries()) { + console.log(`${String(idx + 1).padStart(2)}. ${fmtKb(mod.renderedLength).padEnd(22)} ${mod.id}`); +} + +console.log(`\n=== Entry/Boot Chunk Zod Breakdown (${bootLabel}) ===`); +console.log(`Total zod rendered in entry/boot chunks: ${fmtKb(zodEntryBytes)} across ${zodModules.length} module(s)`); +' diff --git a/vite.config.ts b/vite.config.ts index e84f78c5..51ee9c25 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -2,9 +2,25 @@ import { defineConfig } from "vite"; import solid from "vite-plugin-solid"; import tailwindcss from "@tailwindcss/vite"; import { cloudflare } from "@cloudflare/vite-plugin"; +import { visualizer } from "rollup-plugin-visualizer"; export default defineConfig({ - plugins: [solid(), tailwindcss(), cloudflare()], + plugins: [ + solid(), + tailwindcss(), + cloudflare(), + ...(process.env.BUNDLE_REPORT === "1" + ? [ + { + ...visualizer({ + template: "raw-data", + filename: "dist-report/stats.json", + }), + applyToEnvironment: (env: { name: string }) => env.name === "client", + }, + ] + : []), + ], build: { outDir: "dist", }, From 94869a191cd762773fdfe7466f5294bc70a76610 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 3 Nov 2026 07:00:33 -0500 Subject: [PATCH 2/6] perf(sentry): lazy-load the Sentry SDK behind a scrubbing capture facade --- src/app/App.tsx | 13 +- src/app/components/settings/SettingsPage.tsx | 8 +- src/app/index.tsx | 10 +- src/app/lib/sentry-facade.ts | 163 ++++++++++ src/app/lib/sentry-init.ts | 40 +++ src/app/lib/sentry.ts | 38 +-- src/app/pages/JiraCallback.tsx | 8 +- src/app/pages/LoginPage.tsx | 4 +- src/app/pages/OAuthCallback.tsx | 4 +- src/app/services/api.ts | 10 +- src/app/services/poll.ts | 10 +- src/app/stores/auth.ts | 6 +- src/app/stores/cache.ts | 4 +- .../steps/dependency-exclusions.steps.tsx | 6 +- tests/components/LoginPage.test.tsx | 6 +- .../settings/ApiUsageSection.test.tsx | 6 +- .../components/settings/JiraSection.test.tsx | 8 +- .../components/settings/SettingsPage.test.tsx | 6 +- .../settings/actions-toggle.test.tsx | 6 +- tests/lib/sentry-facade.test.ts | 300 ++++++++++++++++++ tests/lib/sentry.test.ts | 36 ++- tests/lib/settings-transfer.test.ts | 7 +- tests/services/api-dashboard-bodies.test.ts | 7 +- tests/services/api-dep-pr-bodies.test.ts | 7 +- tests/services/api.test.ts | 7 +- tests/services/events-poll.test.ts | 5 +- tests/services/hot-poll.test.ts | 21 +- tests/stores/cache.test.ts | 7 +- tests/validate-deploy-sync.test.ts | 2 + 29 files changed, 646 insertions(+), 109 deletions(-) create mode 100644 src/app/lib/sentry-facade.ts create mode 100644 src/app/lib/sentry-init.ts create mode 100644 tests/lib/sentry-facade.test.ts diff --git a/src/app/App.tsx b/src/app/App.tsx index 83651389..32270d87 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -1,5 +1,5 @@ import { createSignal, createEffect, on, onMount, onCleanup, Show, ErrorBoundary, Suspense, lazy, type JSX } from "solid-js"; -import * as Sentry from "@sentry/solid"; +import { reportBoundaryError } from "./lib/sentry-facade"; import { Router, Route, Navigate, useNavigate } from "@solidjs/router"; import { isAuthenticated, validateToken, AUTH_STORAGE_KEY } from "./stores/auth"; import { config, initConfigPersistence, resolveTheme } from "./stores/config"; @@ -33,8 +33,6 @@ const DashboardPage = lazyWithReload(() => import("./components/dashboard/Dashbo const OnboardingWizard = lazyWithReload(() => import("./components/onboarding/OnboardingWizard")); const SettingsPage = lazyWithReload(() => import("./components/settings/SettingsPage")); -const SentryErrorBoundary = Sentry.withSentryErrorBoundary(ErrorBoundary); - function handleRouteError(err: unknown) { console.error("[app] Route render failed:", err); return ; @@ -232,7 +230,12 @@ export default function App() { }); return ( - + { + reportBoundaryError(err); + return handleRouteError(err); + }} + > @@ -250,6 +253,6 @@ export default function App() { } /> - + ); } diff --git a/src/app/components/settings/SettingsPage.tsx b/src/app/components/settings/SettingsPage.tsx index dcf59b31..abfcbfb7 100644 --- a/src/app/components/settings/SettingsPage.tsx +++ b/src/app/components/settings/SettingsPage.tsx @@ -1,7 +1,7 @@ import { createSignal, createMemo, createEffect, Show, For, onCleanup, onMount } from "solid-js"; import { Select } from "@kobalte/core/select"; import { Dialog } from "@kobalte/core/dialog"; -import * as Sentry from "@sentry/solid"; +import { captureException } from "../../lib/sentry-facade"; import { getRelayStatus } from "../../lib/mcp-relay"; import { useNavigate } from "@solidjs/router"; import { config, setConfig, updateConfig, updateJiraConfig, updateJiraCustomFields, updateJiraCustomScopes, setMonitoredRepo, isActionsBasedTab } from "../../stores/config"; @@ -511,7 +511,7 @@ export default function SettingsPage() { pushNotification("pat-replace", "Token replaced successfully", "info"); } catch (err) { if (err instanceof DOMException && err.name === "AbortError") return; - Sentry.captureException(err, { tags: { source: "pat-replace" } }); + captureException(err, { tags: { source: "pat-replace" } }); setReplacePatError("Network error — please try again"); } finally { setReplaceSubmitting(false); @@ -733,7 +733,7 @@ export default function SettingsPage() { } catch (err) { const msg = err instanceof Error ? err.message : "Unknown error"; console.error("[jira-connect]", err); - Sentry.captureException(err, { tags: { source: "jira-api-token-connect" } }); + captureException(err, { tags: { source: "jira-api-token-connect" } }); setJiraApiError(`Connection failed: ${msg}`); } finally { setJiraApiConnecting(false); @@ -830,7 +830,7 @@ export default function SettingsPage() { pushNotification("jira-replace", "Jira API token replaced successfully", "info"); } catch (err) { if (err instanceof DOMException && err.name === "AbortError") return; - Sentry.captureException(err, { tags: { source: "jira-token-replace" } }); + captureException(err, { tags: { source: "jira-token-replace" } }); setReplaceJiraError("Connection failed — please try again."); } finally { setReplaceJiraSubmitting(false); diff --git a/src/app/index.tsx b/src/app/index.tsx index da9f83bd..4f3fc146 100644 --- a/src/app/index.tsx +++ b/src/app/index.tsx @@ -1,10 +1,12 @@ import "./index.css"; import { render } from "solid-js/web"; -import { initSentry } from "./lib/sentry"; +import { installEarlyErrorCapture, startSentryLoad } from "./lib/sentry-facade"; import App from "./App"; -// Initialize Sentry before rendering — captures errors from first paint. -// No-ops in dev/test (guarded by import.meta.env.DEV check). -initSentry(); +// Capture early errors synchronously before first paint, then lazy-load the +// Sentry SDK on idle after render. No-ops in dev/test or without DSN. +installEarlyErrorCapture(); render(() => , document.getElementById("app")!); + +startSentryLoad(); diff --git a/src/app/lib/sentry-facade.ts b/src/app/lib/sentry-facade.ts new file mode 100644 index 00000000..a94ca1d4 --- /dev/null +++ b/src/app/lib/sentry-facade.ts @@ -0,0 +1,163 @@ +import { scrubUrl } from "./sentry"; +import type { initSdk } from "./sentry-init"; + +export interface CaptureHint { + tags?: Record; + extra?: Record; + mechanism?: { handled: boolean; type: string }; +} + +interface QueuedCapture { + error: Error; + hint?: CaptureHint; +} + +const MAX_QUEUE_SIZE = 20; + +type SentrySdk = ReturnType; + +const queue: QueuedCapture[] = []; +let sdk: SentrySdk | null = null; +let loadStarted = false; +let loadErrorWarned = false; +let resetGeneration = 0; + +let onWindowError: ((event: ErrorEvent) => void) | null = null; +let onUnhandledRejection: ((event: PromiseRejectionEvent) => void) | null = null; +let scheduledIdleId: number | null = null; +let scheduledTimeoutId: ReturnType | null = null; + +function isSentryEnabled(): boolean { + const dsn = import.meta.env.VITE_SENTRY_DSN as string | undefined; + return !import.meta.env.DEV && Boolean(dsn); +} + +function scrubErrorForQueue(err: unknown): Error { + if (err instanceof Error) { + const copy = new Error(scrubUrl(err.message)); + copy.name = err.name; + if (typeof err.stack === "string") { + copy.stack = scrubUrl(err.stack); + } + return copy; + } + return new Error(scrubUrl(String(err))); +} + +function removeEarlyListeners(): void { + if (typeof window === "undefined") return; + if (onWindowError) { + window.removeEventListener("error", onWindowError); + onWindowError = null; + } + if (onUnhandledRejection) { + window.removeEventListener("unhandledrejection", onUnhandledRejection); + onUnhandledRejection = null; + } +} + +export function installEarlyErrorCapture(): void { + if (!isSentryEnabled() || sdk !== null || onWindowError !== null) return; + if (typeof window === "undefined") return; + + onWindowError = (event: ErrorEvent) => { + captureException(event.error ?? event.message); + }; + onUnhandledRejection = (event: PromiseRejectionEvent) => { + captureException(event.reason); + }; + + window.addEventListener("error", onWindowError); + window.addEventListener("unhandledrejection", onUnhandledRejection); +} + +export function startSentryLoad(): void { + if (!isSentryEnabled() || loadStarted) return; + loadStarted = true; + const myGeneration = resetGeneration; + + const load = () => { + scheduledIdleId = null; + scheduledTimeoutId = null; + if (myGeneration !== resetGeneration) return; + + void (async () => { + try { + const mod = await import("./sentry-init"); + if (myGeneration !== resetGeneration) return; + const initializedSdk = mod.initSdk(); + removeEarlyListeners(); + sdk = initializedSdk; + const pending = queue.splice(0); + for (const item of pending) { + initializedSdk.captureException( + item.error, + item.hint as Parameters[1], + ); + } + } catch (err: unknown) { + if (myGeneration !== resetGeneration) return; + removeEarlyListeners(); + if (!loadErrorWarned) { + loadErrorWarned = true; + console.warn("[app] Failed to load Sentry SDK:", err); + } + } + })(); + }; + + if (typeof window !== "undefined" && typeof window.requestIdleCallback === "function") { + scheduledIdleId = window.requestIdleCallback(load); + } else { + scheduledTimeoutId = setTimeout(load, 2000); + } +} + +export function captureException(err: unknown, hint?: CaptureHint): void { + if (!isSentryEnabled()) return; + + if (sdk !== null) { + sdk.captureException( + err, + hint as Parameters[1], + ); + return; + } + + const scrubbedError = scrubErrorForQueue(err); + if (queue.length >= MAX_QUEUE_SIZE) { + queue.shift(); + } + queue.push({ error: scrubbedError, hint }); +} + +export function reportBoundaryError(err: unknown): void { + captureException(err, { + mechanism: { handled: true, type: "auto.function.solid.error_boundary" }, + }); +} + +export function _resetSentryFacadeForTests(): void { + resetGeneration++; + removeEarlyListeners(); + if ( + scheduledIdleId !== null && + typeof window !== "undefined" && + typeof window.cancelIdleCallback === "function" + ) { + window.cancelIdleCallback(scheduledIdleId); + } + if (scheduledTimeoutId !== null) { + clearTimeout(scheduledTimeoutId); + } + scheduledIdleId = null; + scheduledTimeoutId = null; + sdk = null; + loadStarted = false; + loadErrorWarned = false; + queue.length = 0; +} + +export function _getSentryQueueForTests(): readonly QueuedCapture[] { + return queue; +} diff --git a/src/app/lib/sentry-init.ts b/src/app/lib/sentry-init.ts new file mode 100644 index 00000000..0d405e3b --- /dev/null +++ b/src/app/lib/sentry-init.ts @@ -0,0 +1,40 @@ +import * as Sentry from "@sentry/solid"; +import { beforeBreadcrumbHandler, beforeSendHandler } from "./sentry"; + +export function initSdk(): typeof Sentry { + const dsn = import.meta.env.VITE_SENTRY_DSN as string | undefined; + if (import.meta.env.DEV || !dsn) return Sentry; + + Sentry.init({ + dsn, + tunnel: "/api/error-reporting", + environment: import.meta.env.MODE, + enhanceFetchErrorMessages: "report-only", + + // ── Privacy: absolute minimum data ────────────────────────── + dataCollection: { + userInfo: false, + cookies: false, + httpHeaders: false, + httpBodies: [], + }, + + // ── Disable performance tracing (tracesSampleRate omitted = undefined = no spans) ─── + profileSessionSampleRate: 0, + + // ── Only capture errors from our own code ─────────────────── + allowUrls: [ + new RegExp( + `^${window.location.origin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[/\\?#])`, + ), + ], + + // ── Scrub sensitive data before it leaves the browser ──────── + beforeSend: beforeSendHandler, + beforeBreadcrumb: beforeBreadcrumbHandler, + }); + + return Sentry; +} + +export const initSentry = initSdk; diff --git a/src/app/lib/sentry.ts b/src/app/lib/sentry.ts index 54c4df42..cd5f5679 100644 --- a/src/app/lib/sentry.ts +++ b/src/app/lib/sentry.ts @@ -1,4 +1,3 @@ -import * as Sentry from "@sentry/solid"; import type { ErrorEvent, Breadcrumb } from "@sentry/solid"; /** Strip OAuth credentials and tokens from any captured URL or query string. */ @@ -7,13 +6,16 @@ export function scrubUrl(url: string): string { .replace(/code=[^&\s"]+/g, "code=[REDACTED]") .replace(/state=[^&\s"]+/g, "state=[REDACTED]") .replace(/access_token=[^&\s"]+/g, "access_token=[REDACTED]") + .replace(/\brefresh_token=[^&\s"]+/gi, "refresh_token=[REDACTED]") .replace(/client_secret=[^&\s"]+/gi, "client_secret=[REDACTED]") + .replace(/\b(sealed_[a-zA-Z0-9_]*)=[^&\s"]+/gi, "$1=[REDACTED]") + .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [REDACTED]") .replace(/\b(ghu_|ghp_|gho_|github_pat_)[A-Za-z0-9_]+/g, "$1[REDACTED]") .replace(/\bATATT[A-Za-z0-9_\-=]+/g, "ATATT[REDACTED]"); } /** Allowed console breadcrumb prefixes — drop everything else. */ -const ALLOWED_CONSOLE_PREFIXES = [ +export const ALLOWED_CONSOLE_PREFIXES = [ "[app]", "[auth]", "[api]", @@ -27,7 +29,7 @@ const ALLOWED_CONSOLE_PREFIXES = [ "[notifications]", ]; -const BACKGROUND_POLL_SOURCES = new Set([ +export const BACKGROUND_POLL_SOURCES = new Set([ "prEnrichment", "dashboardBodies", "depPRBodies", @@ -121,33 +123,3 @@ export function beforeBreadcrumbHandler( } return breadcrumb; } - -export function initSentry(): void { - const dsn = import.meta.env.VITE_SENTRY_DSN as string | undefined; - if (import.meta.env.DEV || !dsn) return; - - Sentry.init({ - dsn, - tunnel: "/api/error-reporting", - environment: import.meta.env.MODE, - enhanceFetchErrorMessages: "report-only", - - // ── Privacy: absolute minimum data ────────────────────────── - dataCollection: { - userInfo: false, - cookies: false, - httpHeaders: false, - httpBodies: [], - }, - - // ── Disable performance tracing (tracesSampleRate omitted = undefined = no spans) ─── - profileSessionSampleRate: 0, - - // ── Only capture errors from our own code ─────────────────── - allowUrls: [new RegExp(`^${window.location.origin.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[/\\?#])`)], - - // ── Scrub sensitive data before it leaves the browser ──────── - beforeSend: beforeSendHandler, - beforeBreadcrumb: beforeBreadcrumbHandler, - }); -} diff --git a/src/app/pages/JiraCallback.tsx b/src/app/pages/JiraCallback.tsx index 0d270d20..797fc0de 100644 --- a/src/app/pages/JiraCallback.tsx +++ b/src/app/pages/JiraCallback.tsx @@ -1,5 +1,5 @@ import { createSignal, onMount, Show, For } from "solid-js"; -import * as Sentry from "@sentry/solid"; +import { captureException } from "../lib/sentry-facade"; import { useNavigate } from "@solidjs/router"; import { z } from "zod"; import { setJiraAuth } from "../stores/auth"; @@ -101,7 +101,7 @@ export default function JiraCallback() { try { turnstileToken = await acquireTurnstileToken(import.meta.env.VITE_TURNSTILE_SITE_KEY as string ?? "", "jira-token"); } catch (err) { - Sentry.captureException(err, { tags: { source: "jira-callback-turnstile" } }); + captureException(err, { tags: { source: "jira-callback-turnstile" } }); setError("Human verification failed. Please try again."); return; } @@ -133,7 +133,7 @@ export default function JiraCallback() { } tokenData = tokenParsed.data; } catch (err) { - Sentry.captureException(err, { tags: { source: "jira-callback-token-exchange" } }); + captureException(err, { tags: { source: "jira-callback-token-exchange" } }); setError("A network error occurred. Please try again."); return; } @@ -149,7 +149,7 @@ export default function JiraCallback() { } resources = parsed.data; } catch (err) { - Sentry.captureException(err, { tags: { source: "jira-callback-site-discovery" } }); + captureException(err, { tags: { source: "jira-callback-site-discovery" } }); setError("Failed to discover Jira sites. Please try again."); return; } diff --git a/src/app/pages/LoginPage.tsx b/src/app/pages/LoginPage.tsx index 8e0caccf..4f91fc3d 100644 --- a/src/app/pages/LoginPage.tsx +++ b/src/app/pages/LoginPage.tsx @@ -1,5 +1,5 @@ import { createSignal, onMount, Show, Switch, Match } from "solid-js"; -import * as Sentry from "@sentry/solid"; +import { captureException } from "../lib/sentry-facade"; import { useNavigate } from "@solidjs/router"; import { setAuthFromPat, type GitHubUser } from "../stores/auth"; import { config } from "../stores/config"; @@ -85,7 +85,7 @@ export default function LoginPage() { setPatInput(""); navigate("/", { replace: true }); } catch (err) { - Sentry.captureException(err, { tags: { source: "pat-validation" } }); + captureException(err, { tags: { source: "pat-validation" } }); setPatError("Network error — please try again"); } finally { setSubmitting(false); diff --git a/src/app/pages/OAuthCallback.tsx b/src/app/pages/OAuthCallback.tsx index e9a4413d..9eb82f54 100644 --- a/src/app/pages/OAuthCallback.tsx +++ b/src/app/pages/OAuthCallback.tsx @@ -1,5 +1,5 @@ import { createSignal, onMount, Show } from "solid-js"; -import * as Sentry from "@sentry/solid"; +import { captureException } from "../lib/sentry-facade"; import { useNavigate } from "@solidjs/router"; import { setAuth, validateToken, clearAuth } from "../stores/auth"; import { OAUTH_STATE_KEY, OAUTH_RETURN_TO_KEY, sanitizeReturnTo } from "../lib/oauth"; @@ -66,7 +66,7 @@ export default function OAuthCallback() { sessionStorage.removeItem(OAUTH_RETURN_TO_KEY); navigate(sanitizeReturnTo(returnTo), { replace: true }); } catch (err) { - Sentry.captureException(err, { tags: { source: "oauth-callback" } }); + captureException(err, { tags: { source: "oauth-callback" } }); setError("A network error occurred. Please try again."); } }); diff --git a/src/app/services/api.ts b/src/app/services/api.ts index 1db03e24..e3def945 100644 --- a/src/app/services/api.ts +++ b/src/app/services/api.ts @@ -1,5 +1,5 @@ import { getClient, cachedRequest, updateGraphqlRateLimit } from "./github"; -import * as Sentry from "@sentry/solid"; +import { captureException } from "../lib/sentry-facade"; import { pushNotification, dismissNotificationBySource } from "../lib/errors"; import { deleteCacheEntry } from "../stores/cache"; import type { ApiCallSource } from "./api-usage"; @@ -1017,7 +1017,7 @@ async function executeLightCombinedQuery( for (const s of paginationSettled) { if (s.status === "rejected") { console.warn("[api] PR pagination task failed:", s.reason); - Sentry.captureException(s.reason, { tags: { source: "pr-pagination" } }); + captureException(s.reason, { tags: { source: "pr-pagination" } }); } } } @@ -1369,7 +1369,7 @@ export async function fetchPREnrichment( if (batchErrorPushed) return; batchErrorPushed = true; console.warn(`[api] PR enrichment batch ${batchLabel} failed:`, err); - Sentry.captureException(err, { tags: { source: "prEnrichment" } }); + captureException(err, { tags: { source: "prEnrichment" } }); errors.push({ repo: `${BACKFILL_ERROR_PREFIX}${batchLabel}`, statusCode, message, retryable }); }; @@ -1599,7 +1599,7 @@ async function fetchNodeBodiesBatched { await clearCache(); } catch (err) { console.warn("[auth] Cache clear failed during identity data clear:", err); - Sentry.captureException(err, { tags: { source: "auth-identity-data-cache-clear" } }); + captureException(err, { tags: { source: "auth-identity-data-cache-clear" } }); } await snapshotClear; } @@ -330,7 +330,7 @@ export function clearAuth(): void { // Clear IndexedDB cache and snapshot to prevent data leakage between users clearCache().catch((err) => { console.warn("[auth] Cache clear failed during logout:", err); - Sentry.captureException(err, { tags: { source: "auth-logout-cache-clear" } }); + captureException(err, { tags: { source: "auth-logout-cache-clear" } }); }); void clearSnapshotLogged(); // Run registered cleanup callbacks (e.g., poll state reset) diff --git a/src/app/stores/cache.ts b/src/app/stores/cache.ts index 750c32a6..c6767b7a 100644 --- a/src/app/stores/cache.ts +++ b/src/app/stores/cache.ts @@ -1,5 +1,5 @@ import { openDB, type IDBPDatabase } from "idb"; -import * as Sentry from "@sentry/solid"; +import { captureException } from "../lib/sentry-facade"; export interface CacheEntry { key: string; @@ -71,7 +71,7 @@ export async function setCacheEntry( await db.put("cache", entry); } catch (retryErr) { console.warn("[cache] Still over quota after emergency eviction — entry dropped"); - Sentry.captureException(retryErr, { tags: { source: "cache-eviction-retry" } }); + captureException(retryErr, { tags: { source: "cache-eviction-retry" } }); } } else { throw err; diff --git a/tests/acceptance/steps/dependency-exclusions.steps.tsx b/tests/acceptance/steps/dependency-exclusions.steps.tsx index ff18a8b2..644f0d91 100644 --- a/tests/acceptance/steps/dependency-exclusions.steps.tsx +++ b/tests/acceptance/steps/dependency-exclusions.steps.tsx @@ -60,9 +60,11 @@ vi.mock("../../../src/app/lib/dashboard-snapshot", () => ({ clearSnapshot: vi.fn().mockResolvedValue(undefined), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), - withSentryErrorBoundary: vi.fn((c: unknown) => c), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); vi.mock("../../../src/app/stores/cache", () => ({ diff --git a/tests/components/LoginPage.test.tsx b/tests/components/LoginPage.test.tsx index 42a91e1a..dbce42c5 100644 --- a/tests/components/LoginPage.test.tsx +++ b/tests/components/LoginPage.test.tsx @@ -40,9 +40,11 @@ vi.mock("../../src/app/stores/cache", () => ({ clearCache: vi.fn().mockResolvedValue(undefined), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), - withSentryErrorBoundary: vi.fn((c: unknown) => c), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); vi.mock("../../src/app/lib/pat", async (importOriginal) => { diff --git a/tests/components/settings/ApiUsageSection.test.tsx b/tests/components/settings/ApiUsageSection.test.tsx index 3dfacc24..47bb80db 100644 --- a/tests/components/settings/ApiUsageSection.test.tsx +++ b/tests/components/settings/ApiUsageSection.test.tsx @@ -56,9 +56,11 @@ vi.mock("../../../src/app/stores/auth", () => ({ onAuthCleared: vi.fn(), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), - withSentryErrorBoundary: vi.fn((c: unknown) => c), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); vi.mock("../../../src/app/stores/cache", () => ({ diff --git a/tests/components/settings/JiraSection.test.tsx b/tests/components/settings/JiraSection.test.tsx index 3cf2ec58..ee8a97da 100644 --- a/tests/components/settings/JiraSection.test.tsx +++ b/tests/components/settings/JiraSection.test.tsx @@ -176,13 +176,15 @@ vi.mock("../../../src/app/services/jira-keys", () => ({ clearJiraKeyCache: vi.fn(), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), - withSentryErrorBoundary: vi.fn((c: unknown) => c), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); // Component imports after all mocks -import * as Sentry from "@sentry/solid"; +import * as Sentry from "../../../src/app/lib/sentry-facade"; import SettingsPage, { staleJiraScopeReset } from "../../../src/app/components/settings/SettingsPage"; import { viewState, setTabFilter } from "../../../src/app/stores/view"; import { pushNotification, dismissNotificationBySource } from "../../../src/app/lib/errors"; diff --git a/tests/components/settings/SettingsPage.test.tsx b/tests/components/settings/SettingsPage.test.tsx index ebab9853..1778fbf3 100644 --- a/tests/components/settings/SettingsPage.test.tsx +++ b/tests/components/settings/SettingsPage.test.tsx @@ -54,9 +54,11 @@ vi.mock("../../../src/app/lib/proxy", () => ({ unsealCredentialBundle: vi.fn(), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), - withSentryErrorBoundary: vi.fn((c: unknown) => c), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); vi.mock("../../../src/app/stores/cache", () => ({ diff --git a/tests/components/settings/actions-toggle.test.tsx b/tests/components/settings/actions-toggle.test.tsx index f8e2f427..0e782982 100644 --- a/tests/components/settings/actions-toggle.test.tsx +++ b/tests/components/settings/actions-toggle.test.tsx @@ -34,9 +34,11 @@ vi.mock("../../../src/app/stores/auth", () => ({ onAuthCleared: vi.fn(), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), - withSentryErrorBoundary: vi.fn((c: unknown) => c), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); vi.mock("../../../src/app/stores/cache", () => ({ diff --git a/tests/lib/sentry-facade.test.ts b/tests/lib/sentry-facade.test.ts new file mode 100644 index 00000000..b4c77dc5 --- /dev/null +++ b/tests/lib/sentry-facade.test.ts @@ -0,0 +1,300 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { beforeSendHandler } from "../../src/app/lib/sentry"; +import { + installEarlyErrorCapture, + startSentryLoad, + captureException, + reportBoundaryError, + _resetSentryFacadeForTests, + _getSentryQueueForTests, +} from "../../src/app/lib/sentry-facade"; + +const mockSentryInit = vi.fn(); +const mockSentryCaptureException = vi.fn(); + +vi.mock("@sentry/solid", () => ({ + init: (...args: unknown[]) => mockSentryInit(...args), + captureException: (...args: unknown[]) => mockSentryCaptureException(...args), +})); + +let shouldFailSentryInitImport = false; +vi.mock("../../src/app/lib/sentry-init", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + initSdk: vi.fn(() => { + if (shouldFailSentryInitImport) { + throw new Error("ChunkLoadError: Loading chunk sentry-init failed"); + } + return actual.initSdk(); + }), + }; +}); + +describe("sentry-facade", () => { + beforeEach(() => { + _resetSentryFacadeForTests(); + mockSentryInit.mockClear(); + mockSentryCaptureException.mockClear(); + shouldFailSentryInitImport = false; + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.useRealTimers(); + }); + + afterEach(() => { + _resetSentryFacadeForTests(); + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.useRealTimers(); + }); + + it("is a no-op when gate is off (DEV=true or missing VITE_SENTRY_DSN)", () => { + // Case 1: DEV=true even with DSN set + vi.stubEnv("DEV", true); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + + const addListenerSpy = vi.spyOn(window, "addEventListener"); + installEarlyErrorCapture(); + captureException(new Error("boom with ghp_secret123")); + startSentryLoad(); + + expect(addListenerSpy).not.toHaveBeenCalledWith("error", expect.any(Function)); + expect(_getSentryQueueForTests()).toHaveLength(0); + expect(mockSentryInit).not.toHaveBeenCalled(); + + // Case 2: DEV=false but DSN empty + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", ""); + installEarlyErrorCapture(); + captureException(new Error("boom")); + startSentryLoad(); + + expect(_getSentryQueueForTests()).toHaveLength(0); + expect(mockSentryInit).not.toHaveBeenCalled(); + addListenerSpy.mockRestore(); + }); + + it("scrubs error message and stack at enqueue time before SDK init", () => { + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + + const rawErr = new TypeError( + "Request failed with ghp_supersecrettoken123 and Bearer my_jwt_token_abc", + ); + rawErr.stack = + "TypeError: Request failed with ghp_supersecrettoken123\n at fetch (https://gh.gordoncode.dev/cb?code=oauth_code_1&refresh_token=rt_secret_2&sealed_refresh_token=sealed_val_3:10:5)"; + + captureException(rawErr, { tags: { source: "pat-validation" } }); + + const queue = _getSentryQueueForTests(); + expect(queue).toHaveLength(1); + const queued = queue[0]; + expect(queued.error).not.toBe(rawErr); + expect(queued.error.name).toBe("TypeError"); + expect(queued.error.message).toBe( + "Request failed with ghp_[REDACTED] and Bearer [REDACTED]", + ); + expect(queued.error.message).not.toContain("supersecrettoken123"); + expect(queued.error.message).not.toContain("my_jwt_token_abc"); + expect(queued.error.stack).toContain("ghp_[REDACTED]"); + expect(queued.error.stack).toContain("code=[REDACTED]"); + expect(queued.error.stack).toContain("refresh_token=[REDACTED]"); + expect(queued.error.stack).toContain("sealed_refresh_token=[REDACTED]"); + expect(queued.hint).toEqual({ tags: { source: "pat-validation" } }); + + // Non-Error values are also converted to scrubbed Error instances + captureException("raw string failure with ghu_secret999"); + expect(queue[1].error.message).toBe("raw string failure with ghu_[REDACTED]"); + }); + + it("caps the pre-init queue at 20 entries, dropping the oldest", () => { + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + + for (let i = 1; i <= 25; i++) { + captureException(new Error(`error-${i}`), { tags: { seq: String(i) } }); + } + + const queue = _getSentryQueueForTests(); + expect(queue).toHaveLength(20); + expect(queue[0].error.message).toBe("error-6"); + expect(queue[19].error.message).toBe("error-25"); + }); + + it("drains pre-init queue in FIFO order after idle load and forwards subsequent captures directly", async () => { + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + + let idleCb: (() => void) | null = null; + vi.stubGlobal("requestIdleCallback", vi.fn((cb: () => void) => { + idleCb = cb; + return 1; + })); + + captureException(new Error("first ghp_tok1"), { tags: { order: "1" } }); + captureException(new Error("second ghp_tok2"), { tags: { order: "2" } }); + + startSentryLoad(); + expect(idleCb).not.toBeNull(); + idleCb!(); + + await vi.waitFor(() => { + expect(mockSentryInit).toHaveBeenCalledOnce(); + expect(mockSentryCaptureException).toHaveBeenCalledTimes(2); + }); + + expect(_getSentryQueueForTests()).toHaveLength(0); + expect((mockSentryCaptureException.mock.calls[0][0] as Error).message).toBe( + "first ghp_[REDACTED]", + ); + expect(mockSentryCaptureException.mock.calls[0][1]).toEqual({ + tags: { order: "1" }, + }); + expect((mockSentryCaptureException.mock.calls[1][0] as Error).message).toBe( + "second ghp_[REDACTED]", + ); + expect(mockSentryCaptureException.mock.calls[1][1]).toEqual({ + tags: { order: "2" }, + }); + + // Subsequent capture after init forwards directly without queueing + const postInitErr = new Error("post-init error"); + captureException(postInitErr, { tags: { order: "3" } }); + expect(_getSentryQueueForTests()).toHaveLength(0); + expect(mockSentryCaptureException).toHaveBeenCalledTimes(3); + expect(mockSentryCaptureException.mock.calls[2][0]).toBe(postInitErr); + expect(mockSentryCaptureException.mock.calls[2][1]).toEqual({ + tags: { order: "3" }, + }); + }); + + it("forwards mechanism from reportBoundaryError", async () => { + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + vi.useFakeTimers(); + + const boundaryErr = new Error("route render crash"); + reportBoundaryError(boundaryErr); + + startSentryLoad(); + vi.advanceTimersByTime(2000); + + await vi.waitFor(() => { + expect(mockSentryCaptureException).toHaveBeenCalledOnce(); + }); + + expect(mockSentryCaptureException).toHaveBeenCalledWith( + expect.objectContaining({ message: "route render crash" }), + { + mechanism: { + handled: true, + type: "auto.function.solid.error_boundary", + }, + }, + ); + }); + + it("preserves tags.source on drained pre-init captures so beforeSendHandler drops background poll fetch disconnects", async () => { + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + vi.useFakeTimers(); + + captureException(new TypeError("Failed to fetch"), { + tags: { source: "poll-cycle" }, + }); + + startSentryLoad(); + vi.advanceTimersByTime(2000); + + await vi.waitFor(() => { + expect(mockSentryCaptureException).toHaveBeenCalledOnce(); + }); + + const [drainedErr, drainedHint] = mockSentryCaptureException.mock.calls[0] as [ + Error, + { tags?: Record }, + ]; + expect(drainedHint).toEqual({ tags: { source: "poll-cycle" } }); + + // Simulate Sentry constructing the ErrorEvent with the forwarded hint tags + const simulatedEvent = { + tags: drainedHint.tags, + exception: { + values: [{ type: drainedErr.name, value: drainedErr.message }], + }, + }; + expect(beforeSendHandler(simulatedEvent as never)).toBeNull(); + }); + + it("enqueues synchronous window error and unhandledrejection events fired before startSentryLoad and removes listeners after init", async () => { + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + vi.useFakeTimers(); + + const removeSpy = vi.spyOn(window, "removeEventListener"); + installEarlyErrorCapture(); + // Calling twice is idempotent + installEarlyErrorCapture(); + + const earlyErr = new Error("early window error ghp_secret1"); + window.dispatchEvent(new ErrorEvent("error", { error: earlyErr, message: earlyErr.message })); + + const rejectionEvent = new Event("unhandledrejection") as PromiseRejectionEvent; + Object.defineProperty(rejectionEvent, "reason", { + value: new Error("early unhandled rejection gho_secret2"), + }); + window.dispatchEvent(rejectionEvent); + + expect(_getSentryQueueForTests()).toHaveLength(2); + expect(_getSentryQueueForTests()[0].error.message).toBe( + "early window error ghp_[REDACTED]", + ); + expect(_getSentryQueueForTests()[1].error.message).toBe( + "early unhandled rejection gho_[REDACTED]", + ); + + startSentryLoad(); + vi.advanceTimersByTime(2000); + + await vi.waitFor(() => { + expect(mockSentryCaptureException).toHaveBeenCalledTimes(2); + }); + + expect(removeSpy).toHaveBeenCalledWith("error", expect.any(Function)); + expect(removeSpy).toHaveBeenCalledWith("unhandledrejection", expect.any(Function)); + removeSpy.mockRestore(); + }); + + it("handles sentry-init failure gracefully by warning once and never throwing", async () => { + vi.stubEnv("DEV", false); + vi.stubEnv("VITE_SENTRY_DSN", "https://key@o1.ingest.us.sentry.io/1"); + vi.useFakeTimers(); + + shouldFailSentryInitImport = true; + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + + installEarlyErrorCapture(); + captureException(new Error("queued before failed load")); + startSentryLoad(); + vi.advanceTimersByTime(2000); + + await vi.waitFor(() => { + expect(warnSpy).toHaveBeenCalledOnce(); + }); + + expect(warnSpy).toHaveBeenCalledWith( + "[app] Failed to load Sentry SDK:", + expect.any(Error), + ); + expect(mockSentryCaptureException).not.toHaveBeenCalled(); + + // Queue remains capped at 20 even if more errors arrive after failed load + for (let i = 0; i < 30; i++) { + captureException(new Error(`post-fail-${i}`)); + } + expect(_getSentryQueueForTests()).toHaveLength(20); + + warnSpy.mockRestore(); + }); +}); diff --git a/tests/lib/sentry.test.ts b/tests/lib/sentry.test.ts index 3e322d0e..5735c482 100644 --- a/tests/lib/sentry.test.ts +++ b/tests/lib/sentry.test.ts @@ -3,8 +3,8 @@ import { scrubUrl, beforeSendHandler, beforeBreadcrumbHandler, - initSentry, } from "../../src/app/lib/sentry"; +import { initSdk } from "../../src/app/lib/sentry-init"; vi.mock("@sentry/solid", () => ({ init: vi.fn(), @@ -74,6 +74,30 @@ describe("scrubUrl", () => { "Error: token ATATT[REDACTED] exposed", ); }); + + it("strips refresh_token= parameter case-insensitively", () => { + expect( + scrubUrl("https://example.com/oauth?refresh_token=rt_secret123&REFRESH_TOKEN=rt_upper456&other=ok"), + ).toBe( + "https://example.com/oauth?refresh_token=[REDACTED]&refresh_token=[REDACTED]&other=ok", + ); + }); + + it("strips sealed_*= query and body parameters while preserving the parameter name", () => { + expect( + scrubUrl("https://example.com/cb?sealed_refresh_token=enc123&sealed_bundle=enc456&sealed_token=enc789&safe=1"), + ).toBe( + "https://example.com/cb?sealed_refresh_token=[REDACTED]&sealed_bundle=[REDACTED]&sealed_token=[REDACTED]&safe=1", + ); + }); + + it("strips Bearer substrings case-insensitively", () => { + expect( + scrubUrl("Authorization header failed: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.abc-123_def+/= and bearer secret_tok_99"), + ).toBe( + "Authorization header failed: Bearer [REDACTED] and Bearer [REDACTED]", + ); + }); }); describe("beforeSendHandler", () => { @@ -419,7 +443,7 @@ describe("beforeBreadcrumbHandler", () => { }); }); -describe("initSentry", () => { +describe("initSdk", () => { // Import the mock so we can inspect calls let mockInit: ReturnType; @@ -439,21 +463,21 @@ describe("initSentry", () => { it("is a no-op when VITE_SENTRY_DSN is undefined", () => { vi.stubEnv("DEV", false); // Do not stub VITE_SENTRY_DSN — beforeEach calls vi.unstubAllEnvs() so it is truly undefined - initSentry(); + initSdk(); expect(mockInit).not.toHaveBeenCalled(); }); it("is a no-op when VITE_SENTRY_DSN is empty string", () => { vi.stubEnv("DEV", false); vi.stubEnv("VITE_SENTRY_DSN", ""); - initSentry(); + initSdk(); expect(mockInit).not.toHaveBeenCalled(); }); it("calls Sentry.init with correct DSN and enhanceFetchErrorMessages: 'report-only' when VITE_SENTRY_DSN is set", () => { vi.stubEnv("DEV", false); vi.stubEnv("VITE_SENTRY_DSN", "https://test-key@o1.ingest.us.sentry.io/1"); - initSentry(); + initSdk(); expect(mockInit).toHaveBeenCalledOnce(); expect(mockInit).toHaveBeenCalledWith( expect.objectContaining({ @@ -467,7 +491,7 @@ describe("initSentry", () => { vi.stubEnv("DEV", false); vi.stubEnv("VITE_SENTRY_DSN", "https://test-key@o1.ingest.us.sentry.io/1"); vi.stubGlobal("location", { origin: "https://test.example.com" }); - initSentry(); + initSdk(); const [config] = mockInit.mock.calls[0] as [{ allowUrls: RegExp[] }]; expect(config.allowUrls).toHaveLength(1); expect(config.allowUrls[0]).toBeInstanceOf(RegExp); diff --git a/tests/lib/settings-transfer.test.ts b/tests/lib/settings-transfer.test.ts index f8ad5548..7f19dfa0 100644 --- a/tests/lib/settings-transfer.test.ts +++ b/tests/lib/settings-transfer.test.ts @@ -12,10 +12,11 @@ vi.mock("../../src/app/lib/dashboard-snapshot", () => ({ writeSnapshot: vi.fn(), flushSnapshot: vi.fn().mockResolvedValue(undefined), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), - captureMessage: vi.fn(), - withSentryErrorBoundary: vi.fn((c: unknown) => c), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); import { ConfigSchema, JiraConfigSchema } from "../../src/shared/schemas"; diff --git a/tests/services/api-dashboard-bodies.test.ts b/tests/services/api-dashboard-bodies.test.ts index b94e5662..f2a14ac9 100644 --- a/tests/services/api-dashboard-bodies.test.ts +++ b/tests/services/api-dashboard-bodies.test.ts @@ -12,7 +12,7 @@ import { } from "../../src/app/services/api"; import { getClient } from "../../src/app/services/github"; import { pushNotification, dismissNotificationBySource } from "../../src/app/lib/errors"; -import { captureException } from "@sentry/solid"; +import { captureException } from "../../src/app/lib/sentry-facade"; // ── Mocks ───────────────────────────────────────────────────────────────────── @@ -41,8 +41,11 @@ vi.mock("../../src/app/lib/errors", () => ({ isMuted: vi.fn(() => false), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); // ── Helpers ─────────────────────────────────────────────────────────────────── diff --git a/tests/services/api-dep-pr-bodies.test.ts b/tests/services/api-dep-pr-bodies.test.ts index 087f062d..0042d18d 100644 --- a/tests/services/api-dep-pr-bodies.test.ts +++ b/tests/services/api-dep-pr-bodies.test.ts @@ -11,7 +11,7 @@ import { } from "../../src/app/services/api"; import { getClient } from "../../src/app/services/github"; import { pushNotification, dismissNotificationBySource } from "../../src/app/lib/errors"; -import { captureException } from "@sentry/solid"; +import { captureException } from "../../src/app/lib/sentry-facade"; const mockUpdateGraphqlRateLimit = vi.fn(); vi.mock("../../src/app/services/github", () => ({ @@ -37,8 +37,11 @@ vi.mock("../../src/app/lib/errors", () => ({ isMuted: vi.fn(() => false), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); const NODES_BATCH_SIZE = BODY_FETCH_BATCH_SIZE; diff --git a/tests/services/api.test.ts b/tests/services/api.test.ts index e25b5d7d..17175632 100644 --- a/tests/services/api.test.ts +++ b/tests/services/api.test.ts @@ -1,6 +1,6 @@ import "fake-indexeddb/auto"; import { describe, it, expect, vi, beforeEach } from "vitest"; -import * as Sentry from "@sentry/solid"; +import * as Sentry from "../../src/app/lib/sentry-facade"; import { fetchOrgs, fetchRepos, @@ -35,8 +35,11 @@ import orgsFixture from "../fixtures/github-orgs.json"; import reposFixture from "../fixtures/github-repos.json"; import runsFixture from "../fixtures/github-runs.json"; -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); vi.mock("../../src/app/lib/errors", () => ({ diff --git a/tests/services/events-poll.test.ts b/tests/services/events-poll.test.ts index ff3f57af..b4c38b9a 100644 --- a/tests/services/events-poll.test.ts +++ b/tests/services/events-poll.test.ts @@ -90,8 +90,11 @@ vi.mock("../../src/app/services/api-usage", () => ({ checkAndResetIfExpired: vi.fn(), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); // Import AFTER mocks diff --git a/tests/services/hot-poll.test.ts b/tests/services/hot-poll.test.ts index c456d9a9..f9d0de79 100644 --- a/tests/services/hot-poll.test.ts +++ b/tests/services/hot-poll.test.ts @@ -64,8 +64,11 @@ vi.mock("../../src/app/lib/notifications", () => ({ _resetNotificationState: vi.fn(), })); -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); vi.mock("../../src/app/stores/config", () => ({ @@ -1066,7 +1069,7 @@ describe("createHotPollCoordinator", () => { pullRequests: [makePullRequest({ id: 1, checkStatus: "running", enriched: true, nodeId: "PR_a" })], }); - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); await createRoot(async (dispose) => { @@ -1544,7 +1547,7 @@ describe("fetchHotPRStatus edge cases", () => { }); it("does not report to Sentry when reportToSentry option is omitted", async () => { - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); const octokit = makeOctokit(undefined, () => Promise.reject(new Error("api error"))); @@ -1554,7 +1557,7 @@ describe("fetchHotPRStatus edge cases", () => { }); it("does not report to Sentry when reportToSentry is false", async () => { - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); const octokit = makeOctokit(undefined, () => Promise.reject(new Error("api error"))); @@ -1564,7 +1567,7 @@ describe("fetchHotPRStatus edge cases", () => { }); it("reports to Sentry when reportToSentry is true", async () => { - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); const error = new Error("api error"); const octokit = makeOctokit(undefined, () => Promise.reject(error)); @@ -2138,7 +2141,7 @@ describe("fetchHotData hadErrors", () => { }); it("does not report PR fetch failure to Sentry below HOT_POLL_SENTRY_THRESHOLD", async () => { - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); const octokit = makeOctokit(undefined, () => Promise.reject(new Error("graphql error"))); mockGetClient.mockReturnValue(octokit); @@ -2154,7 +2157,7 @@ describe("fetchHotData hadErrors", () => { }); it("reports PR fetch failure to Sentry once priorConsecutiveFailures reaches HOT_POLL_SENTRY_THRESHOLD", async () => { - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); const octokit = makeOctokit(undefined, () => Promise.reject(new Error("graphql error"))); mockGetClient.mockReturnValue(octokit); @@ -2173,7 +2176,7 @@ describe("fetchHotData hadErrors", () => { }); it("does not report run fetch failure to Sentry below HOT_POLL_SENTRY_THRESHOLD", async () => { - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); const octokit = makeOctokit( () => Promise.reject(new Error("network error")), @@ -2192,7 +2195,7 @@ describe("fetchHotData hadErrors", () => { }); it("reports run fetch failure to Sentry once priorConsecutiveFailures reaches HOT_POLL_SENTRY_THRESHOLD", async () => { - const Sentry = await import("@sentry/solid"); + const Sentry = await import("../../src/app/lib/sentry-facade"); (Sentry.captureException as ReturnType).mockClear(); const octokit = makeOctokit( () => Promise.reject(new Error("network error")), diff --git a/tests/stores/cache.test.ts b/tests/stores/cache.test.ts index 6cb2ee0b..89687fc0 100644 --- a/tests/stores/cache.test.ts +++ b/tests/stores/cache.test.ts @@ -1,6 +1,6 @@ import "fake-indexeddb/auto"; import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; -import { captureException } from "@sentry/solid"; +import { captureException } from "../../src/app/lib/sentry-facade"; import { getDb, getCacheEntry, @@ -17,8 +17,11 @@ import { type RawWorkflowRunsResponse, } from "../../src/app/services/api"; -vi.mock("@sentry/solid", () => ({ +vi.mock("../../src/app/lib/sentry-facade", () => ({ captureException: vi.fn(), + reportBoundaryError: vi.fn(), + installEarlyErrorCapture: vi.fn(), + startSentryLoad: vi.fn(), })); // Reset the DB singleton between tests by closing and clearing diff --git a/tests/validate-deploy-sync.test.ts b/tests/validate-deploy-sync.test.ts index da9af9e7..e311eca8 100644 --- a/tests/validate-deploy-sync.test.ts +++ b/tests/validate-deploy-sync.test.ts @@ -157,6 +157,8 @@ describe("validate-deploy.sh stays in sync with Env interfaces", () => { const viteFiles = [ "src/app/lib/oauth.ts", "src/app/lib/sentry.ts", + "src/app/lib/sentry-facade.ts", + "src/app/lib/sentry-init.ts", "src/app/lib/proxy.ts", ]; const viteVars = new Set(); From 4def4312b639c152d2222c8bfe0f78c513cc2149 Mon Sep 17 00:00:00 2001 From: Will Gordon Date: Tue, 3 Nov 2026 07:27:41 -0500 Subject: [PATCH 3/6] perf(bundle): defer authenticated-only modules, lazy emoji map and custom tab modal --- mcp/src/index.ts | 8 +- src/app/App.tsx | 32 ++- .../components/dashboard/DashboardPage.tsx | 32 ++- .../components/settings/CustomTabsSection.tsx | 27 ++- src/app/lib/emoji.ts | 34 ++- src/app/lib/use-credential-import.ts | 6 +- src/app/pages/JiraCallback.tsx | 4 +- src/app/pages/LoginPage.tsx | 42 ++-- src/app/services/github.ts | 48 ++-- src/app/stores/auth.ts | 12 +- src/app/stores/config.ts | 4 +- src/app/stores/view.ts | 218 ++++++++++-------- src/shared/schemas.ts | 129 ++++++----- tests/app/cache-eviction.test.tsx | 16 +- tests/app/login-lean.test.tsx | 157 +++++++++++++ tests/components/App.test.tsx | 34 ++- tests/components/ItemRow.test.tsx | 20 ++ tests/components/LoginPage.test.tsx | 21 -- .../settings/CustomTabsSection.test.tsx | 46 ++-- tests/lib/emoji.test.ts | 33 ++- tests/lib/settings-transfer.test.ts | 3 +- tests/services/github.test.ts | 76 +++++- tests/stores/view-jira-order.test.ts | 3 +- 23 files changed, 684 insertions(+), 321 deletions(-) create mode 100644 tests/app/login-lean.test.tsx diff --git a/mcp/src/index.ts b/mcp/src/index.ts index 8c3ba279..e8711792 100644 --- a/mcp/src/index.ts +++ b/mcp/src/index.ts @@ -30,10 +30,10 @@ const MAX_TRACKED_USERS = 10; const MAX_MONITORED_REPOS = 10; const ConfigUpdatePayloadSchema = z.object({ - selectedRepos: RepoRefSchema.array().max(MAX_REPOS).default([]), - trackedUsers: TrackedUserSchema.array().max(MAX_TRACKED_USERS).default([]), - upstreamRepos: RepoRefSchema.array().max(MAX_REPOS).default([]), - monitoredRepos: RepoRefSchema.array().max(MAX_MONITORED_REPOS).default([]), + selectedRepos: z.array(RepoRefSchema).max(MAX_REPOS).default([]), + trackedUsers: z.array(TrackedUserSchema).max(MAX_TRACKED_USERS).default([]), + upstreamRepos: z.array(RepoRefSchema).max(MAX_REPOS).default([]), + monitoredRepos: z.array(RepoRefSchema).max(MAX_MONITORED_REPOS).default([]), enableActions: z.boolean().default(true), }); diff --git a/src/app/App.tsx b/src/app/App.tsx index 32270d87..4174409b 100644 --- a/src/app/App.tsx +++ b/src/app/App.tsx @@ -1,17 +1,22 @@ -import { createSignal, createEffect, on, onMount, onCleanup, Show, ErrorBoundary, Suspense, lazy, type JSX } from "solid-js"; +import { createSignal, createEffect, on, onMount, onCleanup, getOwner, runWithOwner, Show, ErrorBoundary, Suspense, lazy, type JSX } from "solid-js"; import { reportBoundaryError } from "./lib/sentry-facade"; import { Router, Route, Navigate, useNavigate } from "@solidjs/router"; import { isAuthenticated, validateToken, AUTH_STORAGE_KEY } from "./stores/auth"; import { config, initConfigPersistence, resolveTheme } from "./stores/config"; import { initViewPersistence, pruneStaleIgnoredItems } from "./stores/view"; import { evictStaleEntries, evictKeysWithPrefix } from "./stores/cache"; -import { initClientWatcher } from "./services/github"; -import { initMcpRelay } from "./lib/mcp-relay"; import LoginPage from "./pages/LoginPage"; import OAuthCallback from "./pages/OAuthCallback"; import JiraCallback from "./pages/JiraCallback"; import PrivacyPage from "./pages/PrivacyPage"; +let authInitStarted = false; + +/** @internal Test-only reset helper for authInitStarted across App renders */ +export function _resetAuthInitStartedForTests(): void { + authInitStarted = false; +} + const CHUNK_RELOAD_KEY = "github-tracker:chunk-reload"; const CHUNK_RELOAD_MAX_AGE = 10_000; @@ -163,6 +168,25 @@ function RootRedirect() { } export default function App() { + const appOwner = getOwner(); + + createEffect( + on(isAuthenticated, (authed) => { + if (!authed || authInitStarted) return; + authInitStarted = true; + void Promise.all([import("./services/github"), import("./lib/mcp-relay")]) + .then(([gh, relay]) => + runWithOwner(appOwner, () => { + gh.initClientWatcher(); + relay.initMcpRelay(); + }), + ) + .catch(() => { + // Non-fatal — dynamic import failure or test environment teardown + }); + }), + ); + createEffect(() => { document.documentElement.setAttribute("data-theme", resolveTheme(config.theme)); }); @@ -202,8 +226,6 @@ export default function App() { // All reactive init functions must be called inside the component tree initConfigPersistence(); initViewPersistence(); - initClientWatcher(); - initMcpRelay(); pruneStaleIgnoredItems(); const staleCacheMaxAgeMs = 24 * 60 * 60 * 1000; diff --git a/src/app/components/dashboard/DashboardPage.tsx b/src/app/components/dashboard/DashboardPage.tsx index 8413975b..0e926a1b 100644 --- a/src/app/components/dashboard/DashboardPage.tsx +++ b/src/app/components/dashboard/DashboardPage.tsx @@ -1,4 +1,4 @@ -import { batch, createSignal, createMemo, createEffect, on, Show, Switch, Match, onMount, onCleanup, untrack } from "solid-js"; +import { batch, createSignal, createMemo, createEffect, on, Show, Switch, Match, Suspense, lazy, onMount, onCleanup, untrack } from "solid-js"; import { createStore, produce, reconcile, unwrap } from "solid-js/store"; import { z } from "zod"; import Header from "../layout/Header"; @@ -49,10 +49,12 @@ import { Tooltip } from "../shared/Tooltip"; import { isIssueVisible, isPrVisible, isRunVisible, matchesActionsConclusionFilter } from "../../lib/filters"; import { isUserInvolved } from "../../lib/grouping"; import { KNOWN_CONCLUSIONS, KNOWN_EVENTS } from "../shared/filterTypes"; -import CustomTabModal from "../shared/CustomTabModal"; +import { loadEmojiMap } from "../../lib/emoji"; import { mergeActiveFilters } from "../../lib/tabFilters"; import type { CustomTab } from "../../stores/config"; +const CustomTabModal = lazy(() => import("../shared/CustomTabModal")); + // Hoisted to module scope — these are constant values (Zod schema defaults). const ISSUE_FILTER_DEFAULTS = IssueFiltersSchema.parse({}); const PR_FILTER_DEFAULTS = PullRequestFiltersSchema.parse({}); @@ -883,6 +885,10 @@ export default function DashboardPage() { const [clockTick, setClockTick] = createSignal(0); const [showCustomTabModal, setShowCustomTabModal] = createSignal(false); + const [customTabModalEverOpened, setCustomTabModalEverOpened] = createSignal(false); + createEffect(() => { + if (showCustomTabModal()) setCustomTabModalEverOpened(true); + }); const [editingTabId, setEditingTabId] = createSignal(null); const editingTab = createMemo(() => { const id = editingTabId(); @@ -974,6 +980,8 @@ export default function DashboardPage() { }); onMount(() => { + void loadEmojiMap(); + if ( !realDataCommitted && dashboardData.issues.length === 0 && @@ -2112,14 +2120,18 @@ export default function DashboardPage() { - { setShowCustomTabModal(false); setEditingTabId(null); }} - editingTab={editingTab()} - availableOrgs={[...new Set(config.selectedRepos.map((r) => r.owner))]} - availableRepos={config.selectedRepos} - enableActions={config.enableActions} - /> + + + { setShowCustomTabModal(false); setEditingTabId(null); }} + editingTab={editingTab()} + availableOrgs={[...new Set(config.selectedRepos.map((r) => r.owner))]} + availableRepos={config.selectedRepos} + enableActions={config.enableActions} + /> + +