@lensmcp/cluster 1.22.4 → 1.22.5

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.
@@ -1 +1 @@
1
- "use strict";var R=Object.defineProperty;var d=(n,t)=>R(n,"name",{value:t,configurable:!0});var T=Object.defineProperty,u=d((n,t)=>T(n,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.DevServerReloadPlugin=void 0,exports.devserverControlSock=devserverControlSock,exports.createDevWebpackConfig=createDevWebpackConfig;const tslib_1=require("tslib"),app_plugin_1=require("@nx/webpack/app-plugin"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),webpack_node_externals_1=tslib_1.__importDefault(require("webpack-node-externals")),build_scope_patterns_1=require("./build-scope-patterns"),tsgo_check_plugin_1=require("./tsgo-check-plugin"),webpack=require("webpack");class DevServerReloadPlugin{static{d(this,"DevServerReloadPlugin")}static{u(this,"DevServerReloadPlugin")}static{this.RECENT_PATH_CAP=32}constructor(t,o=!1,r){this.testimony={schemaVersion:1,lastWatchRunAt:0,lastBuildAt:0,buildsSinceSpawn:0,degraded:!1,recentPaths:[]},this.secure=o,this.base=`${o?"https":"http"}://localhost:${t}`,this.controlSock=r}post(t,o){const r=JSON.stringify(o),s=u(()=>new Promise((a,c)=>{const l=(this.secure?require("node:https"):require("node:http")).request(`${this.base}${t}`,{method:"POST",headers:{"content-type":"application/json"},rejectUnauthorized:!1},p=>{p.resume(),p.on("end",a)});l.on("error",c),l.end(r)}),"viaTcp"),i=this.controlSock;return!i||!fs.existsSync(i)?s():new Promise((a,c)=>{const l=require("node:http").request({socketPath:i,path:t,method:"POST",headers:{"content-type":"application/json"}},p=>{p.resume(),p.on("end",a)});l.on("error",c),l.end(r)}).catch(s)}snapshot(){return{...this.testimony,recentPaths:[...this.testimony.recentPaths]}}stampWatchRun(t){if(this.testimony.lastWatchRunAt=Date.now(),t.length){const o=[...this.testimony.recentPaths,...t];this.testimony.recentPaths=o.slice(-DevServerReloadPlugin.RECENT_PATH_CAP)}}degrade(t){this.testimony.degraded=t}tellWatching(){this.post("/webpack/watching",this.testimony).catch(()=>{})}apply(t){const o="DevServerReloadPlugin";let r=!1;t.hooks.watchRun?.tap(o,s=>{const i=[...s?.modifiedFiles??[],...s?.removedFiles??[]].filter(a=>typeof a=="string");if(this.stampWatchRun(i),!r){const a=s?.watchFileSystem?.watcher;a&&typeof a.on=="function"&&(r=!0,a.on("error",c=>{this.degrade(`watcher error: ${c?.message??String(c)}`),this.tellWatching()}))}this.tellWatching()}),t.hooks.watchClose?.tap(o,()=>{this.degrade("watch closed"),this.tellWatching()}),t.hooks.failed?.tap(o,s=>{this.degrade(`compiler failed: ${s?.message??String(s)}`),this.tellWatching()}),t.hooks.done.tap(o,async s=>{try{if(s.hasErrors()){this.tellWatching();return}this.testimony.lastBuildAt=Date.now(),this.testimony.buildsSinceSpawn+=1,await this.post("/webpack/reload",{watcher:this.testimony}),console.log("[DevServerReloadPlugin] notified devserver to reload")}catch{console.log("[DevServerReloadPlugin] devserver not running yet")}})}}exports.DevServerReloadPlugin=DevServerReloadPlugin;function devserverControlSock(n,t=process.env){const o=t.LENSMCP_WS_KEY||"",r=o?path.join(os.tmpdir(),o,`${n}-devserver`):path.join(os.tmpdir(),`${n}-devserver`);return path.join(r,"parent.sock")}d(devserverControlSock,"devserverControlSock"),u(devserverControlSock,"devserverControlSock");function createDevWebpackConfig(n){const{appRoot:t,outputDir:o,main:r,tsConfig:s,workspaceRoot:i,assets:a=[],port:c,memoryLimit:l=8192,buildLibsFromSource:p=!0,orgScopes:b=[],bundlePackages:y=[],additionalEntryPoints:k=[],nodeExternalsConfig:m,webpackConfigPath:v}=n,{allowlistPatterns:C,scopePrefixes:E,scopePatterns:N}=(0,build_scope_patterns_1.buildScopePatterns)(b),P=process.env.LENSMCP_TYPECHECK,S=P==="tsgo"?(0,tsgo_check_plugin_1.resolveTsgoBin)(i,process.env.LENSMCP_TSGO_BIN):null;if(P==="tsgo"&&!S){const e=`${tsgo_check_plugin_1.TSGO_MISSING_CAUSE}. Fell back to fork-ts-checker, which reports to the console only \u2014 so typecheck:// has no producer for this project until it is fixed`;console.warn(`[serve] ${n.appName}: LENSMCP_TYPECHECK=tsgo but ${e}.`),(0,tsgo_check_plugin_1.reportTsgoUnavailable)({appName:n.appName,tsConfig:s,workspaceRoot:i,detail:e})}const f=!!S,_=y.map(e=>new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(/|$)`)),W=[/webpack\/hot\/poll\?100/,...C,..._,...m?.allowlist||[]],w={output:{path:o,...process.env.NODE_ENV!=="production"&&{devtoolModuleFilenameTemplate:"[absolute-resource-path]"},clean:!0},externals:[(0,webpack_node_externals_1.default)({allowlist:W,additionalModuleDirs:m?.additionalModuleDirs||[],...m?.importType&&{importType:m.importType}}),({request:e},g)=>{if(e&&path.isAbsolute(e)&&e.startsWith(i)&&!e.includes("node_modules")||e&&(e.startsWith(path.join(i,"apps"))||e.startsWith(path.join(i,"libs")))||e&&E.some(h=>e.startsWith(h))||e&&N.some(h=>h.test(e))||e&&_.some(h=>h.test(e)))return g();if(e&&!(e.startsWith("./")||e.startsWith(".."))){const h=e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0];return fs.existsSync(path.join(i,"node_modules",h))?g(null,`commonjs ${e}`):g()}return g()}],mode:"development",devtool:"eval-cheap-module-source-map",plugins:[new webpack.HotModuleReplacementPlugin,new app_plugin_1.NxAppWebpackPlugin({target:"node22",compiler:"tsc",main:r,additionalEntryPoints:k,verbose:!0,sourceMap:"eval-cheap-module-source-map",mergeExternals:!0,externalDependencies:[],memoryLimit:l,tsConfig:s,assets:a,optimization:!1,progress:!1,outputHashing:"none",generatePackageJson:!1,watchDependencies:!0,typeCheckOptions:process.env.LENSMCP_TYPECHECK==="off"||f?!1:{async:!0},buildLibsFromSource:p}),new DevServerReloadPlugin(c,n.httpsReload===!0,devserverControlSock(n.serviceName)),...f?[new tsgo_check_plugin_1.TsgoCheckPlugin({appName:n.appName,tsConfig:s,workspaceRoot:i,...process.env.LENSMCP_TSGO_BIN?{binPath:process.env.LENSMCP_TSGO_BIN}:{}})]:[]],snapshot:{managedPaths:[/^(.+?[\\/])?node_modules[\\/]/]},watch:!0,watchOptions:{ignored:["**/*.env.template","**/config.template.json","**/*.md","**/dist/**","**/migrations/**"]},cache:{type:"filesystem"}};if(v){const e=require(path.resolve(t,v));return(e.default||e)(w)}return w}d(createDevWebpackConfig,"createDevWebpackConfig"),u(createDevWebpackConfig,"createDevWebpackConfig");
1
+ "use strict";var W=Object.defineProperty;var d=(r,t)=>W(r,"name",{value:t,configurable:!0});var T=Object.defineProperty,u=d((r,t)=>T(r,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.DevServerReloadPlugin=void 0,exports.devserverControlSock=devserverControlSock,exports.createDevWebpackConfig=createDevWebpackConfig;const tslib_1=require("tslib"),app_plugin_1=require("@nx/webpack/app-plugin"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),webpack_node_externals_1=tslib_1.__importDefault(require("webpack-node-externals")),build_scope_patterns_1=require("./build-scope-patterns"),tsgo_check_plugin_1=require("./tsgo-check-plugin"),fork_ts_check_reporter_1=require("./fork-ts-check-reporter"),webpack=require("webpack");class DevServerReloadPlugin{static{d(this,"DevServerReloadPlugin")}static{u(this,"DevServerReloadPlugin")}static{this.RECENT_PATH_CAP=32}constructor(t,o=!1,i){this.testimony={schemaVersion:1,lastWatchRunAt:0,lastBuildAt:0,buildsSinceSpawn:0,degraded:!1,recentPaths:[]},this.secure=o,this.base=`${o?"https":"http"}://localhost:${t}`,this.controlSock=i}post(t,o){const i=JSON.stringify(o),s=u(()=>new Promise((a,c)=>{const p=(this.secure?require("node:https"):require("node:http")).request(`${this.base}${t}`,{method:"POST",headers:{"content-type":"application/json"},rejectUnauthorized:!1},l=>{l.resume(),l.on("end",a)});p.on("error",c),p.end(i)}),"viaTcp"),n=this.controlSock;return!n||!fs.existsSync(n)?s():new Promise((a,c)=>{const p=require("node:http").request({socketPath:n,path:t,method:"POST",headers:{"content-type":"application/json"}},l=>{l.resume(),l.on("end",a)});p.on("error",c),p.end(i)}).catch(s)}snapshot(){return{...this.testimony,recentPaths:[...this.testimony.recentPaths]}}stampWatchRun(t){if(this.testimony.lastWatchRunAt=Date.now(),t.length){const o=[...this.testimony.recentPaths,...t];this.testimony.recentPaths=o.slice(-DevServerReloadPlugin.RECENT_PATH_CAP)}}degrade(t){this.testimony.degraded=t}tellWatching(){this.post("/webpack/watching",this.testimony).catch(()=>{})}apply(t){const o="DevServerReloadPlugin";let i=!1;t.hooks.watchRun?.tap(o,s=>{const n=[...s?.modifiedFiles??[],...s?.removedFiles??[]].filter(a=>typeof a=="string");if(this.stampWatchRun(n),!i){const a=s?.watchFileSystem?.watcher;a&&typeof a.on=="function"&&(i=!0,a.on("error",c=>{this.degrade(`watcher error: ${c?.message??String(c)}`),this.tellWatching()}))}this.tellWatching()}),t.hooks.watchClose?.tap(o,()=>{this.degrade("watch closed"),this.tellWatching()}),t.hooks.failed?.tap(o,s=>{this.degrade(`compiler failed: ${s?.message??String(s)}`),this.tellWatching()}),t.hooks.done.tap(o,async s=>{try{if(s.hasErrors()){this.tellWatching();return}this.testimony.lastBuildAt=Date.now(),this.testimony.buildsSinceSpawn+=1,await this.post("/webpack/reload",{watcher:this.testimony}),console.log("[DevServerReloadPlugin] notified devserver to reload")}catch{console.log("[DevServerReloadPlugin] devserver not running yet")}})}}exports.DevServerReloadPlugin=DevServerReloadPlugin;function devserverControlSock(r,t=process.env){const o=t.LENSMCP_WS_KEY||"",i=o?path.join(os.tmpdir(),o,`${r}-devserver`):path.join(os.tmpdir(),`${r}-devserver`);return path.join(i,"parent.sock")}d(devserverControlSock,"devserverControlSock"),u(devserverControlSock,"devserverControlSock");function createDevWebpackConfig(r){const{appRoot:t,outputDir:o,main:i,tsConfig:s,workspaceRoot:n,assets:a=[],port:c,memoryLimit:p=8192,buildLibsFromSource:l=!0,orgScopes:w=[],bundlePackages:b=[],additionalEntryPoints:y=[],nodeExternalsConfig:m,webpackConfigPath:v}=r,{allowlistPatterns:C,scopePrefixes:E,scopePatterns:N}=(0,build_scope_patterns_1.buildScopePatterns)(w),P=process.env.LENSMCP_TYPECHECK,f=P==="tsgo"?(0,tsgo_check_plugin_1.resolveTsgoBin)(n,process.env.LENSMCP_TSGO_BIN):null;if(P==="tsgo"&&!f){const e=`${tsgo_check_plugin_1.TSGO_MISSING_CAUSE}. Fell back to fork-ts-checker, which reports to the console only \u2014 so typecheck:// has no producer for this project until it is fixed`;console.warn(`[serve] ${r.appName}: LENSMCP_TYPECHECK=tsgo but ${e}.`),(0,tsgo_check_plugin_1.reportTsgoUnavailable)({appName:r.appName,tsConfig:s,workspaceRoot:n,detail:e})}const _=!!f,S=b.map(e=>new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(/|$)`)),R=[/webpack\/hot\/poll\?100/,...C,...S,...m?.allowlist||[]],k={output:{path:o,...process.env.NODE_ENV!=="production"&&{devtoolModuleFilenameTemplate:"[absolute-resource-path]"},clean:!0},externals:[(0,webpack_node_externals_1.default)({allowlist:R,additionalModuleDirs:m?.additionalModuleDirs||[],...m?.importType&&{importType:m.importType}}),({request:e},g)=>{if(e&&path.isAbsolute(e)&&e.startsWith(n)&&!e.includes("node_modules")||e&&(e.startsWith(path.join(n,"apps"))||e.startsWith(path.join(n,"libs")))||e&&E.some(h=>e.startsWith(h))||e&&N.some(h=>h.test(e))||e&&S.some(h=>h.test(e)))return g();if(e&&!(e.startsWith("./")||e.startsWith(".."))){const h=e.startsWith("@")?e.split("/").slice(0,2).join("/"):e.split("/")[0];return fs.existsSync(path.join(n,"node_modules",h))?g(null,`commonjs ${e}`):g()}return g()}],mode:"development",devtool:"eval-cheap-module-source-map",plugins:[new webpack.HotModuleReplacementPlugin,new app_plugin_1.NxAppWebpackPlugin({target:"node22",compiler:"tsc",main:i,additionalEntryPoints:y,verbose:!0,sourceMap:"eval-cheap-module-source-map",mergeExternals:!0,externalDependencies:[],memoryLimit:p,tsConfig:s,assets:a,optimization:!1,progress:!1,outputHashing:"none",generatePackageJson:!1,watchDependencies:!0,typeCheckOptions:process.env.LENSMCP_TYPECHECK==="off"||_?!1:{async:!0},buildLibsFromSource:l}),new DevServerReloadPlugin(c,r.httpsReload===!0,devserverControlSock(r.serviceName)),..._?[new tsgo_check_plugin_1.TsgoCheckPlugin({appName:r.appName,tsConfig:s,workspaceRoot:n,...process.env.LENSMCP_TSGO_BIN?{binPath:process.env.LENSMCP_TSGO_BIN}:{}})]:process.env.LENSMCP_TYPECHECK==="off"?[]:[new fork_ts_check_reporter_1.ForkTsCheckReporterPlugin({appName:r.appName,tsConfig:s,workspaceRoot:n})]],snapshot:{managedPaths:[/^(.+?[\\/])?node_modules[\\/]/]},watch:!0,watchOptions:{ignored:["**/*.env.template","**/config.template.json","**/*.md","**/dist/**","**/migrations/**"]},cache:{type:"filesystem"}};if(v){const e=require(path.resolve(t,v));return(e.default||e)(k)}return k}d(createDevWebpackConfig,"createDevWebpackConfig"),u(createDevWebpackConfig,"createDevWebpackConfig");
@@ -1 +1 @@
1
- "use strict";var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});var S=Object.defineProperty,u=a((e,r)=>S(e,"name",{value:r,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.pickSock=pickSock,exports.lensPortFromUpstream=lensPortFromUpstream,exports.discoverRoutes=discoverRoutes,exports.projectSourceRoots=projectSourceRoots;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),manifest_1=require("../manifest"),scope_1=require("./scope");function pickSock(e,r=1500){const p=Date.now();if(p-e.scannedAt>r){try{e.socks=fs.readdirSync(e.dir).filter(s=>/^child-\d+(?:-g\d+)?\.sock$/.test(s)).map(s=>path.join(e.dir,s))}catch{e.socks=[]}e.scannedAt=p}if(e.socks.length!==0)return e.idx=(e.idx+1)%e.socks.length,e.socks[e.idx]}a(pickSock,"pickSock"),u(pickSock,"pickSock");function lensPortFromUpstream(e){if(!e)return;const r=/:(\d+)/.exec(e);return r?Number(r[1]):void 0}a(lensPortFromUpstream,"lensPortFromUpstream"),u(lensPortFromUpstream,"lensPortFromUpstream");function discoverRoutes(e,r,p=os.tmpdir(),s="",l={}){const d=u(i=>s?path.join(p,s,`${i}-devserver`):path.join(p,`${i}-devserver`),"sockDirFor"),c=[],h=[],o=[];let n;for(const[i,x]of Object.entries(r)){let t;try{const f=JSON.parse(fs.readFileSync(path.join(e,x.root,"project.json"),"utf8"));t=f.cluster??f.davnx}catch{continue}if(!t)continue;let v,j,m,y;if(t.service)t.lens&&console.warn(`[gateway] ${i}: cluster.lens is ignored for pod (service) decls \u2014 backends are instrumented by serve-hmr.`),v={dir:d(t.service),socks:[],idx:-1,scannedAt:0},j={project:i,decl:t,root:e,wsKey:s,pool:v,state:"down",lastUsed:Date.now(),inflight:0,lastScaleAt:0},h.push(j);else if(t.lens){const f=t.port??lensPortFromUpstream(t.upstream)??5173;m=`http://localhost:${f}`,y={project:i,...s?{workspaceKey:s}:{},projectRoot:path.join(e,x.root),port:f,...l[i]?.length?{sourceRoots:l[i]}:{}}}else if(m=t.upstream??(t.port?`http://localhost:${t.port}`:void 0),!m){console.warn(`[gateway] ${i}: no service/upstream/port \u2014 skipped.`);continue}const k={project:i,prependPrefix:t.prependPrefix,target:m,pool:v,svc:j,prefix:t.path,auth:t.auth,lens:y};t.host&&(c.push({...k,host:t.host}),o.push(t.host),v&&t.internalHost!==!1&&c.push({...k,host:typeof t.internalHost=="string"?t.internalHost:`internal.${t.host}`,internal:!0})),t.default&&(n={...k,prefix:void 0})}return n&&(n.apex=(0,scope_1.baseDomainOf)(o),c.push(n)),(0,manifest_1.sortBySpecificity)(c),{routes:c,services:h}}a(discoverRoutes,"discoverRoutes"),u(discoverRoutes,"discoverRoutes");function projectSourceRoots(e,r,p={}){const s={};for(const l of Object.keys(r)){const d=new Set,c=u(o=>{if(!d.has(o)){d.add(o);for(const n of p[o]??[])c(n)}},"visit");c(l);const h=[...d].map(o=>r[o]?.root).filter(o=>typeof o=="string").map(o=>path.resolve(e,o)).filter(o=>{const n=path.relative(e,o);return n===""||n!==".."&&!n.startsWith(`..${path.sep}`)&&!path.isAbsolute(n)});s[l]=[...new Set(h)]}return s}a(projectSourceRoots,"projectSourceRoots"),u(projectSourceRoots,"projectSourceRoots");
1
+ "use strict";var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});var S=Object.defineProperty,u=a((e,r)=>S(e,"name",{value:r,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.pickSock=pickSock,exports.lensPortFromUpstream=lensPortFromUpstream,exports.discoverRoutes=discoverRoutes,exports.projectSourceRoots=projectSourceRoots;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),os=tslib_1.__importStar(require("node:os")),path=tslib_1.__importStar(require("node:path")),manifest_1=require("../manifest"),scope_1=require("./scope");function pickSock(e,r=1500){const p=Date.now();if(p-e.scannedAt>r){try{e.socks=fs.readdirSync(e.dir).filter(s=>/^child-\d+(?:-g\d+)?\.sock$/.test(s)).map(s=>path.join(e.dir,s))}catch{e.socks=[]}e.scannedAt=p}if(e.socks.length!==0)return e.idx=(e.idx+1)%e.socks.length,e.socks[e.idx]}a(pickSock,"pickSock"),u(pickSock,"pickSock");function lensPortFromUpstream(e){if(!e)return;const r=/:(\d+)/.exec(e);return r?Number(r[1]):void 0}a(lensPortFromUpstream,"lensPortFromUpstream"),u(lensPortFromUpstream,"lensPortFromUpstream");function discoverRoutes(e,r,p=os.tmpdir(),s="",l={}){const d=u(i=>s?path.join(p,s,`${i}-devserver`):path.join(p,`${i}-devserver`),"sockDirFor"),c=[],h=[],o=[];let n;for(const[i,x]of Object.entries(r)){let t;try{const f=JSON.parse(fs.readFileSync(path.join(e,x.root,"project.json"),"utf8"));t=f.cluster??f.davnx}catch{continue}if(!t)continue;let v,k,m,y;if(t.service)t.lens&&console.warn(`[gateway] ${i}: cluster.lens is ignored for pod (service) decls \u2014 backends are instrumented by serve-hmr.`),v={dir:d(t.service),socks:[],idx:-1,scannedAt:0},k={project:i,decl:t,root:e,wsKey:s,pool:v,state:"down",lastUsed:Date.now(),inflight:0,lastScaleAt:0},h.push(k);else if(t.lens){const f=t.port??lensPortFromUpstream(t.upstream)??5173;m=`http://localhost:${f}`,y={project:i,...s?{workspaceKey:s}:{},workspaceRoot:e,projectRoot:path.join(e,x.root),port:f,...l[i]?.length?{sourceRoots:l[i]}:{}}}else if(m=t.upstream??(t.port?`http://localhost:${t.port}`:void 0),!m){console.warn(`[gateway] ${i}: no service/upstream/port \u2014 skipped.`);continue}const j={project:i,prependPrefix:t.prependPrefix,target:m,pool:v,svc:k,prefix:t.path,auth:t.auth,lens:y};t.host&&(c.push({...j,host:t.host}),o.push(t.host),v&&t.internalHost!==!1&&c.push({...j,host:typeof t.internalHost=="string"?t.internalHost:`internal.${t.host}`,internal:!0})),t.default&&(n={...j,prefix:void 0})}return n&&(n.apex=(0,scope_1.baseDomainOf)(o),c.push(n)),(0,manifest_1.sortBySpecificity)(c),{routes:c,services:h}}a(discoverRoutes,"discoverRoutes"),u(discoverRoutes,"discoverRoutes");function projectSourceRoots(e,r,p={}){const s={};for(const l of Object.keys(r)){const d=new Set,c=u(o=>{if(!d.has(o)){d.add(o);for(const n of p[o]??[])c(n)}},"visit");c(l);const h=[...d].map(o=>r[o]?.root).filter(o=>typeof o=="string").map(o=>path.resolve(e,o)).filter(o=>{const n=path.relative(e,o);return n===""||n!==".."&&!n.startsWith(`..${path.sep}`)&&!path.isAbsolute(n)});s[l]=[...new Set(h)]}return s}a(projectSourceRoots,"projectSourceRoots"),u(projectSourceRoots,"projectSourceRoots");
@@ -1,2 +1,2 @@
1
- "use strict";var D=Object.defineProperty;var l=(s,d)=>D(s,"name",{value:d,configurable:!0});var b=Object.defineProperty,o=l((s,d)=>b(s,"name",{value:d,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_DASHBOARD_PROJECT=void 0,exports.createObservability=createObservability;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),redact_1=require("@lensmcp/core/redact"),busHygiene=(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})();exports.LENS_DASHBOARD_PROJECT="(lens-dashboard)";function ownerOf(s){return s?.svc?{root:s.svc.root,wsKey:s.svc.wsKey}:s?.lens?.workspaceKey?{wsKey:s.lens.workspaceKey}:{}}l(ownerOf,"ownerOf"),o(ownerOf,"ownerOf");function busFileFor(s,d){const{root:u}=ownerOf(s);if(!u)return;const p=path.join(u,".lensmcp","events.jsonl");return p===d?void 0:p}l(busFileFor,"busFileFor"),o(busFileFor,"busFileFor");const hdr=o(s=>typeof s=="string"&&s!==""?s:Array.isArray(s)?s[0]:void 0,"hdr");function createObservability(s,d){const u=o(()=>Date.now().toString(36)+Math.random().toString(36).slice(2,12),"eid"),p=busHygiene?.createEventFloodGuard({burst:30,perSec:5}),h=o((e,r,t,n,a,c)=>{const i=c??s;try{const y=p?p.admit(t):{ok:!0,suppressed:0};if(!y.ok)return;fs.mkdirSync(path.dirname(i),{recursive:!0});const w=n&&(0,redact_1.redactDeep)(n),g=JSON.stringify({id:u(),sessionId:"pending",timestamp:Date.now(),source:"gateway",category:"cluster",severity:e,context:(0,redact_1.redactDeep)({sessionId:"pending",...a}),fingerprint:t,title:(0,redact_1.safeTitle)(r),raw:y.suppressed>0?{...w,floodSuppressed:y.suppressed}:w})+`
2
- `;busHygiene?.maybeRotateEventFile(i,g.length),fs.appendFileSync(i,g)}catch{}},"emit"),m=o(e=>{const r=hdr(e.headers["x-lensmcp-flow-id"]);let t=hdr(e.headers["x-request-id"]);if(!(!r&&!t&&!hdr(e.headers.traceparent)))return t||(t=u(),e.headers["x-request-id"]=t),{startedAt:Date.now(),method:(e.method??"GET").toUpperCase(),host:(e.headers.host||"").split(":")[0],url:e.url??"/",steps:[],...r?{flowId:r}:{},...t?{requestId:t}:{},...hdr(e.headers["x-lensmcp-origin-node-id"])?{originNodeId:hdr(e.headers["x-lensmcp-origin-node-id"])}:{}}},"beginTrace"),v=o((e,r,t)=>{e&&e.steps.push({step:r,atMs:Date.now()-e.startedAt,...t})},"traceStep"),S=o((e,r,t,n,a)=>{if(!e||e.done||(e.done=!0,r===exports.LENS_DASHBOARD_PROJECT&&t<500))return;const c=Date.now()-e.startedAt;h(t>=500?"error":"info",`gateway ${e.method} ${e.host}${e.url} \u2192 ${t} (${c}ms)`,`gateway-request:${r}`,{kind:"gateway-request",project:r,host:e.host,method:e.method,url:e.url,status:t,durationMs:c,startedAt:e.startedAt,steps:e.steps,...ownerOf(a).wsKey?{wsKey:ownerOf(a).wsKey}:{},...n},{...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.originNodeId?{originNodeId:e.originNodeId}:{}},busFileFor(a,s))},"finishTrace"),f=new Map;return{emit:h,eid:u,beginTrace:m,traceStep:v,finishTrace:S,recordEdge:o((e,r,t,n)=>{if(e.project===exports.LENS_DASHBOARD_PROJECT&&t<500&&t!==0)return;const a=e.host??"(default)",c=(n?n+"\u21D2":"")+a+"\u2192"+e.project,i=f.get(c)??{host:a,project:e.project,caller:n,count:0,totalMs:0,errors:0,...busFileFor(e,s)?{busFile:busFileFor(e,s)}:{},...ownerOf(e).wsKey?{wsKey:ownerOf(e).wsKey}:{}};i.count+=1,i.totalMs+=r,(t>=500||t===0)&&(i.errors+=1),f.set(c,i)},"recordEdge"),startEdgeFlusher:o(()=>{const e=setInterval(()=>{for(const r of f.values()){const t=Math.round(r.totalMs/r.count);h(r.errors?"warning":"info",`traffic ${r.host} \u2192 ${r.project}: ${r.count} req, ~${t}ms${r.errors?`, ${r.errors} errors`:""}`,`gateway-traffic:${r.host}->${r.project}`,{kind:"gateway-traffic",host:r.host,project:r.project,caller:r.caller,count:r.count,avgMs:t,errors:r.errors,...r.wsKey?{wsKey:r.wsKey}:{}},void 0,r.busFile)}f.clear()},d.trafficFlushMs);return e.unref(),e},"startEdgeFlusher")}}l(createObservability,"createObservability"),o(createObservability,"createObservability");
1
+ "use strict";var D=Object.defineProperty;var p=(t,c)=>D(t,"name",{value:c,configurable:!0});var b=Object.defineProperty,o=p((t,c)=>b(t,"name",{value:c,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_DASHBOARD_PROJECT=void 0,exports.createObservability=createObservability;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),redact_1=require("@lensmcp/core/redact"),busHygiene=(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})();exports.LENS_DASHBOARD_PROJECT="(lens-dashboard)";function ownerOf(t){return t?.svc?{root:t.svc.root,wsKey:t.svc.wsKey}:t?.lens?{...t.lens.workspaceRoot?{root:t.lens.workspaceRoot}:{},...t.lens.workspaceKey?{wsKey:t.lens.workspaceKey}:{}}:{}}p(ownerOf,"ownerOf"),o(ownerOf,"ownerOf");function busFileFor(t,c){const{root:u}=ownerOf(t);if(!u)return;const l=path.join(u,".lensmcp","events.jsonl");return l===c?void 0:l}p(busFileFor,"busFileFor"),o(busFileFor,"busFileFor");const hdr=o(t=>typeof t=="string"&&t!==""?t:Array.isArray(t)?t[0]:void 0,"hdr");function createObservability(t,c){const u=o(()=>Date.now().toString(36)+Math.random().toString(36).slice(2,12),"eid"),l=busHygiene?.createEventFloodGuard({burst:30,perSec:5}),h=o((e,r,s,n,a,d)=>{const i=d??t;try{const w=l?l.admit(s):{ok:!0,suppressed:0};if(!w.ok)return;fs.mkdirSync(path.dirname(i),{recursive:!0});const y=n&&(0,redact_1.redactDeep)(n),g=JSON.stringify({id:u(),sessionId:"pending",timestamp:Date.now(),source:"gateway",category:"cluster",severity:e,context:(0,redact_1.redactDeep)({sessionId:"pending",...a}),fingerprint:s,title:(0,redact_1.safeTitle)(r),raw:w.suppressed>0?{...y,floodSuppressed:w.suppressed}:y})+`
2
+ `;busHygiene?.maybeRotateEventFile(i,g.length),fs.appendFileSync(i,g)}catch{}},"emit"),m=o(e=>{const r=hdr(e.headers["x-lensmcp-flow-id"]);let s=hdr(e.headers["x-request-id"]);if(!(!r&&!s&&!hdr(e.headers.traceparent)))return s||(s=u(),e.headers["x-request-id"]=s),{startedAt:Date.now(),method:(e.method??"GET").toUpperCase(),host:(e.headers.host||"").split(":")[0],url:e.url??"/",steps:[],...r?{flowId:r}:{},...s?{requestId:s}:{},...hdr(e.headers["x-lensmcp-origin-node-id"])?{originNodeId:hdr(e.headers["x-lensmcp-origin-node-id"])}:{}}},"beginTrace"),v=o((e,r,s)=>{e&&e.steps.push({step:r,atMs:Date.now()-e.startedAt,...s})},"traceStep"),S=o((e,r,s,n,a)=>{if(!e||e.done||(e.done=!0,r===exports.LENS_DASHBOARD_PROJECT&&s<500))return;const d=Date.now()-e.startedAt;h(s>=500?"error":"info",`gateway ${e.method} ${e.host}${e.url} \u2192 ${s} (${d}ms)`,`gateway-request:${r}`,{kind:"gateway-request",project:r,host:e.host,method:e.method,url:e.url,status:s,durationMs:d,startedAt:e.startedAt,steps:e.steps,...ownerOf(a).wsKey?{wsKey:ownerOf(a).wsKey}:{},...n},{...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.originNodeId?{originNodeId:e.originNodeId}:{}},busFileFor(a,t))},"finishTrace"),f=new Map;return{emit:h,eid:u,beginTrace:m,traceStep:v,finishTrace:S,recordEdge:o((e,r,s,n)=>{if(e.project===exports.LENS_DASHBOARD_PROJECT&&s<500&&s!==0)return;const a=e.host??"(default)",d=(n?n+"\u21D2":"")+a+"\u2192"+e.project,i=f.get(d)??{host:a,project:e.project,caller:n,count:0,totalMs:0,errors:0,...busFileFor(e,t)?{busFile:busFileFor(e,t)}:{},...ownerOf(e).wsKey?{wsKey:ownerOf(e).wsKey}:{}};i.count+=1,i.totalMs+=r,(s>=500||s===0)&&(i.errors+=1),f.set(d,i)},"recordEdge"),startEdgeFlusher:o(()=>{const e=setInterval(()=>{for(const r of f.values()){const s=Math.round(r.totalMs/r.count);h(r.errors?"warning":"info",`traffic ${r.host} \u2192 ${r.project}: ${r.count} req, ~${s}ms${r.errors?`, ${r.errors} errors`:""}`,`gateway-traffic:${r.host}->${r.project}`,{kind:"gateway-traffic",host:r.host,project:r.project,caller:r.caller,count:r.count,avgMs:s,errors:r.errors,...r.wsKey?{wsKey:r.wsKey}:{}},void 0,r.busFile)}f.clear()},c.trafficFlushMs);return e.unref(),e},"startEdgeFlusher")}}p(createObservability,"createObservability"),o(createObservability,"createObservability");
@@ -117,6 +117,12 @@ export interface LensFrontend {
117
117
  project: string;
118
118
  /** Owning workspace, used to isolate same-named frontends in the shared daemon. */
119
119
  workspaceKey?: string;
120
+ /** Absolute WORKSPACE root of the owning workspace — the parent of `.lensmcp/events.jsonl`.
121
+ * A pod route carries this on its `ServiceCtl.root`; a lens route had only `projectRoot`
122
+ * (the app dir), so `ownerOf` could not resolve the owning bus and every gateway event for
123
+ * the browser-facing host (`app.<apex>`) was narrated into the DAEMON's bus instead of the
124
+ * guest workspace's — the browser's own request hop went missing from that workspace's flows. */
125
+ workspaceRoot?: string;
120
126
  /** Absolute project root (holds vite.config.*). */
121
127
  projectRoot: string;
122
128
  /** The pinned Vite dev port (also the upstream target's port). */
@@ -0,0 +1,13 @@
1
+ export interface ForkTsCheckReporterOptions {
2
+ appName: string;
3
+ tsConfig: string;
4
+ workspaceRoot: string;
5
+ /** Override the lens bus file; defaults to `LENSMCP_EVENT_FILE` / `<root>/.lensmcp/events.jsonl`. */
6
+ eventFile?: string;
7
+ }
8
+ export declare class ForkTsCheckReporterPlugin {
9
+ private readonly opts;
10
+ private startedAt;
11
+ constructor(opts: ForkTsCheckReporterOptions);
12
+ apply(compiler: any): void;
13
+ }
@@ -0,0 +1 @@
1
+ "use strict";var p=Object.defineProperty;var s=(e,t)=>p(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,r=s((e,t)=>a(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ForkTsCheckReporterPlugin=void 0;const tslib_1=require("tslib"),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus");function loadForkTsChecker(e){const t=[];try{t.push(path.dirname(require.resolve("@nx/webpack/package.json",{paths:[e]})))}catch{}t.push(e,__dirname);for(const o of t)try{return require(require.resolve("fork-ts-checker-webpack-plugin",{paths:[o]}))}catch{}return null}s(loadForkTsChecker,"loadForkTsChecker"),r(loadForkTsChecker,"loadForkTsChecker");function toDiagnostic(e,t){return{file:e.file?path.relative(t,e.file)||e.file:"<unknown>",line:e.location?.start?.line??0,column:e.location?.start?.column??0,severity:e.severity==="warning"?"warning":"error",code:/^TS\d+$/.test(e.code)?e.code:`TS${e.code}`,message:e.message}}s(toDiagnostic,"toDiagnostic"),r(toDiagnostic,"toDiagnostic");class ForkTsCheckReporterPlugin{static{s(this,"ForkTsCheckReporterPlugin")}static{r(this,"ForkTsCheckReporterPlugin")}constructor(t){this.startedAt=0,this.opts=t}apply(t){const o=loadForkTsChecker(this.opts.workspaceRoot)?.getCompilerHooks;if(typeof o!="function")return;let c;try{c=o(t)}catch{return}c.start?.tapPromise("LensmcpForkTsCheckReporter",async i=>(this.startedAt=Date.now(),i)),c.issues?.tap("LensmcpForkTsCheckReporter",i=>{try{(0,typecheck_bus_1.publishTypecheckDiagnostics)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"fork-ts-checker",tsConfig:this.opts.tsConfig,diagnostics:(i??[]).map(n=>toDiagnostic(n,this.opts.workspaceRoot)),durationMs:this.startedAt?Date.now()-this.startedAt:0,...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}return i})}}exports.ForkTsCheckReporterPlugin=ForkTsCheckReporterPlugin;
package/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { type NodeExternalsConfig, type ScopePatterns, buildScopePatterns } from './build-scope-patterns';
2
2
  export { createDevWebpackConfig, type DevWebpackOptions } from './create-webpack-dev';
3
3
  export { createProdWebpackConfig, type ProdWebpackOptions } from './create-webpack-prod';
4
- export { appendTypecheckEvents, buildTypecheckRunEvents, parseTscDiagnosticLine, parseTscOutput, publishTypecheckRun, resolveEventFile, type TscDiagnostic, type TypecheckBusEvent, } from './typecheck-bus';
4
+ export { appendTypecheckEvents, buildTypecheckRunEvents, parseTscDiagnosticLine, parseTscOutput, publishTypecheckDiagnostics, publishTypecheckRun, resolveEventFile, type TscDiagnostic, type TypecheckBusEvent, } from './typecheck-bus';
5
+ export { ForkTsCheckReporterPlugin, type ForkTsCheckReporterOptions } from './fork-ts-check-reporter';
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var c=(t,r)=>p(t,"name",{value:r,configurable:!0});var n=Object.defineProperty,e=c((t,r)=>n(t,"name",{value:r,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.resolveEventFile=exports.publishTypecheckRun=exports.parseTscOutput=exports.parseTscDiagnosticLine=exports.buildTypecheckRunEvents=exports.appendTypecheckEvents=exports.createProdWebpackConfig=exports.createDevWebpackConfig=exports.buildScopePatterns=void 0;var build_scope_patterns_1=require("./build-scope-patterns");Object.defineProperty(exports,"buildScopePatterns",{enumerable:!0,get:e(function(){return build_scope_patterns_1.buildScopePatterns},"get")});var create_webpack_dev_1=require("./create-webpack-dev");Object.defineProperty(exports,"createDevWebpackConfig",{enumerable:!0,get:e(function(){return create_webpack_dev_1.createDevWebpackConfig},"get")});var create_webpack_prod_1=require("./create-webpack-prod");Object.defineProperty(exports,"createProdWebpackConfig",{enumerable:!0,get:e(function(){return create_webpack_prod_1.createProdWebpackConfig},"get")});var typecheck_bus_1=require("./typecheck-bus");Object.defineProperty(exports,"appendTypecheckEvents",{enumerable:!0,get:e(function(){return typecheck_bus_1.appendTypecheckEvents},"get")}),Object.defineProperty(exports,"buildTypecheckRunEvents",{enumerable:!0,get:e(function(){return typecheck_bus_1.buildTypecheckRunEvents},"get")}),Object.defineProperty(exports,"parseTscDiagnosticLine",{enumerable:!0,get:e(function(){return typecheck_bus_1.parseTscDiagnosticLine},"get")}),Object.defineProperty(exports,"parseTscOutput",{enumerable:!0,get:e(function(){return typecheck_bus_1.parseTscOutput},"get")}),Object.defineProperty(exports,"publishTypecheckRun",{enumerable:!0,get:e(function(){return typecheck_bus_1.publishTypecheckRun},"get")}),Object.defineProperty(exports,"resolveEventFile",{enumerable:!0,get:e(function(){return typecheck_bus_1.resolveEventFile},"get")});
1
+ "use strict";var p=Object.defineProperty;var c=(r,t)=>p(r,"name",{value:t,configurable:!0});var n=Object.defineProperty,e=c((r,t)=>n(r,"name",{value:t,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.ForkTsCheckReporterPlugin=exports.resolveEventFile=exports.publishTypecheckRun=exports.publishTypecheckDiagnostics=exports.parseTscOutput=exports.parseTscDiagnosticLine=exports.buildTypecheckRunEvents=exports.appendTypecheckEvents=exports.createProdWebpackConfig=exports.createDevWebpackConfig=exports.buildScopePatterns=void 0;var build_scope_patterns_1=require("./build-scope-patterns");Object.defineProperty(exports,"buildScopePatterns",{enumerable:!0,get:e(function(){return build_scope_patterns_1.buildScopePatterns},"get")});var create_webpack_dev_1=require("./create-webpack-dev");Object.defineProperty(exports,"createDevWebpackConfig",{enumerable:!0,get:e(function(){return create_webpack_dev_1.createDevWebpackConfig},"get")});var create_webpack_prod_1=require("./create-webpack-prod");Object.defineProperty(exports,"createProdWebpackConfig",{enumerable:!0,get:e(function(){return create_webpack_prod_1.createProdWebpackConfig},"get")});var typecheck_bus_1=require("./typecheck-bus");Object.defineProperty(exports,"appendTypecheckEvents",{enumerable:!0,get:e(function(){return typecheck_bus_1.appendTypecheckEvents},"get")}),Object.defineProperty(exports,"buildTypecheckRunEvents",{enumerable:!0,get:e(function(){return typecheck_bus_1.buildTypecheckRunEvents},"get")}),Object.defineProperty(exports,"parseTscDiagnosticLine",{enumerable:!0,get:e(function(){return typecheck_bus_1.parseTscDiagnosticLine},"get")}),Object.defineProperty(exports,"parseTscOutput",{enumerable:!0,get:e(function(){return typecheck_bus_1.parseTscOutput},"get")}),Object.defineProperty(exports,"publishTypecheckDiagnostics",{enumerable:!0,get:e(function(){return typecheck_bus_1.publishTypecheckDiagnostics},"get")}),Object.defineProperty(exports,"publishTypecheckRun",{enumerable:!0,get:e(function(){return typecheck_bus_1.publishTypecheckRun},"get")}),Object.defineProperty(exports,"resolveEventFile",{enumerable:!0,get:e(function(){return typecheck_bus_1.resolveEventFile},"get")});var fork_ts_check_reporter_1=require("./fork-ts-check-reporter");Object.defineProperty(exports,"ForkTsCheckReporterPlugin",{enumerable:!0,get:e(function(){return fork_ts_check_reporter_1.ForkTsCheckReporterPlugin},"get")});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/cluster",
3
- "version": "1.22.4",
3
+ "version": "1.22.5",
4
4
  "description": "Run your Nx workspace as a local production cluster: pods on unix sockets with true HMR, one https gateway with per-project domains, scale-from-zero, autoscale, idle-kill, local-CA TLS — observed by the LensMCP lens.",
5
5
  "main": "./index.js",
6
6
  "types": "./index.d.ts",
@@ -57,9 +57,9 @@
57
57
  }
58
58
  },
59
59
  "dependencies": {
60
- "@lensmcp/core": "1.22.4",
61
- "@lensmcp/node-instrumentation": "1.22.4",
62
- "@lensmcp/nx-plugin": "1.22.4",
60
+ "@lensmcp/core": "1.22.5",
61
+ "@lensmcp/node-instrumentation": "1.22.5",
62
+ "@lensmcp/nx-plugin": "1.22.5",
63
63
  "fastify": "^5.8.5",
64
64
  "@fastify/reply-from": "^12.6.2",
65
65
  "@typescript/native-preview": "^7.0.0-dev.20260707.2",
@@ -116,11 +116,16 @@ export declare function reportTsgoUnavailable(args: {
116
116
  eventFile?: string;
117
117
  }): void;
118
118
  /**
119
- * Write the shim tsconfig (absolute `extends`; see the header) and return its path. It lives under
120
- * the WORKSPACE's git-ignored `tmp/` — NOT os.tmpdir(): `types: ['node']` (and every other @types
121
- * lookup) resolves typeRoots by walking node_modules UP FROM THE CONFIG FILE's directory, so a shim
122
- * outside the tree fails every service with `TS2688: Cannot find type definition file for 'node'`.
119
+ * The `paths` in effect for a config, and the directory they are anchored at.
120
+ *
121
+ * Walks the `extends` chain leaf-first; the nearest declaration wins (tsconfig REPLACES `paths`,
122
+ * it does not merge them). The anchor is the nearest `baseUrl`, resolved against the file that
123
+ * declared IT — or, with no baseUrl anywhere, the file that declared the paths.
123
124
  */
125
+ export declare function effectivePaths(tsConfig: string, seen?: Set<string>): {
126
+ paths: Record<string, string[]>;
127
+ anchorDir: string;
128
+ } | null;
124
129
  export declare function writeShimTsconfig(appName: string, tsConfig: string, workspaceRoot: string): string;
125
130
  export declare class TsgoCheckPlugin {
126
131
  private readonly opts;
@@ -1,4 +1,5 @@
1
- "use strict";var d=Object.defineProperty;var l=(s,t)=>d(s,"name",{value:t,configurable:!0});var u=Object.defineProperty,r=l((s,t)=>u(s,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TsgoCheckPlugin=exports.TSGO_MISSING_CAUSE=exports.TSGO_PACKAGE=void 0,exports.resolveTsgoPackageDir=resolveTsgoPackageDir,exports.resolveTsgoBin=resolveTsgoBin,exports.reportTsgoUnavailable=reportTsgoUnavailable,exports.writeShimTsconfig=writeShimTsconfig;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus");exports.TSGO_PACKAGE="@typescript/native-preview";function shimNames(s){return s==="win32"?["tsgo.cmd","tsgo.exe"]:["tsgo"]}l(shimNames,"shimNames"),r(shimNames,"shimNames");function isExecutableFile(s,t){try{if(!fs.statSync(s).isFile())return!1}catch{return!1}if(t==="win32")return!0;try{return fs.accessSync(s,fs.constants.X_OK),!0}catch{return!1}}l(isExecutableFile,"isExecutableFile"),r(isExecutableFile,"isExecutableFile");function resolveTsgoPackageDir(){try{return path.dirname(require.resolve(`${exports.TSGO_PACKAGE}/package.json`))}catch{}try{let s=path.dirname(require.resolve(exports.TSGO_PACKAGE));for(let t=0;t<6;t++){const i=path.join(s,"package.json");if(fs.existsSync(i))try{const{name:e}=JSON.parse(fs.readFileSync(i,"utf8"));if(e===exports.TSGO_PACKAGE)return s}catch{}const o=path.dirname(s);if(o===s)break;s=o}}catch{}return null}l(resolveTsgoPackageDir,"resolveTsgoPackageDir"),r(resolveTsgoPackageDir,"resolveTsgoPackageDir");function packageDeclaredBin(s){try{const{bin:t}=JSON.parse(fs.readFileSync(path.join(s,"package.json"),"utf8")),i=typeof t=="string"?t:t?.tsgo;return i?path.join(s,i):null}catch{return null}}l(packageDeclaredBin,"packageDeclaredBin"),r(packageDeclaredBin,"packageDeclaredBin");function ownBinCandidates(s,t){const i=path.resolve(s,"..","..",".bin"),o=shimNames(t).map(n=>path.join(i,n)),e=t==="win32"?null:packageDeclaredBin(s);return e?[e,...o]:o}l(ownBinCandidates,"ownBinCandidates"),r(ownBinCandidates,"ownBinCandidates");function resolveTsgoBin(s,t,i={}){const o=i.platform??process.platform,e=i.isExecutable??(p=>isExecutableFile(p,o));if(t)return e(t)?t:null;for(const p of shimNames(o)){const a=path.join(s,"node_modules",".bin",p);if(e(a))return a}const n=(i.ownPackageDir??resolveTsgoPackageDir)();return n?ownBinCandidates(n,o).find(e)??null:null}l(resolveTsgoBin,"resolveTsgoBin"),r(resolveTsgoBin,"resolveTsgoBin"),exports.TSGO_MISSING_CAUSE=`tsgo binary not found \u2014 @lensmcp/cluster depends on ${exports.TSGO_PACKAGE}, so an absent binary means an incomplete install (reinstall node_modules), a platform with no ${exports.TSGO_PACKAGE} build, or a LENSMCP_TSGO_BIN override pointing at a missing or non-executable file`;function reportTsgoUnavailable(s){try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:s.workspaceRoot,project:s.appName,tool:"tsgo",tsConfig:s.tsConfig,output:"",durationMs:0,toolError:s.detail,...s.eventFile?{eventFile:s.eventFile}:{}})}catch{}}l(reportTsgoUnavailable,"reportTsgoUnavailable"),r(reportTsgoUnavailable,"reportTsgoUnavailable");function writeShimTsconfig(s,t,i){const o=path.join(i,"tmp","lensmcp-tsgo");fs.mkdirSync(o,{recursive:!0});const e=path.join(o,`${s}.tsconfig.json`);return fs.writeFileSync(e,JSON.stringify({extends:t,compilerOptions:{module:"preserve",moduleResolution:"bundler",isolatedModules:!1,baseUrl:null}},null,2)),e}l(writeShimTsconfig,"writeShimTsconfig"),r(writeShimTsconfig,"writeShimTsconfig");class TsgoCheckPlugin{static{l(this,"TsgoCheckPlugin")}static{r(this,"TsgoCheckPlugin")}constructor(t){this.timer=null,this.inflight=null,this.shimPath=null,this.disabled=!1,this.opts=t,this.spawnImpl=t.spawnImpl??node_child_process_1.spawn}apply(t){t.hooks.done.tap("TsgoCheckPlugin",i=>{i.hasErrors()||this.schedule()})}schedule(){this.disabled||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.run(),this.opts.debounceMs??500),this.timer.unref?.())}publish(t){if(this.opts.publishEvents!==!1)try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,output:t.output,durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{},...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}run(){const t=resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath);if(!t){this.disabled=!0;const n=`${exports.TSGO_MISSING_CAUSE}. Type checking is disabled for the rest of this session`;console.warn(`[tsgo] ${this.opts.appName}: ${n}.`),this.publish({output:"",durationMs:0,toolError:n});return}this.inflight&&(this.inflight.kill("SIGTERM"),this.inflight=null),this.shimPath||(this.shimPath=writeShimTsconfig(this.opts.appName,this.opts.tsConfig,this.opts.workspaceRoot));const i=Date.now(),o=this.spawnImpl(t,["--noEmit","--pretty","false","-p",this.shimPath],{cwd:this.opts.workspaceRoot,stdio:["ignore","pipe","pipe"]});this.inflight=o;let e="";o.stdout?.on("data",n=>{e+=n.toString()}),o.stderr?.on("data",n=>{e+=n.toString()}),o.on("error",()=>{this.inflight===o&&(this.inflight=null),console.warn(`[tsgo] ${this.opts.appName}: failed to spawn ${t}`),this.publish({output:"",durationMs:Date.now()-i,toolError:`failed to spawn ${t}`})}),o.on("close",(n,p)=>{if(this.inflight===o&&(this.inflight=null),p)return;const a=Date.now()-i,h=(a/1e3).toFixed(1);if(n===0){console.log(`[tsgo] ${this.opts.appName}: types clean (${h}s)`),this.publish({output:"",durationMs:a});return}e.trim()&&process.stdout.write(e.endsWith(`
2
- `)?e:`${e}
3
- `);const c=(e.match(/error TS\d+/g)??[]).length;console.log(`[tsgo] ${this.opts.appName}: ${c} type error${c===1?"":"s"} (${h}s)`),this.publish({output:e,durationMs:a,...c===0?{toolError:`tsgo exited ${n} with no diagnostics: ${firstLine(e)}`}:{}})})}}exports.TsgoCheckPlugin=TsgoCheckPlugin;function firstLine(s){return s.trim().split(`
4
- `)[0]?.slice(0,300)??""}l(firstLine,"firstLine"),r(firstLine,"firstLine");
1
+ "use strict";var m=Object.defineProperty;var a=(e,t)=>m(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,c=a((e,t)=>d(e,"name",{value:t,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.TsgoCheckPlugin=exports.TSGO_MISSING_CAUSE=exports.TSGO_PACKAGE=void 0,exports.resolveTsgoPackageDir=resolveTsgoPackageDir,exports.resolveTsgoBin=resolveTsgoBin,exports.reportTsgoUnavailable=reportTsgoUnavailable,exports.effectivePaths=effectivePaths,exports.writeShimTsconfig=writeShimTsconfig;const tslib_1=require("tslib"),node_child_process_1=require("node:child_process"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),typecheck_bus_1=require("./typecheck-bus");exports.TSGO_PACKAGE="@typescript/native-preview";function shimNames(e){return e==="win32"?["tsgo.cmd","tsgo.exe"]:["tsgo"]}a(shimNames,"shimNames"),c(shimNames,"shimNames");function isExecutableFile(e,t){try{if(!fs.statSync(e).isFile())return!1}catch{return!1}if(t==="win32")return!0;try{return fs.accessSync(e,fs.constants.X_OK),!0}catch{return!1}}a(isExecutableFile,"isExecutableFile"),c(isExecutableFile,"isExecutableFile");function resolveTsgoPackageDir(){try{return path.dirname(require.resolve(`${exports.TSGO_PACKAGE}/package.json`))}catch{}try{let e=path.dirname(require.resolve(exports.TSGO_PACKAGE));for(let t=0;t<6;t++){const i=path.join(e,"package.json");if(fs.existsSync(i))try{const{name:n}=JSON.parse(fs.readFileSync(i,"utf8"));if(n===exports.TSGO_PACKAGE)return e}catch{}const s=path.dirname(e);if(s===e)break;e=s}}catch{}return null}a(resolveTsgoPackageDir,"resolveTsgoPackageDir"),c(resolveTsgoPackageDir,"resolveTsgoPackageDir");function packageDeclaredBin(e){try{const{bin:t}=JSON.parse(fs.readFileSync(path.join(e,"package.json"),"utf8")),i=typeof t=="string"?t:t?.tsgo;return i?path.join(e,i):null}catch{return null}}a(packageDeclaredBin,"packageDeclaredBin"),c(packageDeclaredBin,"packageDeclaredBin");function ownBinCandidates(e,t){const i=path.resolve(e,"..","..",".bin"),s=shimNames(t).map(o=>path.join(i,o)),n=t==="win32"?null:packageDeclaredBin(e);return n?[n,...s]:s}a(ownBinCandidates,"ownBinCandidates"),c(ownBinCandidates,"ownBinCandidates");function resolveTsgoBin(e,t,i={}){const s=i.platform??process.platform,n=i.isExecutable??(r=>isExecutableFile(r,s));if(t)return n(t)?t:null;for(const r of shimNames(s)){const l=path.join(e,"node_modules",".bin",r);if(n(l))return l}const o=(i.ownPackageDir??resolveTsgoPackageDir)();return o?ownBinCandidates(o,s).find(n)??null:null}a(resolveTsgoBin,"resolveTsgoBin"),c(resolveTsgoBin,"resolveTsgoBin"),exports.TSGO_MISSING_CAUSE=`tsgo binary not found \u2014 @lensmcp/cluster depends on ${exports.TSGO_PACKAGE}, so an absent binary means an incomplete install (reinstall node_modules), a platform with no ${exports.TSGO_PACKAGE} build, or a LENSMCP_TSGO_BIN override pointing at a missing or non-executable file`;function reportTsgoUnavailable(e){try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:e.workspaceRoot,project:e.appName,tool:"tsgo",tsConfig:e.tsConfig,output:"",durationMs:0,toolError:e.detail,...e.eventFile?{eventFile:e.eventFile}:{}})}catch{}}a(reportTsgoUnavailable,"reportTsgoUnavailable"),c(reportTsgoUnavailable,"reportTsgoUnavailable");function parseJsonc(e){let t="",i=!1,s=!1,n=!1;for(let o=0;o<e.length;o++){const r=e[o],l=e[o+1];if(s){r===`
2
+ `&&(s=!1,t+=r);continue}if(n){r==="*"&&l==="/"&&(n=!1,o++);continue}if(i){t+=r,r==="\\"?(t+=l??"",o++):r==='"'&&(i=!1);continue}if(r==='"'){i=!0,t+=r;continue}if(r==="/"&&l==="/"){s=!0,o++;continue}if(r==="/"&&l==="*"){n=!0,o++;continue}t+=r}try{return JSON.parse(t.replace(/,(\s*[}\]])/g,"$1"))}catch{return null}}a(parseJsonc,"parseJsonc"),c(parseJsonc,"parseJsonc");function resolveExtends(e,t){if(!e.startsWith(".")&&!path.isAbsolute(e))return null;const i=path.isAbsolute(e)?e:path.resolve(t,e);for(const s of[i,`${i}.json`,path.join(i,"tsconfig.json")])try{if(fs.statSync(s).isFile())return s}catch{}return null}a(resolveExtends,"resolveExtends"),c(resolveExtends,"resolveExtends");function effectivePaths(e,t=new Set){if(t.has(e))return null;t.add(e);let i;try{i=fs.readFileSync(e,"utf8")}catch{return null}const s=parseJsonc(i);if(!s)return null;const n=path.dirname(e),o=s.compilerOptions??{},r=Array.isArray(s.extends)?s.extends.filter(h=>typeof h=="string"):typeof s.extends=="string"?[s.extends]:[],l=c(()=>{for(const h of[...r].reverse()){const f=resolveExtends(h,n);if(!f)continue;const g=effectivePaths(f,t);if(g)return g}return null},"inherited"),p=o.paths,u=typeof o.baseUrl=="string"?path.resolve(n,o.baseUrl):void 0;if(!p){const h=l();return h?{paths:h.paths,anchorDir:u??h.anchorDir}:null}return{paths:p,anchorDir:u??l()?.anchorDir??n}}a(effectivePaths,"effectivePaths"),c(effectivePaths,"effectivePaths");function writeShimTsconfig(e,t,i){const s=path.join(i,"tmp","lensmcp-tsgo");fs.mkdirSync(s,{recursive:!0});const n=path.join(s,`${e}.tsconfig.json`),o=effectivePaths(t),r=o?Object.fromEntries(Object.entries(o.paths).map(([l,p])=>[l,(Array.isArray(p)?p:[]).map(u=>path.isAbsolute(u)?u:path.resolve(o.anchorDir,u))])):void 0;return fs.writeFileSync(n,JSON.stringify({extends:t,compilerOptions:{module:"preserve",moduleResolution:"bundler",isolatedModules:!1,baseUrl:null,...r&&Object.keys(r).length?{paths:r}:{}}},null,2)),n}a(writeShimTsconfig,"writeShimTsconfig"),c(writeShimTsconfig,"writeShimTsconfig");class TsgoCheckPlugin{static{a(this,"TsgoCheckPlugin")}static{c(this,"TsgoCheckPlugin")}constructor(t){this.timer=null,this.inflight=null,this.shimPath=null,this.disabled=!1,this.opts=t,this.spawnImpl=t.spawnImpl??node_child_process_1.spawn}apply(t){t.hooks.done.tap("TsgoCheckPlugin",i=>{i.hasErrors()||this.schedule()})}schedule(){this.disabled||(this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.run(),this.opts.debounceMs??500),this.timer.unref?.())}publish(t){if(this.opts.publishEvents!==!1)try{(0,typecheck_bus_1.publishTypecheckRun)({workspaceRoot:this.opts.workspaceRoot,project:this.opts.appName,tool:"tsgo",tsConfig:this.opts.tsConfig,output:t.output,durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{},...this.opts.eventFile?{eventFile:this.opts.eventFile}:{}})}catch{}}run(){const t=resolveTsgoBin(this.opts.workspaceRoot,this.opts.binPath);if(!t){this.disabled=!0;const o=`${exports.TSGO_MISSING_CAUSE}. Type checking is disabled for the rest of this session`;console.warn(`[tsgo] ${this.opts.appName}: ${o}.`),this.publish({output:"",durationMs:0,toolError:o});return}this.inflight&&(this.inflight.kill("SIGTERM"),this.inflight=null),this.shimPath||(this.shimPath=writeShimTsconfig(this.opts.appName,this.opts.tsConfig,this.opts.workspaceRoot));const i=Date.now(),s=this.spawnImpl(t,["--noEmit","--pretty","false","-p",this.shimPath],{cwd:this.opts.workspaceRoot,stdio:["ignore","pipe","pipe"]});this.inflight=s;let n="";s.stdout?.on("data",o=>{n+=o.toString()}),s.stderr?.on("data",o=>{n+=o.toString()}),s.on("error",()=>{this.inflight===s&&(this.inflight=null),console.warn(`[tsgo] ${this.opts.appName}: failed to spawn ${t}`),this.publish({output:"",durationMs:Date.now()-i,toolError:`failed to spawn ${t}`})}),s.on("close",(o,r)=>{if(this.inflight===s&&(this.inflight=null),r)return;const l=Date.now()-i,p=(l/1e3).toFixed(1);if(o===0){console.log(`[tsgo] ${this.opts.appName}: types clean (${p}s)`),this.publish({output:"",durationMs:l});return}n.trim()&&process.stdout.write(n.endsWith(`
3
+ `)?n:`${n}
4
+ `);const u=(n.match(/error TS\d+/g)??[]).length;console.log(`[tsgo] ${this.opts.appName}: ${u} type error${u===1?"":"s"} (${p}s)`),this.publish({output:n,durationMs:l,...u===0?{toolError:`tsgo exited ${o} with no diagnostics: ${firstLine(n)}`}:{}})})}}exports.TsgoCheckPlugin=TsgoCheckPlugin;function firstLine(e){return e.trim().split(`
5
+ `)[0]?.slice(0,300)??""}a(firstLine,"firstLine"),c(firstLine,"firstLine");
@@ -68,6 +68,23 @@ export declare function resolveEventFile(workspaceRoot: string): string;
68
68
  */
69
69
  export declare function appendTypecheckEvents(eventFile: string, events: readonly TypecheckBusEvent[]): void;
70
70
  /** Parse a raw tsgo/tsc run and publish it. Returns the events written (for tests). */
71
+ /**
72
+ * Publish a run from diagnostics that are ALREADY structured.
73
+ *
74
+ * `publishTypecheckRun` exists for a checker we spawn ourselves and read text from. A checker
75
+ * running INSIDE webpack hands us `{file, line, column, code, message}` objects directly, and
76
+ * formatting those back into `file(1,2): error TS123: msg` only to re-parse them would be a
77
+ * round trip through a regex that can only lose information.
78
+ */
79
+ export declare function publishTypecheckDiagnostics(args: {
80
+ workspaceRoot: string;
81
+ project: string;
82
+ tool: string;
83
+ tsConfig?: string;
84
+ diagnostics: readonly TscDiagnostic[];
85
+ durationMs: number;
86
+ eventFile?: string;
87
+ }): TypecheckBusEvent[];
71
88
  export declare function publishTypecheckRun(args: {
72
89
  workspaceRoot: string;
73
90
  project: string;
package/typecheck-bus.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var g=Object.defineProperty;var s=(t,e)=>g(t,"name",{value:e,configurable:!0});var f=Object.defineProperty,i=s((t,e)=>f(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_DIAGNOSTICS_PER_RUN=void 0,exports.stripAnsi=stripAnsi,exports.parseTscDiagnosticLine=parseTscDiagnosticLine,exports.parseTscOutput=parseTscOutput,exports.buildTypecheckRunEvents=buildTypecheckRunEvents,exports.resolveEventFile=resolveEventFile,exports.appendTypecheckEvents=appendTypecheckEvents,exports.publishTypecheckRun=publishTypecheckRun;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),busHygiene=(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})(),DIAG_LINE_REGEX=/^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/,ANSI_CSI=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function stripAnsi(t){return t.replace(ANSI_CSI,"")}s(stripAnsi,"stripAnsi"),i(stripAnsi,"stripAnsi");function parseTscDiagnosticLine(t){const e=stripAnsi(t).trim();if(!e)return null;const n=DIAG_LINE_REGEX.exec(e);if(!n)return null;const[,o,l,u,c,a,p]=n;return!o||!l||!u||!c||!a||!p?null:{file:o,line:Number(l),column:Number(u),severity:c==="warning"?"warning":"error",code:a,message:p}}s(parseTscDiagnosticLine,"parseTscDiagnosticLine"),i(parseTscDiagnosticLine,"parseTscDiagnosticLine");function parseTscOutput(t){const e=[];for(const n of t.split(`
2
- `)){const o=parseTscDiagnosticLine(n);o&&e.push(o)}return e}s(parseTscOutput,"parseTscOutput"),i(parseTscOutput,"parseTscOutput"),exports.MAX_DIAGNOSTICS_PER_RUN=200;let idCounter=0;function makeId(){return idCounter=(idCounter+1)%65535,`${Date.now().toString(36)}${idCounter.toString(36)}${Math.random().toString(36).slice(2,8)}`}s(makeId,"makeId"),i(makeId,"makeId");function buildTypecheckRunEvents(t){const e=(t.now??Date.now)(),n=t.idImpl??makeId,o="pending",l={sessionId:o,source:"typescript",category:"typecheck",context:{sessionId:o,projectName:t.project}},u={project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{}},c=t.diagnostics.filter(r=>r.severity==="error"),a=t.diagnostics.slice(0,exports.MAX_DIAGNOSTICS_PER_RUN),p=[];if(!t.toolError){p.push({...l,id:n(),timestamp:e,severity:"info",title:`tsc clear: ${t.project}`,message:`typecheck run starting for ${t.project}`,fingerprint:`tsc:${t.project}:run-start`,raw:{...u,kind:"typecheck-run",phase:"start"}});for(const r of a)p.push({...l,id:n(),timestamp:e,severity:r.severity,title:`${r.code}: ${r.message}`,message:r.message,location:{file:r.file,line:r.line,column:r.column},fingerprint:`tsc:${t.project}:${r.file}:${r.line}:${r.column}:${r.code}`,raw:{...u,kind:"typecheck-diagnostic",code:r.code}})}const d=t.toolError?"error":c.length>0?"failing":"clean";return p.push({...l,id:n(),timestamp:e,severity:"info",title:`typecheck run: ${t.project} \u2014 ${t.toolError?"tool error":`${c.length} error${c.length===1?"":"s"}`} (${t.durationMs}ms)`,...t.toolError?{message:t.toolError}:{},fingerprint:`tsc:${t.project}:run-end`,raw:{...u,kind:"typecheck-run",phase:"end",status:d,durationMs:t.durationMs,errorCount:c.length,warningCount:t.diagnostics.length-c.length,...t.diagnostics.length>a.length?{truncatedDiagnostics:t.diagnostics.length-a.length}:{},...t.toolError?{error:t.toolError}:{}}}),p}s(buildTypecheckRunEvents,"buildTypecheckRunEvents"),i(buildTypecheckRunEvents,"buildTypecheckRunEvents");function resolveEventFile(t){return process.env.LENSMCP_EVENT_FILE||path.join(t,".lensmcp","events.jsonl")}s(resolveEventFile,"resolveEventFile"),i(resolveEventFile,"resolveEventFile");let ensuredDir=null;function ensureDir(t){const e=path.dirname(t);ensuredDir!==e&&(fs.mkdirSync(e,{recursive:!0}),ensuredDir=e)}s(ensureDir,"ensureDir"),i(ensureDir,"ensureDir");function appendTypecheckEvents(t,e){if(e.length===0)return;const n=e.map(o=>JSON.stringify(o)).join(`
1
+ "use strict";var d=Object.defineProperty;var s=(e,r)=>d(e,"name",{value:r,configurable:!0});var f=Object.defineProperty,i=s((e,r)=>f(e,"name",{value:r,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.MAX_DIAGNOSTICS_PER_RUN=void 0,exports.stripAnsi=stripAnsi,exports.parseTscDiagnosticLine=parseTscDiagnosticLine,exports.parseTscOutput=parseTscOutput,exports.buildTypecheckRunEvents=buildTypecheckRunEvents,exports.resolveEventFile=resolveEventFile,exports.appendTypecheckEvents=appendTypecheckEvents,exports.publishTypecheckDiagnostics=publishTypecheckDiagnostics,exports.publishTypecheckRun=publishTypecheckRun;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),busHygiene=(()=>{try{return require("@lensmcp/node-instrumentation")}catch{return}})(),DIAG_LINE_REGEX=/^(.+?)\((\d+),(\d+)\):\s+(error|warning)\s+(TS\d+):\s+(.+)$/,ANSI_CSI=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function stripAnsi(e){return e.replace(ANSI_CSI,"")}s(stripAnsi,"stripAnsi"),i(stripAnsi,"stripAnsi");function parseTscDiagnosticLine(e){const r=stripAnsi(e).trim();if(!r)return null;const o=DIAG_LINE_REGEX.exec(r);if(!o)return null;const[,t,u,l,c,a,p]=o;return!t||!u||!l||!c||!a||!p?null:{file:t,line:Number(u),column:Number(l),severity:c==="warning"?"warning":"error",code:a,message:p}}s(parseTscDiagnosticLine,"parseTscDiagnosticLine"),i(parseTscDiagnosticLine,"parseTscDiagnosticLine");function parseTscOutput(e){const r=[];for(const o of e.split(`
2
+ `)){const t=parseTscDiagnosticLine(o);t&&r.push(t)}return r}s(parseTscOutput,"parseTscOutput"),i(parseTscOutput,"parseTscOutput"),exports.MAX_DIAGNOSTICS_PER_RUN=200;let idCounter=0;function makeId(){return idCounter=(idCounter+1)%65535,`${Date.now().toString(36)}${idCounter.toString(36)}${Math.random().toString(36).slice(2,8)}`}s(makeId,"makeId"),i(makeId,"makeId");function buildTypecheckRunEvents(e){const r=(e.now??Date.now)(),o=e.idImpl??makeId,t="pending",u={sessionId:t,source:"typescript",category:"typecheck",context:{sessionId:t,projectName:e.project}},l={project:e.project,tool:e.tool,...e.tsConfig?{tsConfig:e.tsConfig}:{}},c=e.diagnostics.filter(n=>n.severity==="error"),a=e.diagnostics.slice(0,exports.MAX_DIAGNOSTICS_PER_RUN),p=[];if(!e.toolError){p.push({...u,id:o(),timestamp:r,severity:"info",title:`tsc clear: ${e.project}`,message:`typecheck run starting for ${e.project}`,fingerprint:`tsc:${e.project}:run-start`,raw:{...l,kind:"typecheck-run",phase:"start"}});for(const n of a)p.push({...u,id:o(),timestamp:r,severity:n.severity,title:`${n.code}: ${n.message}`,message:n.message,location:{file:n.file,line:n.line,column:n.column},fingerprint:`tsc:${e.project}:${n.file}:${n.line}:${n.column}:${n.code}`,raw:{...l,kind:"typecheck-diagnostic",code:n.code}})}const g=e.toolError?"error":c.length>0?"failing":"clean";return p.push({...u,id:o(),timestamp:r,severity:"info",title:`typecheck run: ${e.project} \u2014 ${e.toolError?"tool error":`${c.length} error${c.length===1?"":"s"}`} (${e.durationMs}ms)`,...e.toolError?{message:e.toolError}:{},fingerprint:`tsc:${e.project}:run-end`,raw:{...l,kind:"typecheck-run",phase:"end",status:g,durationMs:e.durationMs,errorCount:c.length,warningCount:e.diagnostics.length-c.length,...e.diagnostics.length>a.length?{truncatedDiagnostics:e.diagnostics.length-a.length}:{},...e.toolError?{error:e.toolError}:{}}}),p}s(buildTypecheckRunEvents,"buildTypecheckRunEvents"),i(buildTypecheckRunEvents,"buildTypecheckRunEvents");function resolveEventFile(e){return process.env.LENSMCP_EVENT_FILE||path.join(e,".lensmcp","events.jsonl")}s(resolveEventFile,"resolveEventFile"),i(resolveEventFile,"resolveEventFile");let ensuredDir=null;function ensureDir(e){const r=path.dirname(e);ensuredDir!==r&&(fs.mkdirSync(r,{recursive:!0}),ensuredDir=r)}s(ensureDir,"ensureDir"),i(ensureDir,"ensureDir");function appendTypecheckEvents(e,r){if(r.length===0)return;const o=r.map(t=>JSON.stringify(t)).join(`
3
3
  `)+`
4
- `;try{ensureDir(t),busHygiene?.maybeRotateEventFile(t,n.length),fs.appendFileSync(t,n)}catch(o){if(o?.code==="ENOENT"){try{ensuredDir=null,ensureDir(t),fs.appendFileSync(t,n)}catch{}return}}}s(appendTypecheckEvents,"appendTypecheckEvents"),i(appendTypecheckEvents,"appendTypecheckEvents");function publishTypecheckRun(t){const e=buildTypecheckRunEvents({project:t.project,tool:t.tool,...t.tsConfig?{tsConfig:t.tsConfig}:{},diagnostics:t.toolError?[]:parseTscOutput(t.output),durationMs:t.durationMs,...t.toolError?{toolError:t.toolError}:{}});return appendTypecheckEvents(t.eventFile??resolveEventFile(t.workspaceRoot),e),e}s(publishTypecheckRun,"publishTypecheckRun"),i(publishTypecheckRun,"publishTypecheckRun");
4
+ `;try{ensureDir(e),busHygiene?.maybeRotateEventFile(e,o.length),fs.appendFileSync(e,o)}catch(t){if(t?.code==="ENOENT"){try{ensuredDir=null,ensureDir(e),fs.appendFileSync(e,o)}catch{}return}}}s(appendTypecheckEvents,"appendTypecheckEvents"),i(appendTypecheckEvents,"appendTypecheckEvents");function publishTypecheckDiagnostics(e){const r=buildTypecheckRunEvents({project:e.project,tool:e.tool,...e.tsConfig?{tsConfig:e.tsConfig}:{},diagnostics:e.diagnostics,durationMs:e.durationMs});return appendTypecheckEvents(e.eventFile??resolveEventFile(e.workspaceRoot),r),r}s(publishTypecheckDiagnostics,"publishTypecheckDiagnostics"),i(publishTypecheckDiagnostics,"publishTypecheckDiagnostics");function publishTypecheckRun(e){const r=buildTypecheckRunEvents({project:e.project,tool:e.tool,...e.tsConfig?{tsConfig:e.tsConfig}:{},diagnostics:e.toolError?[]:parseTscOutput(e.output),durationMs:e.durationMs,...e.toolError?{toolError:e.toolError}:{}});return appendTypecheckEvents(e.eventFile??resolveEventFile(e.workspaceRoot),r),r}s(publishTypecheckRun,"publishTypecheckRun"),i(publishTypecheckRun,"publishTypecheckRun");