diff --git a/.claude/docs/v1.2.1/sessions/56b-modernize-ts.md b/.claude/docs/v1.2.1/sessions/56b-modernize-ts.md new file mode 100644 index 00000000..9d936154 --- /dev/null +++ b/.claude/docs/v1.2.1/sessions/56b-modernize-ts.md @@ -0,0 +1,84 @@ +# Session log: #56 (part B) — modernize the TypeScript idioms + +Date: 2026-11-25. Branch `claude/project-thread-n2s3q6-modernize-ts`, cut from `origin/v1.2.1` at `a2d92672` (after #35 parts A and B, PRs #61/#63, and #56 part A, PR #62). Story: Code-XR-Project/Code-XR#56 (epic #26). Plan: `docs/cleanup/modernization.md` §5, rows 1 (TypeScript part) and 4–10; the measured before/after table is its §7. Part A (Python and browser runtimes) is `56a-modernize-py-js.md`. + +## Commits + +| Commit | Subject | Plan row | Proof | +|---|---|---|---| +| `3e282b4c` | chore(lint): lock the TypeScript idioms already at zero | 1 | config only | +| `2308d6c0` | refactor(ts): static imports for Node built-ins | 4 | H2 (+802 B: hoisted requires, one `__importStar` helper) | +| `27bfec86` | refactor(ts): slice() instead of substr(), lock includes() and slice() | 5 | H2 (one statement) | +| `9e2506ec` | refactor(ts): optional chaining where it is safe | 6 | H2 (10 sites) | +| `bf60a7a1` | refactor(ts): template literals instead of string concatenation | 7 | H2 (8 sites) + byte-identical SSE script output | +| `55d5c819` | refactor(ts): type the any in code_analysis/views/subsections/active_analyses | 8 | H1 `3838d8e16de4` | +| `9c873f6e` | refactor(ts): type the any in code_analysis/services | 8 | H1 `3838d8e16de4` | +| `d335a157` | refactor(ts): type the any in code_analysis/engine/watchers | 8 | H1 `3838d8e16de4` | +| `552825a0` | refactor(ts): type the any in active_servers (model, registry, registrar) | 8 | H1 `3838d8e16de4` | +| `12f9599b` | refactor(ts): typed metadata.sessionId lookup in serverControl, lock active_servers | 8 + 6 | H2 (one statement) | +| `cd83e65e` | refactor(ts): ?? for object-typed defaults | 9 | H2 (48 `??`, 43 statements) | + +Row 10 has no commit: none of the 24 `.then()` qualifies (see below). + +## Measurements + +| Metric | Before | After | +|---|---:|---:| +| `npm test` | 1053/1053 | 1056/1056 (+3 lint-contract tests) | +| ESLint warning budget (`eslint.maxWarnings`) | 204 | 158 | +| `any.total` (guardrail) | 130 | 84 | +| `complexity.over10` / `over15` | 54 / 9 | 53 / 8 | +| inline `require()` of built-ins | 7 | 0 | +| `substr()` | 1 | 0 | +| typed `prefer-optional-chain` reports | 10 | 0 | +| `prefer-template` reports | 8 | 0 | +| typed `prefer-nullish-coalescing` (`ignorePrimitives` all) | 76 (60 `\|\|`, 15 if-assign, 1 ternary) | 12 `\|\|` kept, in 8 exempted files | +| `dist/extension.js` (production, no source maps) | `b4c1894828cd`, 1,194,230 B | `983cfe36a26d`, 1,194,977 B | + +The bundle grows 747 B in total, all of it from row 4 (the hoisted `require`s rename minifier locals and add TypeScript's `__importStar` helper to `SSEManager`); every other row is neutral or smaller. + +## How the changes were proved + +- **Types-only commits (row 8)**: the production bundle (`CODEXR_NO_SOURCEMAPS=1 npm run package`) is byte-identical to the parent, `3838d8e16de4`, each time. One `any` pair (`serverControl.ts`'s `(server.metadata as any).sessionId`) could not be typed in a dist-identical commit: once typed, `prefer-optional-chain` forces `?.`, so it is its own H2 commit (`12f9599b`). +- **H2 commits**: the minified bundle split on `;` and diffed against the parent; every changed statement is listed in the commit body. +- **Generated HTML (row 7)**: `CreateStructure.getSSEScriptWithNonce` was run from `out/` under the fake vscode, for `xr`, `dom` and `none`, before and after: same length and sha256. +- **`??` (row 9)**: converted only where the left operand is object-typed **and** produced by this code (Map/find over stored objects, internal call results, internal optional parameters). Parsed JSON from WebSocket clients and the analysis bridge, workspace storage and settings updates keep `||`, because a malformed `0`, `''` or `false` must still fall back. +- **Text pins**: every touched file grepped by basename in `test/` and `scripts/`, pins classified in each commit body. Row 9 also checked every `\|\|` / `\?\?` regex of the suites that read the touched files: one S pin found and kept. + +## Gates + +`npm run typecheck`, `npm run lint` and `npm test` after every commit; `npm run test:analysis` after rows 7 (executePython touched) and 9 (export code touched), both green. `guardrails:update` in every commit that moved a metric. + +## Deliberately not done + +- **Row 10 (`await` instead of `.then()`)**: 0 of 24. Every `.then()` is a fire-and-forget user prompt (`void vscode.window.showXMessage(…).then(choice => …)`, 18), the HTTP request handler's `routeRequest(…).then().catch()` (converting needs an async handler, and `HttpServer` is §4 territory), promise caches/queues whose promise is stored, not awaited (`gitTimelineBlobIndex` 2, `gitTimelineBlobAnalyzer` 1, `gitAnalysisEligibility` 2), `void job.then(clear, clear)` in `dependencyGraphService`, or `.then(resolve, reject)` inside a `new Promise` (`cloudflaredBinaryManager`, §4). +- **`projectEvolutionService.ts:421`** keeps `|| null`: `historicalComparison.test.cjs:467` pins `source.kind === 'workingCopy') || null` verbatim (S pin). Relaxing it needs a characterization commit first. +- **The 11 other `||` of row 9** (WebSocket/bridge payloads, storage, settings): not provably free of `''`/`0`/`false` at runtime. +- **The 18 remaining concatenations** of the A.1 row: literal + literal line wraps of long messages; `prefer-template` does not report them and they read better as they are. +- **`a && a.b` left by the script (2)**: `serverWatcherIntegration.ts:151` (`server.metadata && server.metadata.sessionId === sessionId` — not equivalent when `sessionId` is undefined) and `sharedChartTypeSettingCore.ts:103` (not reported by the typed rule). +- **Row 8 beyond 4 folders**: `utils/commandBuilder.ts` (generic `TArgs extends any[]`), `utils/jsonFieldAnalyzer.ts` (`unknown` would need narrowing code, not types), `executePython.ts`'s `PythonPayload = any` and the pinned `parsePythonOutput(…): any` signature, and the rest listed in modernization.md §7. +- §4 items: enums, `new Promise` wrappers, sync `fs` in async functions, `HttpServer.stop()` order, the XR field-schema contract, the 8 lazy requires of the tree provider: untouched. + +## Design notes + +- `ActiveServer.serverInstance` is typed by a structural `ActiveServerRuntime` interface in the model rather than `ServerInstance` from `servers/runtime/serverFactory`: importing the latter (even `import type`) made the model, registry and registrar lose their vscode-free status, and `dependencyDirection.test.cjs`'s floor (109) went red. +- `ActiveServer.metadata` became `ActiveServerMetadata` (the read fields plus `sessionId`, with an `unknown` index signature for what the launcher records). The model used to declare three fields while the registry stored anything. +- The per-folder `no-explicit-any: error` lives in a flat-config block named `codexr/any-free-folders`; the lint contract test excludes that one named block from its "budget rules stay warnings" check and pins it to that single rule over existing `src/` folders. + +## Quirks found (record only, for 1.3.0) + +- `ActiveAnalysesDataService.getSubsectionItem()` returns a plain object where its caller expects a `CodeAnalysisTreeItem`; it type-checks structurally, but it is not an instance. +- `metadata.sessionId` reaches the registry only through the launcher's `additionalMetadata` spread (`serverLaunchOrchestrator.ts` passes `{ sessionId }`), which `ActiveServer.metadata` did not declare until this session; it is now an optional field of `ActiveServerMetadata`. + +## CHANGELOG + +No line: nothing a user can notice. Covered by the existing "Internal improvements" summary. + +## F5 checks for the maintainer + +1. Active Analyses: run a directory analysis (XR and LivePanel); left-click an entry (actions quick pick), Show Details, View in Browser, Export folder, Close Analysis. +2. Stop the analysis server from Active Servers: the analysis is cleaned up and the notification names the port. +3. Edit a file in an analyzed directory: the incremental re-analysis updates the scene/panel (XR and LivePanel), including adding and deleting a file. +4. Active Servers tooltip shows `File: ` for a served HTML file; Open in Browser works on HTTP and HTTPS servers. +5. Collaboration: join a room, transfer host, kick a participant, presenter stop (paths with `?? {}` defaults around them). +6. Visualize Data: pick a chart, a JSON file and map dimensions; the field list shows "N values • Samples: …". diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 9c0c4f4d..ce5ce528 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -105,6 +105,79 @@ export default [{ "@typescript-eslint/no-floating-promises": ["error", { checkThenables: true }], "@typescript-eslint/no-misused-promises": "warn", }, +}, { + // Modernized idioms (story #56, docs/cleanup/modernization.md §1 and §7). + // Each rule landed in the commit that brought its idiom to zero in src/, so + // the count can only stay there. Exceptions are per-file overrides below, + // never eslint-disable comments (the suppressions guardrail is at 0). + files: ["src/**/*.ts"], + rules: { + "no-var": "error", + "prefer-rest-params": "error", + "@typescript-eslint/no-namespace": "error", + "@typescript-eslint/no-unsafe-function-type": "error", + "@typescript-eslint/no-require-imports": "error", + "@typescript-eslint/prefer-includes": "error", + "@typescript-eslint/prefer-optional-chain": "error", + "prefer-template": "error", + "no-restricted-properties": ["error", { + property: "substr", + message: "Use slice() (substr is Annex B legacy; slice(start, start + length) for non-negative arguments).", + }], + // `??` only where the left operand is object-typed: '' || d and '' ?? d + // differ, and settings or user JSON carry real '', 0 and false values, + // so primitive operands, ternaries and if-assignments are not reported. + "@typescript-eslint/prefer-nullish-coalescing": ["error", { + ignorePrimitives: { string: true, number: true, boolean: true, bigint: true }, + ignoreTernaryTests: true, + ignoreIfStatements: true, + }], + }, +}, { + // Files that keep an object-typed `x || {}` on purpose: the operand is + // parsed JSON from a WebSocket client, the bridge protocol, workspace + // storage or a settings update, where a malformed `0`, `''` or `false` + // must still fall back to the default (modernization.md §7, row 9). + files: [ + // historicalComparison.test.cjs pins `source.kind === 'workingCopy') || null` here (S pin). + "src/code_analysis/historical/projectEvolutionService.ts", + "src/servers/runtime/analysis/dependencyGraphBridge.ts", + "src/servers/runtime/analysis/projectEvolutionBridge.ts", + "src/servers/runtime/collaboration/collaborationRoomServer.ts", + "src/servers/runtime/collaboration/roomSharedState.ts", + "src/servers/storage/serverSettingsManager.ts", + "src/visualize_data/state/visualizeDataState.ts", + "src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts", + ], + rules: { + "@typescript-eslint/prefer-nullish-coalescing": "off", + }, +}, { + // The lazy require() calls that stay (modernization.md §4): the eight in + // the tree provider are load-bearing (cleanup skill §4), and the other two + // defer a relative import to break a load-time module cycle. + files: [ + "src/views/ModularTreeDataProvider.ts", + "src/code_analysis/engine/watchers/directoryReAnalyzer.ts", + "src/utils/getVisualizationConfiguration.ts", + ], + rules: { + "@typescript-eslint/no-require-imports": "off", + }, +}, { + // Folders whose `any`s were typed away (story #56, modernization.md §7): + // there no-explicit-any is an error, not a budget warning. A folder joins + // the list in the commit that brings it to zero. + name: "codexr/any-free-folders", + files: [ + "src/active_servers/**/*.ts", + "src/code_analysis/engine/watchers/**/*.ts", + "src/code_analysis/services/**/*.ts", + "src/code_analysis/views/subsections/active_analyses/**/*.ts", + ], + rules: { + "@typescript-eslint/no-explicit-any": "error", + }, }, { files: NO_CONSOLE_FILES, ignores: CONSOLE_ALLOWLIST, diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index 4da2b1dc..8ba181cb 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 204", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 158", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/active_servers/model/activeServerModel.ts b/apps/vscode-extension/src/active_servers/model/activeServerModel.ts index 51f9a7cf..0e3c2b06 100644 --- a/apps/vscode-extension/src/active_servers/model/activeServerModel.ts +++ b/apps/vscode-extension/src/active_servers/model/activeServerModel.ts @@ -53,14 +53,35 @@ export interface ActiveServer { customName?: string; /** Server instance reference for control operations */ - serverInstance?: any; + serverInstance?: ActiveServerRuntime; /** Additional metadata */ - metadata?: { - host?: string; - staticRoot?: string; - description?: string; - }; + metadata?: ActiveServerMetadata; +} + +/** + * The runtime behind a registered server (HttpServer or one of the HTTPS + * servers). Declared structurally, with only what the extension calls on it, + * so this model stays free of the server runtime and of vscode. + */ +export interface ActiveServerRuntime { + stop(): Promise; + forceStop(): void; + createAuthenticatedBrowserUrl(baseUrl: string): string; +} + +/** + * Registration metadata, stored as given: the fields the extension reads, + * plus whatever the launcher records (serverType, originalPort, portChanged, + * launcherId, ...) and its callers add. + */ +export interface ActiveServerMetadata { + host?: string; + staticRoot?: string; + description?: string; + /** The analysis session the server serves, when the registration names one. */ + sessionId?: string; + [field: string]: unknown; } /** diff --git a/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts b/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts index d7c20f8f..39bb2b54 100644 --- a/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts +++ b/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'events'; -import { ActiveServer, RegistryEvent, RegistryEventType, LaunchMode, CertMode } from '../model/activeServerModel'; +import { ActiveServer, ActiveServerMetadata, ActiveServerRuntime, RegistryEvent, RegistryEventType, LaunchMode, CertMode } from '../model/activeServerModel'; import { RemoteAccessState } from '../../remote_access/model/remoteAccessModel'; import { getLogger } from '../../core/logging/sink'; @@ -81,8 +81,8 @@ export class ActiveServerRegistry { timestamp: number; htmlFile?: string; customName?: string; - serverInstance?: any; - metadata?: any; + serverInstance?: ActiveServerRuntime; + metadata?: ActiveServerMetadata; }): ActiveServer { logger.debug('SERVER: registerServer called with config:', { port: config.port, @@ -343,8 +343,8 @@ export function registerActiveServer(config: { timestamp: number; htmlFile?: string; customName?: string; - serverInstance?: any; - metadata?: any; + serverInstance?: ActiveServerRuntime; + metadata?: ActiveServerMetadata; }): ActiveServer { return getActiveServerRegistry().registerServer(config); } diff --git a/apps/vscode-extension/src/active_servers/runtime/serverControl.ts b/apps/vscode-extension/src/active_servers/runtime/serverControl.ts index e5aa6de6..252aebce 100644 --- a/apps/vscode-extension/src/active_servers/runtime/serverControl.ts +++ b/apps/vscode-extension/src/active_servers/runtime/serverControl.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode'; -import { ActiveServer } from '../model/activeServerModel'; +import { ActiveServer, ActiveServerRuntime } from '../model/activeServerModel'; +import type { UnifiedAnalysisSession } from '../../code_analysis/engine/core/analysisSession'; import { getActiveServerRegistry } from '../registry/activeServerRegistry'; import { getPanelManager } from '../services/panelManager'; import { fileToServerMap } from '../../utils/fileToServerMap'; @@ -117,7 +118,7 @@ export class ServerControl { * Await the instance's graceful stop, falling back to a forced socket close * if it hangs or fails. Returns false when the shutdown was not clean. */ - private static async stopInstanceOrForce(serverId: string, instance: any): Promise { + private static async stopInstanceOrForce(serverId: string, instance: ActiveServerRuntime): Promise { let timer: NodeJS.Timeout | undefined; try { await Promise.race([ @@ -220,7 +221,7 @@ export class ServerControl { const allSessions = sessionRegistry.getAllSessions(); logger.debug(() => `DEBUG - Found ${allSessions.length} active analysis sessions`); - allSessions.forEach((session: any, index: number) => { + allSessions.forEach((session: UnifiedAnalysisSession, index: number) => { logger.debug(() => `DEBUG - Session ${index + 1}:`, { id: session.id, targetPath: session.targetPath, @@ -233,8 +234,8 @@ export class ServerControl { let associatedSession = null; // Try to find by sessionId in server metadata (when implemented) - if (server.metadata && (server.metadata as any).sessionId) { - const sessionId = (server.metadata as any).sessionId; + if (server.metadata?.sessionId) { + const sessionId = server.metadata.sessionId; logger.debug(() => `DEBUG - Trying to find session by metadata sessionId: ${sessionId}`); associatedSession = sessionRegistry.getSession(sessionId); if (associatedSession) { diff --git a/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts b/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts index bca0cebd..750586c0 100644 --- a/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts +++ b/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts @@ -1,4 +1,4 @@ -import { ActiveServer, LaunchMode, CertMode } from '../model/activeServerModel'; +import { ActiveServer, ActiveServerMetadata, ActiveServerRuntime, LaunchMode, CertMode } from '../model/activeServerModel'; import { registerActiveServer } from '../registry/activeServerRegistry'; import { getLogger } from '../../core/logging/sink'; @@ -15,8 +15,8 @@ export interface ServerRegistrationConfig { timestamp: number; htmlFile?: string; customName?: string; - serverInstance?: any; - metadata?: any; + serverInstance?: ActiveServerRuntime; + metadata?: ActiveServerMetadata; } /** diff --git a/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts b/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts index b81193b6..436ae41e 100644 --- a/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts +++ b/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts @@ -18,7 +18,7 @@ export function getServerLabel(server: ActiveServer): string { * Format server details for display */ export function formatServerDetails(server: ActiveServer): string { - const metadata = (server.metadata || {}) as Record; + const metadata = (server.metadata ?? {}) as Record; const remote = server.remoteAccess; const protocol = server.certMode === 'http' ? 'http' : 'https'; const lanUrl = NetworkUtils.getPrimaryExternalUrl(server.port, protocol); diff --git a/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts b/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts index e8c9ca73..8b175898 100644 --- a/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts +++ b/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts @@ -29,7 +29,7 @@ export class CreateChart { // Every chart — boats included — comes from the single canonical // template list; a duplicated boats fallback used to live here and // drifted from the real one. - const chart = chartTemplates.find((candidate) => candidate.id === chartId) || null; + const chart = chartTemplates.find((candidate) => candidate.id === chartId) ?? null; if (!chart) { return { success: false, @@ -216,7 +216,7 @@ export class CreateChart { * Get chart metadata by ID */ public static getChartMetadata(chartId: string): ChartMetadata | null { - return chartTemplates.find(c => c.id === chartId) || null; + return chartTemplates.find(c => c.id === chartId) ?? null; } /** diff --git a/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts b/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts index 958c6223..735b7611 100644 --- a/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts +++ b/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts @@ -135,7 +135,7 @@ export class CreateStructure { // Add nonce script tag for main.js (standard path for all analyses) const mainJsScript = ``; - return scriptContent + '\n' + mainJsScript; + return `${scriptContent}\n${mainJsScript}`; } catch (error) { logger.error(`Error loading SSE script:`, error); diff --git a/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts b/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts index 37a6b334..be3bc2c6 100644 --- a/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts +++ b/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts @@ -101,8 +101,8 @@ export class TemplateHTMLProcessor { jsContentType: typeof returnResult.jsContent }); - logger.debug('DEBUG - indexHtml preview:', returnResult.indexHtml?.substring(0, 100) + '...'); - logger.debug('DEBUG - jsContent preview:', returnResult.jsContent?.substring(0, 100) + '...'); + logger.debug('DEBUG - indexHtml preview:', `${returnResult.indexHtml?.substring(0, 100)}...`); + logger.debug('DEBUG - jsContent preview:', `${returnResult.jsContent?.substring(0, 100)}...`); return returnResult; diff --git a/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts b/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts index f4ee7080..0a92587f 100644 --- a/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts +++ b/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts @@ -37,7 +37,7 @@ export class CodeAnalysisCommands { ): CommandRegistration[] { logger.debug('Collecting all command registrations'); - const defaultRefreshCallback = refreshCallback || (() => { + const defaultRefreshCallback = refreshCallback ?? (() => { logger.debug('Default refresh callback executed'); }); diff --git a/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts b/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts index 8f729cff..9447f4bd 100644 --- a/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts +++ b/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts @@ -3,6 +3,7 @@ * Commands for analyzing directories in LivePanel mode. */ +import * as path from 'path'; import * as vscode from 'vscode'; import { AnalysisOrchestrator } from '../../engine/analysisOrchestrator'; import { CommandRegistration } from '../subsections/analysis_settings/analysis_file_mode'; @@ -47,7 +48,7 @@ export class DirectoryAnalysisLivePanelCommands { if (stat.type === vscode.FileType.Directory) { directoryPath = uri.fsPath; } else { - directoryPath = require('path').dirname(uri.fsPath); + directoryPath = path.dirname(uri.fsPath); } } else if (vscode.workspace.workspaceFolders?.length) { if (vscode.workspace.workspaceFolders.length === 1) { @@ -65,7 +66,7 @@ export class DirectoryAnalysisLivePanelCommands { void vscode.window.showWarningMessage('CodeXR: No directory selected for LivePanel analysis'); return; } - directoryPath = require('path').dirname(activeEditor.document.fileName); + directoryPath = path.dirname(activeEditor.document.fileName); } await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'LivePanel', 'directory', this.context, false); @@ -88,7 +89,7 @@ export class DirectoryAnalysisLivePanelCommands { const stat = await vscode.workspace.fs.stat(uri); directoryPath = stat.type === vscode.FileType.Directory ? uri.fsPath - : require('path').dirname(uri.fsPath); + : path.dirname(uri.fsPath); } else if (vscode.workspace.workspaceFolders?.length) { directoryPath = vscode.workspace.workspaceFolders[0].uri.fsPath; } else { @@ -97,7 +98,7 @@ export class DirectoryAnalysisLivePanelCommands { void vscode.window.showWarningMessage('CodeXR: No directory selected for LivePanel Deep analysis'); return; } - directoryPath = require('path').dirname(activeEditor.document.fileName); + directoryPath = path.dirname(activeEditor.document.fileName); } await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'LivePanel', 'directory', this.context, true); diff --git a/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts b/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts index 7b94da8c..948a7947 100644 --- a/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts +++ b/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts @@ -168,7 +168,7 @@ export class DependencyGraphService { onProgress?: (message: string) => void, ): Promise { const session = this.getSession(); - const refreshRequest: DependencyRefreshRequest = request || { + const refreshRequest: DependencyRefreshRequest = request ?? { sourceRevision: 0, changedFiles: [], addedFiles: [], diff --git a/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts b/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts index 63397f20..28251e5d 100644 --- a/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts +++ b/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts @@ -86,7 +86,7 @@ export class LauncherLivePanel { progress: { process: 20, save: 40, watcherOrServer: 60, serverOrWatcher: 80, done: 100 }, preValidation: async () => { - const files = session.filesToHash || []; + const files = session.filesToHash ?? []; logger.debug(() => `${LOG_PREFIX}: Directory session target path: ${session.targetPath}`); logger.debug(() => `${LOG_PREFIX}: Directory session deep mode: ${session.isDeep ? 'enabled' : 'disabled'}`); logger.debug(() => `${LOG_PREFIX}: Session currently tracks ${files.length} hashed files`); diff --git a/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts b/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts index c511cd32..d5ec1008 100644 --- a/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts +++ b/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts @@ -230,7 +230,7 @@ export class AnalysisBootstrap { ): void { const missingFiles = requiredFiles.filter((fileName) => { const content = loadedFiles.get(fileName); - return !content || !content.trim(); + return !content?.trim(); }); if (missingFiles.length > 0) { diff --git a/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts b/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts index 6f6702a5..94e0d8f8 100644 --- a/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts +++ b/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts @@ -75,7 +75,7 @@ export class ExecutePython { } public async executeXRFieldSchema(targetType: 'file' | 'directory'): Promise { - logger.debug(() => 'Loading XR field schema for ' + targetType); + logger.debug(() => `Loading XR field schema for ${targetType}`); return await this.executePythonScript('main.py', [ '--mode', 'schema', '--type', targetType, diff --git a/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts b/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts index 69e16345..be413b9b 100644 --- a/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts +++ b/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts @@ -12,6 +12,7 @@ import { SessionServerManager } from '../servers/sessionServerManager'; import { SHA256Generator } from '../../../utils/sha256Generator'; import { FileHashTracker } from './fileHashTracker'; import { + AnalysisFileEntry, createEmptyFileEntry, hasMatchingLivePanelFile, hasMatchingXRFile, @@ -29,9 +30,12 @@ import { getLogger } from '../../../core/logging/sink'; const logger = getLogger('DIRECTORY_REANALYZER'); +/** A parsed data.json, in either layout; `xrFormat` says which one. */ +type AnalysisData = XRAnalysisData | LivePanelAnalysisData; + interface IncrementalChangeSet { removedFiles?: string[]; - updatedResults?: any[]; + updatedResults?: AnalysisFileEntry[]; addedFiles?: string[]; } @@ -44,7 +48,7 @@ export class DirectoryReAnalyzer { this.sessionServerManager = new SessionServerManager(context); } - async reAnalyzeFiles(changedFiles: string[]): Promise { + async reAnalyzeFiles(changedFiles: string[]): Promise { try { logger.debug(() => `Re-analyzing ${changedFiles.length} changed files`); const result = await this.executePython.executeFileReanalysis(changedFiles); @@ -151,7 +155,7 @@ export class DirectoryReAnalyzer { } private applyRemovedFiles( - currentData: any, + currentData: AnalysisData, xrFormat: boolean, removedFiles: string[], hashTracker: FileHashTracker, @@ -160,8 +164,8 @@ export class DirectoryReAnalyzer { for (const removedPath of removedFiles) { const removed = xrFormat - ? removeDeletedFileFromXRFormat(currentData, removedPath) - : removeDeletedFileFromLivePanelFormat(currentData, removedPath); + ? removeDeletedFileFromXRFormat(currentData as XRAnalysisData, removedPath) + : removeDeletedFileFromLivePanelFormat(currentData as LivePanelAnalysisData, removedPath); if (removed) { hasChanges = true; @@ -173,18 +177,18 @@ export class DirectoryReAnalyzer { return hasChanges; } - private applyUpdatedResults(currentData: any, xrFormat: boolean, updatedResults: any[]): boolean { + private applyUpdatedResults(currentData: AnalysisData, xrFormat: boolean, updatedResults: AnalysisFileEntry[]): boolean { if (updatedResults.length === 0) { return false; } return xrFormat - ? upsertXRFiles(currentData, updatedResults) - : upsertLivePanelFiles(currentData, updatedResults); + ? upsertXRFiles(currentData as XRAnalysisData, updatedResults) + : upsertLivePanelFiles(currentData as LivePanelAnalysisData, updatedResults); } private async applyAddedFiles( - currentData: any, + currentData: AnalysisData, xrFormat: boolean, session: UnifiedAnalysisSession, addedFiles: string[], @@ -194,8 +198,8 @@ export class DirectoryReAnalyzer { for (const filePath of addedFiles) { const alreadyExists = xrFormat - ? hasMatchingXRFile(currentData, filePath) - : hasMatchingLivePanelFile(currentData, filePath); + ? hasMatchingXRFile(currentData as XRAnalysisData, filePath) + : hasMatchingLivePanelFile(currentData as LivePanelAnalysisData, filePath); if (!alreadyExists) { filesToAnalyze.push(filePath); @@ -206,7 +210,7 @@ export class DirectoryReAnalyzer { return false; } - let reanalysisResults: any[] = []; + let reanalysisResults: AnalysisFileEntry[] = []; try { const results = await this.executePython.executeFileReanalysis(filesToAnalyze); reanalysisResults = Array.isArray(results) ? results : [results]; @@ -214,7 +218,7 @@ export class DirectoryReAnalyzer { logger.error('Error analyzing new files:', error); } - const resultsToUpsert: any[] = []; + const resultsToUpsert: AnalysisFileEntry[] = []; for (const [index, filePath] of filesToAnalyze.entries()) { const result = reanalysisResults[index] && reanalysisResults[index].success !== false ? reanalysisResults[index] @@ -231,9 +235,9 @@ export class DirectoryReAnalyzer { } if (xrFormat) { - upsertXRFiles(currentData, resultsToUpsert); + upsertXRFiles(currentData as XRAnalysisData, resultsToUpsert); } else { - upsertLivePanelFiles(currentData, resultsToUpsert); + upsertLivePanelFiles(currentData as LivePanelAnalysisData, resultsToUpsert); } return true; @@ -248,7 +252,7 @@ export class DirectoryReAnalyzer { } } - private async writeJsonAtomically(filePath: string, data: any): Promise { + private async writeJsonAtomically(filePath: string, data: unknown): Promise { const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`; await fs.promises.writeFile(tempPath, JSON.stringify(data, null, 2), 'utf8'); await fs.promises.rename(tempPath, filePath); diff --git a/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts b/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts index b83575e1..6095373d 100644 --- a/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts +++ b/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts @@ -238,7 +238,7 @@ export class FileWatcherOrchestrator { watcherId: this.watcherId, targetPath: this.session.targetPath, sessionId: this.session.id, - debounceStatus: this.debounceManager?.getStatus() || null, + debounceStatus: this.debounceManager?.getStatus() ?? null, }; } diff --git a/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts b/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts index 9725b657..02e5fa13 100644 --- a/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts +++ b/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts @@ -132,7 +132,7 @@ function collectManifestPayloadUrls(manifest: ExportManifest): Set { } } } - for (const source of manifest.gitData?.references.sources || []) { + for (const source of manifest.gitData?.references.sources ?? []) { urls.add(source.payloadUrl); } if ( diff --git a/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts b/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts index d4258d46..730b7b3a 100644 --- a/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts +++ b/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts @@ -186,7 +186,7 @@ export async function runGitRevisionExport( options: GitRevisionExportOptions, ): Promise { const { gitService } = deps; - const request: GitRevisionExportRequest = options.request || { + const request: GitRevisionExportRequest = options.request ?? { scope: { kind: 'all' }, performanceProfile: 'balanced', }; @@ -279,7 +279,7 @@ function groupSourcesByCommit( if (source.kind !== 'gitRef' || !source.commitSha) { return; } - const group = bySha.get(source.commitSha) || []; + const group = bySha.get(source.commitSha) ?? []; if (!group.some((existing) => existing.id === source.id)) { group.push(source); } @@ -327,7 +327,7 @@ async function prepareStoreOrCancel( bySha: Map, ): Promise<{ store: PreparedGitRevisionStore } | { outcome: GitExportOutcome }> { try { - const primarySources = Array.from(bySha.keys()).map((sha) => (bySha.get(sha) || [])[0]); + const primarySources = Array.from(bySha.keys()).map((sha) => (bySha.get(sha) ?? [])[0]); return { store: await deps.prepareRevisionStore(primarySources) }; } catch (error) { if (run.options.token?.isCancellationRequested || String(error).includes('git-export-cancelled')) { diff --git a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts index 0a66f88e..da18653b 100644 --- a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts +++ b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts @@ -153,7 +153,7 @@ export class GitAnalysisSourceCatalog { if (source.kind !== 'gitRef') { continue; } - const group = gitSourcesBySha.get(source.commitSha) || []; + const group = gitSourcesBySha.get(source.commitSha) ?? []; group.push(source); gitSourcesBySha.set(source.commitSha, group); } @@ -178,7 +178,7 @@ export class GitAnalysisSourceCatalog { const cached = source.kind === 'workingCopy' ? workingCopyEligibility : this.deterministicExclusions.get(source.commitSha) - || this.commitEligibility.get(source.commitSha); + ?? this.commitEligibility.get(source.commitSha); if (!cached || cached.usable) { usable.push(source); continue; diff --git a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts index f73596b8..9c14e32f 100644 --- a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts +++ b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts @@ -72,7 +72,7 @@ export class GitAnalysisSessionContext { private readonly policy: GitRevisionAnalysisPolicy, ) { this.ownsSourceCatalog = !sourceCatalog; - this.sourceCatalog = sourceCatalog || new GitAnalysisSourceCatalog( + this.sourceCatalog = sourceCatalog ?? new GitAnalysisSourceCatalog( session.targetType, session.isDeep === true, path.join(session.savedFilesPath || staticRoot, 'data.json'), diff --git a/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts b/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts index 57a0d7ff..e9bf2943 100644 --- a/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts +++ b/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts @@ -395,7 +395,7 @@ export class ProjectEvolutionService { } private async buildAutomaticTimeline(existingReferences?: { sources: ComparisonSource[]; workingTreeDirty: boolean }): Promise { - const references = existingReferences || await this.gitService.listReferences(); + const references = existingReferences ?? await this.gitService.listReferences(); const timeline = await this.gitService.listTimelineSources(TIMELINE_SCAN_LIMIT); const gitTimeline = timeline.length ? timeline diff --git a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts index 34786872..24ea4d30 100644 --- a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts +++ b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts @@ -10,6 +10,8 @@ import { getActiveServerRegistry } from '../../active_servers/registry/activeSer import { ServerControl } from '../../active_servers/runtime/serverControl'; import * as fs from 'fs'; import { getLogger } from '../../core/logging/sink'; +import type { ActiveServer, RegistryEvent } from '../../active_servers/model/activeServerModel'; +import type { UnifiedAnalysisSession } from '../engine/core/analysisSession'; const logger = getLogger('SERVER_WATCHER_INTEGRATION'); @@ -38,7 +40,7 @@ export class ServerWatcherIntegration { private setupServerEventListeners(): void { try { const serverRegistry = getActiveServerRegistry(); - serverRegistry.onRegistryChange((event: any) => { + serverRegistry.onRegistryChange((event: RegistryEvent) => { if (event.type === 'serverRemoved') { void this.handleServerRemoved(event.serverId!, event.server!); } @@ -48,10 +50,10 @@ export class ServerWatcherIntegration { } } - private async handleServerRemoved(serverId: string, server: any): Promise { + private async handleServerRemoved(serverId: string, server: ActiveServer): Promise { try { const sessionRegistry = UnifiedSessionRegistry.getInstance(this.context); - const affectedSessions = sessionRegistry.getAllSessions().filter((session: any) => session.port === server.port); + const affectedSessions = sessionRegistry.getAllSessions().filter((session: UnifiedAnalysisSession) => session.port === server.port); logger.debug(() => `Found ${affectedSessions.length} affected sessions for server ${serverId}`); for (const session of affectedSessions) { @@ -134,7 +136,7 @@ export class ServerWatcherIntegration { private async stopServerByPort(port: number): Promise { try { const serverRegistry = getActiveServerRegistry(); - const serverToStop = serverRegistry.getAllServers().find((server: any) => server.port === port); + const serverToStop = serverRegistry.getAllServers().find((server: ActiveServer) => server.port === port); if (serverToStop) { await ServerControl.stopServer(serverToStop.id); } @@ -143,19 +145,19 @@ export class ServerWatcherIntegration { } } - private async findAndStopServerForSession(sessionId: string, session: any): Promise { + private async findAndStopServerForSession(sessionId: string, session: UnifiedAnalysisSession): Promise { try { const serverRegistry = getActiveServerRegistry(); const servers = serverRegistry.getAllServers(); - let matchingServer = servers.find((server: any) => server.metadata && server.metadata.sessionId === sessionId); + let matchingServer = servers.find((server: ActiveServer) => server.metadata && server.metadata.sessionId === sessionId); if (!matchingServer && session.outputPath) { - matchingServer = servers.find((server: any) => server.htmlFile && server.htmlFile.includes(session.outputPath)); + matchingServer = servers.find((server: ActiveServer) => server.htmlFile?.includes(session.outputPath)); } if (!matchingServer) { - matchingServer = servers.find((server: any) => server.customName && server.customName.includes('Analysis')); + matchingServer = servers.find((server: ActiveServer) => server.customName?.includes('Analysis')); } if (matchingServer) { diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts index f5bc8c48..42e3e11a 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts @@ -9,7 +9,7 @@ import * as path from 'path'; import { UnifiedAnalysisSession } from '../../../../engine/core/analysisSession'; import { UnifiedSessionRegistry } from '../../../../engine/core/sessionRegistry'; import { ServerWatcherIntegration } from '../../../../services/serverWatcherIntegration'; -import { ActiveAnalysisItem, ActiveAnalysesDataService } from '../services/activeAnalysesDataService'; +import { ActiveAnalysesDataService } from '../services/activeAnalysesDataService'; import { CommandRegistration } from '../../../../commands/subsections/analysis_settings/analysis_file_mode'; import { analysisRefreshCoordinator } from '../../../../refresh/analysisRefreshCoordinator'; import { @@ -49,6 +49,22 @@ import { getLogger } from '../../../../../core/logging/sink'; const logger = getLogger('ACTIVE_ANALYSES_COMMANDS'); +/** The id-bearing fields extractSessionId looks for on a command argument. */ +interface SessionIdCarrier { + session?: { id?: string }; + sessionId?: string; + id?: string; +} + +/** + * What an Active Analyses command receives: a session id, the data item + * (an ActiveAnalysisItem fits SessionIdCarrier), the TreeItem tagged with the + * session fields, or a wrapper holding the data item as originalAnalysisItem. + */ +type ActiveAnalysisCommandArg = + | string + | (SessionIdCarrier & { originalAnalysisItem?: SessionIdCarrier }); + /** The Git steps of the export wizard: a request to run, or the wizard stops. */ type GitExportPrompt = | { kind: 'cancelled' } @@ -146,7 +162,7 @@ export class ActiveAnalysesCommands { return [...this.commands]; } - private async showActions(arg?: ActiveAnalysisItem | string | any): Promise { + private async showActions(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -214,7 +230,7 @@ export class ActiveAnalysesCommands { } } - private async showDetails(arg?: ActiveAnalysisItem | string | any): Promise { + private async showDetails(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -229,7 +245,7 @@ export class ActiveAnalysesCommands { await vscode.window.showTextDocument(doc); } - private async closeAnalysis(arg?: ActiveAnalysisItem | string | any): Promise { + private async closeAnalysis(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -277,7 +293,7 @@ export class ActiveAnalysesCommands { void vscode.window.showErrorMessage('Failed to close the analysis session cleanly'); } - private async viewInBrowser(arg?: ActiveAnalysisItem | string | any): Promise { + private async viewInBrowser(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -298,7 +314,7 @@ export class ActiveAnalysesCommands { await vscode.env.openExternal(vscode.Uri.parse(url)); } - private async exportFolder(arg?: ActiveAnalysisItem | string | any): Promise { + private async exportFolder(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -701,7 +717,7 @@ export class ActiveAnalysesCommands { * id, then to a live session, reporting the first step that fails. */ private resolveSelectedSession( - arg: unknown, + arg: ActiveAnalysisCommandArg | undefined, ): { sessionId: string; session: UnifiedAnalysisSession } | undefined { const sessionId = this.extractSessionId(arg); if (!sessionId) { @@ -717,7 +733,7 @@ export class ActiveAnalysesCommands { return { sessionId, session }; } - private extractSessionId(arg?: ActiveAnalysisItem | string | any): string | undefined { + private extractSessionId(arg?: ActiveAnalysisCommandArg): string | undefined { if (typeof arg === 'string') { return arg; } @@ -757,7 +773,7 @@ export class ActiveAnalysesCommands { return undefined; } - private generateDetailsContent(session: any): string { + private generateDetailsContent(session: UnifiedAnalysisSession): string { return `# Analysis Details ## Session Information diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts index df4852ff..f958340a 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts @@ -5,7 +5,9 @@ import * as vscode from 'vscode'; import * as path from 'path'; +import { UnifiedAnalysisSession } from '../../../../engine/core/analysisSession'; import { UnifiedSessionRegistry } from '../../../../engine/core/sessionRegistry'; +import type { CodeAnalysisTreeItem } from '../../../../views/items/analysisItems'; import { getLogger } from '../../../../../core/logging/sink'; const logger = getLogger('ACTIVE_ANALYSES_DATA_SERVICE'); @@ -26,9 +28,19 @@ export interface ActiveAnalysisItem { serverUrl?: string; assignedPort?: number; // Direct session reference for commands - NO MORE COMPLEX TRANSFORMATIONS - session: any; + session: UnifiedAnalysisSession; } +/** + * The session fields copied onto the TreeItem: VS Code passes the TreeItem, + * not the element, to context-menu commands, and they locate the session + * through these. + */ +type ActiveAnalysisTreeItem = vscode.TreeItem & Pick< + ActiveAnalysisItem, + 'sessionId' | 'analysisType' | 'status' | 'targetPath' | 'serverUrl' | 'assignedPort' +>; + /** Icon colour per analysis mode for file targets; legacy mode names included. */ const FILE_ICON_COLORS: Readonly> = { LivePanel: 'charts.green', @@ -144,13 +156,13 @@ export class ActiveAnalysesDataService { // CRITICAL: Add sessionId to the TreeItem so commands can locate the session // VS Code passes the TreeItem object to context menu commands, not the original element - (item as any).sessionId = element.sessionId; - (item as any).id = element.id; - (item as any).analysisType = element.analysisType; - (item as any).status = element.status; - (item as any).targetPath = element.targetPath; - (item as any).serverUrl = element.serverUrl; - (item as any).assignedPort = element.assignedPort; + (item as ActiveAnalysisTreeItem).sessionId = element.sessionId; + (item as ActiveAnalysisTreeItem).id = element.id; + (item as ActiveAnalysisTreeItem).analysisType = element.analysisType; + (item as ActiveAnalysisTreeItem).status = element.status; + (item as ActiveAnalysisTreeItem).targetPath = element.targetPath; + (item as ActiveAnalysisTreeItem).serverUrl = element.serverUrl; + (item as ActiveAnalysisTreeItem).assignedPort = element.assignedPort; logger.debug('Created TreeItem with session info:', { sessionId: element.sessionId, @@ -239,7 +251,7 @@ export class ActiveAnalysesDataService { /** * Create analysis item for tree view */ - private createAnalysisItem(session: any, type: 'file' | 'directory'): ActiveAnalysisItem | null { + private createAnalysisItem(session: UnifiedAnalysisSession, type: 'file' | 'directory'): ActiveAnalysisItem | null { try { if (!session) { logger.warn('Cannot create analysis item - session is null/undefined'); @@ -365,7 +377,7 @@ export class ActiveAnalysesDataService { /** * Get analysis by ID */ - public getAnalysisById(id: string): any | null { + public getAnalysisById(id: string): UnifiedAnalysisSession | undefined | null { try { if (!this.sessionRegistry) { logger.warn('Session registry not initialized'); @@ -439,7 +451,7 @@ export class ActiveAnalysesDataService { /** * Get subsection item for the tree (SIMPLIFIED integration) */ - public getSubsectionItem(): any { + public getSubsectionItem(): CodeAnalysisTreeItem { try { const activeCount = this.getAllActiveAnalyses().length; return { diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts index 5067556d..d6720bf0 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts @@ -61,7 +61,7 @@ export class AutoAnalysisDelaySetting { * Get display text for current delay */ private getDelayDisplayText(delayConfig?: AutoAnalysisDelayConfig): string { - const configToUse = delayConfig || this.currentDelayConfig; + const configToUse = delayConfig ?? this.currentDelayConfig; if (configToUse.type === 'Custom') { const ms = configToUse.customMs || 0; return `Custom: ${ms}ms`; @@ -73,7 +73,7 @@ export class AutoAnalysisDelaySetting { * Get appropriate icon for current delay */ private getDelayIcon(delayConfig?: AutoAnalysisDelayConfig): vscode.ThemeIcon { - const configToUse = delayConfig || this.currentDelayConfig; + const configToUse = delayConfig ?? this.currentDelayConfig; if (configToUse.type === 'RealTime') { return new vscode.ThemeIcon('zap', new vscode.ThemeColor('charts.green')); } else if (configToUse.type === 'Custom') { diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts index 9dbf6b83..e9c9a477 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts @@ -73,7 +73,7 @@ export class SharedDimensionMappingSettingCore { } const chart = this.getChartMetadata(chartType); - if (!chart || !chart.dimensions) { + if (!chart?.dimensions) { return [new CodeAnalysisTreeItem( 'No dimensions available', vscode.TreeItemCollapsibleState.None, diff --git a/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts b/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts index ca289cd3..0d37a2d0 100644 --- a/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts +++ b/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts @@ -29,7 +29,7 @@ export function getCollaborationCommandRegistrations( description: 'Join a remote CodeXR session', handler: async () => { const remoteAccess = RemoteAccessManager.getInstance() - || RemoteAccessManager.initialize(context); + ?? RemoteAccessManager.initialize(context); await remoteAccess.joinInvitation(); }, }, diff --git a/apps/vscode-extension/src/python_env/runtime/venvManager.ts b/apps/vscode-extension/src/python_env/runtime/venvManager.ts index 1a3c83d3..ef79bb98 100644 --- a/apps/vscode-extension/src/python_env/runtime/venvManager.ts +++ b/apps/vscode-extension/src/python_env/runtime/venvManager.ts @@ -648,8 +648,7 @@ export class VenvManager { if (!pipStillAvailable) { throw new Error( 'CodeXR could not upgrade pip and the virtual environment pip is no longer usable. ' + - 'The global Python installation was not modified.\n\n' + - this.getErrorDetails(error), + `The global Python installation was not modified.\n\n${this.getErrorDetails(error)}`, ); } diff --git a/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts b/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts index 1ec2a650..160c894c 100644 --- a/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts +++ b/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts @@ -359,19 +359,19 @@ export class RemoteSessionAuthority { return null; } this.browserTokens.delete(tokenHash); - return this.sessions.get(record.sessionId) || null; + return this.sessions.get(record.sessionId) ?? null; } public resolveCookie(cookieHeader: string | undefined): AuthenticatedCollaborationSession | null { this.cleanup(); const sessionId = this.readCookie(cookieHeader, 'codexr_session'); - return sessionId ? this.sessions.get(sessionId) || null : null; + return sessionId ? this.sessions.get(sessionId) ?? null : null; } public resolveExtensionToken(token: string): AuthenticatedCollaborationSession | null { this.cleanup(); const sessionId = this.extensionTokens.get(this.hash(token)); - return sessionId ? this.sessions.get(sessionId) || null : null; + return sessionId ? this.sessions.get(sessionId) ?? null : null; } public updateExtensionProfile( diff --git a/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts b/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts index b552cf60..ce3041fd 100644 --- a/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts +++ b/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts @@ -88,7 +88,7 @@ export class RemoteAccessManager implements vscode.Disposable { throw new Error('The active server no longer exists.'); } if (this.shares.has(serverId)) { - return server.remoteAccess || { ...DEFAULT_REMOTE_ACCESS_STATE }; + return server.remoteAccess ?? { ...DEFAULT_REMOTE_ACCESS_STATE }; } const remoteServer = this.asRemoteCapableServer(server); const binaryPath = await this.binaryManager.resolveBinary(true); diff --git a/apps/vscode-extension/src/servers/commands/serverCommands.ts b/apps/vscode-extension/src/servers/commands/serverCommands.ts index 3fe606cc..6e7ad20d 100644 --- a/apps/vscode-extension/src/servers/commands/serverCommands.ts +++ b/apps/vscode-extension/src/servers/commands/serverCommands.ts @@ -307,7 +307,7 @@ async function promptForHtmlFile(): Promise { const fileUri = await vscode.window.showOpenDialog(options); - if (fileUri && fileUri[0]) { + if (fileUri?.[0]) { const filePath = fileUri[0].fsPath; logger.debug(() => `User selected file: ${filePath}`); diff --git a/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts b/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts index ba2e5e31..455c9e4c 100644 --- a/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts +++ b/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts @@ -122,7 +122,7 @@ export class AnalysisFeatureHost { this.config.extensionContext, this.config.analysisSessionId, this.config.staticRoot, - this.gitAnalysisSourceCatalog || undefined, + this.gitAnalysisSourceCatalog ?? undefined, ); this.analysisUpdateSubscription = analysisUpdateEvents.on((event) => { if (event.sessionId !== this.config.analysisSessionId) { @@ -147,7 +147,7 @@ export class AnalysisFeatureHost { this.config.extensionContext, this.config.analysisSessionId, this.config.staticRoot, - this.gitAnalysisSourceCatalog || undefined, + this.gitAnalysisSourceCatalog ?? undefined, ); } @@ -197,7 +197,7 @@ export class AnalysisFeatureHost { enabled: false, reason: 'Project evolution is not available for this server.', }, - dependencyGraph: this.dependencyGraphService?.getAvailability() || { + dependencyGraph: this.dependencyGraphService?.getAvailability() ?? { enabled: false, reason: 'Dependency analysis is not available for this server.', }, diff --git a/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts b/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts index c366f80c..fad13a37 100644 --- a/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts +++ b/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts @@ -563,7 +563,7 @@ export class ScreenBroadcastSignalingServer { if (!roomId || !screenId) { return null; } - return this.screens.get(this.getScreenKey(roomId, screenId)) || null; + return this.screens.get(this.getScreenKey(roomId, screenId)) ?? null; } private pruneScreen(roomId: string, screenId: string): void { diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts index 2cd06b78..5a9e1303 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts @@ -192,7 +192,7 @@ export class CollaborationRoomServer { const peer: CollaborationPeer = { id: peerId, socket, - session: this.options.resolveSession?.(request) || null, + session: this.options.resolveSession?.(request) ?? null, joinedRoom: false, roomId: null, anonymousDisplayName: '', @@ -329,7 +329,7 @@ export class CollaborationRoomServer { } const role: CollaborationRole = room.participants.size === 0 ? 'host' : 'guest'; - const participant = existingParticipant || { + const participant = existingParticipant ?? { peerId: peer.id, displayName: peer.anonymousDisplayName, identityMode: 'anonymous' as IdentityMode, @@ -344,7 +344,7 @@ export class CollaborationRoomServer { room, peer, participant, - peer.session?.profile || { + peer.session?.profile ?? { identityMode: 'anonymous', customName: '', // A peer with no session (local browser) never chose a colour. diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts index b483f88d..e5f25c0b 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts @@ -85,9 +85,9 @@ export class CollaborationSessionApi { const mapping = fileUri ? fileToServerMap.getServerInfo(fileUri) : null; const activeServerId = mapping?.activeServerId || `port-${this.deps.port}`; const collaborationConfiguration = CollaborationProfileManager.getInstance()?.getConfiguration() - || this.getDefaultCollaborationConfiguration(); + ?? this.getDefaultCollaborationConfiguration(); const session = this.deps.authority.resolveCookie(req.headers.cookie); - const profile = session?.profile || DEFAULT_COLLABORATION_PROFILE; + const profile = session?.profile ?? DEFAULT_COLLABORATION_PROFILE; const { historicalComparison, projectEvolution, dependencyGraph } = await this.deps.getAnalysisAvailability(); diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts b/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts index 4d903d18..b54f5a5f 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts @@ -43,7 +43,7 @@ export class CollaborationRoomRegistry { if (!peer.joinedRoom || !peer.roomId) { return null; } - return this.rooms.get(peer.roomId) || null; + return this.rooms.get(peer.roomId) ?? null; } public broadcast(room: CollaborationRoomState, payload: Record, excludedPeerId?: string): void { diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts b/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts index 9163bbd5..dcaccea5 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts @@ -32,7 +32,7 @@ export function upsertAuthoritativeEntity( } const key = getEntityKey(normalized.entityKind, normalized.entityId); const nextEntity = { - ...(room.entities.get(key) || {}), + ...(room.entities.get(key) ?? {}), ...normalized, updatedAt: new Date().toISOString(), }; @@ -88,9 +88,9 @@ export function upsertEntity( } const key = getEntityKey(entity.entityKind, entity.entityId); - const previous = room.entities.get(key) || null; + const previous = room.entities.get(key) ?? null; const nextEntity: SharedEntityState = { - ...(previous || {}), + ...(previous ?? {}), ...entity, entityKind: entity.entityKind, entityId: entity.entityId, @@ -214,9 +214,9 @@ export function updatePresence(context: RoomContext, peer: CollaborationPeer, pa return; } - const previous = room.presence.get(peer.id) || null; + const previous = room.presence.get(peer.id) ?? null; const nextPresence: SharedPresenceState = { - ...(previous || {}), + ...(previous ?? {}), ...payload, ...getParticipantPresence(participant), peerId: peer.id, diff --git a/apps/vscode-extension/src/servers/runtime/httpServer.ts b/apps/vscode-extension/src/servers/runtime/httpServer.ts index f24c28ba..8d4cab99 100644 --- a/apps/vscode-extension/src/servers/runtime/httpServer.ts +++ b/apps/vscode-extension/src/servers/runtime/httpServer.ts @@ -265,7 +265,7 @@ export class HttpServer { } public getConnectedParticipants(): ConnectedParticipantSummary[] { - return this.collaborationRoomServer?.getConnectedParticipants(this.sessionApi.getCollaborationRoomId()) || []; + return this.collaborationRoomServer?.getConnectedParticipants(this.sessionApi.getCollaborationRoomId()) ?? []; } /** @@ -567,7 +567,7 @@ export class HttpServer { for (const session of sessions) { this.collaborationRoomServer?.updateSessionProfile(session.sessionId, session.profile); } - }) || null; + }) ?? null; this.broadcastSignalingServer = new ScreenBroadcastSignalingServer( server, '/codexr-broadcast', diff --git a/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts b/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts index e5cb98f6..829ddec3 100644 --- a/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts +++ b/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts @@ -214,7 +214,7 @@ export abstract class HttpsServerBase { } else if (error.code === 'EACCES') { reject(new Error(`SERVER: Permission denied. May need to run as administrator for port ${this.config.port}`)); } else { - reject(this.describeStartError(error) || new Error(`SERVER: Failed to start HTTPS server: ${error.message}`)); + reject(this.describeStartError(error) ?? new Error(`SERVER: Failed to start HTTPS server: ${error.message}`)); } } diff --git a/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts b/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts index 5a670c92..3f971785 100644 --- a/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts +++ b/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts @@ -268,7 +268,7 @@ export class MultiServerLauncher { */ private generateServerId(): string { const timestamp = Date.now(); - const random = Math.random().toString(36).substr(2, 5); + const random = Math.random().toString(36).slice(2, 7); return `server_${timestamp}_${random}`; } } diff --git a/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts b/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts index 4003f20f..d3ba36b8 100644 --- a/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts +++ b/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts @@ -1,3 +1,5 @@ +import * as fs from 'fs'; +import * as path from 'path'; import * as http from 'http'; import { SSEClientRegistry } from './sseClientRegistry'; import { fileToServerMap } from '../../../utils/fileToServerMap'; @@ -89,8 +91,7 @@ export class SSEManager { logger.debug(() => `REQUEST_UPDATE: Found mapping - Port: ${mapping.port}, TempDir: ${mapping.tempDir}`); // Verify data.json exists in the temp directory - const dataJsonPath = require('path').join(mapping.tempDir, 'data.json'); - const fs = require('fs'); + const dataJsonPath = path.join(mapping.tempDir, 'data.json'); try { const exists = fs.existsSync(dataJsonPath); logger.debug(() => `REQUEST_UPDATE: data.json exists at ${dataJsonPath}: ${exists}`); diff --git a/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts b/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts index ea4fd1e0..a150da56 100644 --- a/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts +++ b/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts @@ -85,7 +85,7 @@ export class SSEClientRegistry { * @returns Array of response objects */ getClients(fileUri: string): http.ServerResponse[] { - return this.clients.get(fileUri) || []; + return this.clients.get(fileUri) ?? []; } /** diff --git a/apps/vscode-extension/src/servers/utils/networkUtils.ts b/apps/vscode-extension/src/servers/utils/networkUtils.ts index b2a53bbd..18f9ebaa 100644 --- a/apps/vscode-extension/src/servers/utils/networkUtils.ts +++ b/apps/vscode-extension/src/servers/utils/networkUtils.ts @@ -91,8 +91,8 @@ export class NetworkUtils { logger.debug('===================================='); logger.debug(() => `Primary External URL: ${urls.localIP}`); logger.debug(() => `Localhost URL: ${urls.localhost}`); - logger.debug(() => 'For VR/Mobile devices use: ' + urls.localIP); - logger.debug(() => 'For local testing use: ' + urls.localhost); + logger.debug(() => `For VR/Mobile devices use: ${urls.localIP}`); + logger.debug(() => `For local testing use: ${urls.localhost}`); logger.debug('Network Diagnostics:'); logger.debug(() => ` - Server listening on: 0.0.0.0:${port}`); logger.debug(() => ` - Local IP detected: ${this.getLocalIPAddress()}`); diff --git a/apps/vscode-extension/src/utils/fileToServerMap.ts b/apps/vscode-extension/src/utils/fileToServerMap.ts index bb3da1d7..c0b225b2 100644 --- a/apps/vscode-extension/src/utils/fileToServerMap.ts +++ b/apps/vscode-extension/src/utils/fileToServerMap.ts @@ -66,7 +66,7 @@ class FileToServerMapping { * @returns ServerInfo or null if not found */ getServerInfo(fileUri: string): ServerInfo | null { - return this.fileToServer.get(fileUri) || null; + return this.fileToServer.get(fileUri) ?? null; } /** diff --git a/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts b/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts index 10334b1d..ed689bc7 100644 --- a/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts +++ b/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts @@ -221,7 +221,7 @@ export class JsonFieldAnalyzer { return { label: field.name, description: typeInfo, - detail: `${field.valueCount} values${sampleText ? ' • ' + sampleText : ''}` + detail: `${field.valueCount} values${sampleText ? ` • ${sampleText}` : ''}` }; } } diff --git a/apps/vscode-extension/src/utils/languageMetadata.ts b/apps/vscode-extension/src/utils/languageMetadata.ts index cd477fff..9b002e8e 100644 --- a/apps/vscode-extension/src/utils/languageMetadata.ts +++ b/apps/vscode-extension/src/utils/languageMetadata.ts @@ -59,7 +59,7 @@ SupportedLanguages.forEach(lang => { */ export function getLanguageForFile(filePath: string): LanguageInfo | null { const extension = getFileExtension(filePath); - return ExtensionToLanguageMap.get(extension) || null; + return ExtensionToLanguageMap.get(extension) ?? null; } /** diff --git a/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts b/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts index 97bb7efd..7f94985b 100644 --- a/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts +++ b/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts @@ -173,7 +173,7 @@ export class ActiveServersSectionProvider implements SectionProvider(LEGACY_STORAGE_KEY); - if (legacySettings && legacySettings[field]) { + if (legacySettings?.[field]) { return legacySettings[field]; } } diff --git a/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts b/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts index 2743766c..80dced89 100644 --- a/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts +++ b/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts @@ -93,7 +93,7 @@ export class VisualizationLauncher { const fileUri = await vscode.window.showOpenDialog(options); - if (fileUri && fileUri[0]) { + if (fileUri?.[0]) { const filePath = fileUri[0].fsPath; const fileName = path.basename(filePath); diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 24a1299c..7afa2421 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -24,11 +24,10 @@ }, "catch.consoleOnly": 0, "catch.emptyNoComment": 0, - "any.total": 130, + "any.total": 84, "any.byModule": { - "active_servers": 11, "babia_templates": 2, - "code_analysis": 53, + "code_analysis": 18, "commands": 6, "platform": 7, "python_env": 5, @@ -55,13 +54,13 @@ "src/views/active_servers/items/activeServerItems.ts" ], "functions.over80Lines": 36, - "complexity.over10": 54, - "complexity.over15": 9, + "complexity.over10": 53, + "complexity.over15": 8, "complexity.over20": 0, "complexity.over30": 0, "reachability.unreachable": [], "templates.consoleLog": 31, - "eslint.maxWarnings": 204, + "eslint.maxWarnings": 158, "commands.internalByKind": { "legacy-alias": 2, "programmatic": 2, @@ -70,7 +69,7 @@ }, "informational": { "src.files": 337, - "src.lines": 49505, + "src.lines": 49563, "src.functions": 3338, "src.unreachableLines": 0, "console.topFiles": [ @@ -80,22 +79,6 @@ } ], "any.topFiles": [ - { - "file": "src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts", - "count": 11 - }, - { - "file": "src/code_analysis/engine/watchers/directoryReAnalyzer.ts", - "count": 9 - }, - { - "file": "src/code_analysis/services/serverWatcherIntegration.ts", - "count": 8 - }, - { - "file": "src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts", - "count": 7 - }, { "file": "src/commands/analysis/AnalysisCommands.ts", "count": 5 @@ -120,14 +103,6 @@ "file": "src/views/ModularTreeDataProvider.ts", "count": 5 }, - { - "file": "src/active_servers/registry/activeServerRegistry.ts", - "count": 4 - }, - { - "file": "src/active_servers/runtime/serverControl.ts", - "count": 4 - }, { "file": "src/servers/storage/serverSettingsManager.ts", "count": 4 @@ -139,6 +114,30 @@ { "file": "src/views/babia_examples/interactions/handleBabiaExampleClicks.ts", "count": 3 + }, + { + "file": "src/visualization_settings/storage/settingsStorage.ts", + "count": 3 + }, + { + "file": "src/babia_templates/processing/templateProcessor.ts", + "count": 2 + }, + { + "file": "src/code_analysis/engine/parsers/directoryXRParser.ts", + "count": 2 + }, + { + "file": "src/code_analysis/engine/processors/analysisBootstrap.ts", + "count": 2 + }, + { + "file": "src/code_analysis/engine/servers/serverLaunchOrchestrator.ts", + "count": 2 + }, + { + "file": "src/code_analysis/engine/utils/executePython.ts", + "count": 2 } ], "complexity.worst10": [ @@ -184,18 +183,18 @@ "function": "updateFromLegacyConfig", "file": "src/servers/storage/serverSettingsManager.ts" }, - { - "ccn": 16, - "lines": 81, - "function": "closeAssociatedAnalysisSession", - "file": "src/active_servers/runtime/serverControl.ts" - }, { "ccn": 16, "lines": 31, "function": "validateConfig", "file": "src/active_servers/services/serverRegistrar.ts" }, + { + "ccn": 15, + "lines": 81, + "function": "closeAssociatedAnalysisSession", + "file": "src/active_servers/runtime/serverControl.ts" + }, { "ccn": 15, "lines": 88, @@ -206,11 +205,11 @@ "size.largest10": [ { "file": "src/python_env/runtime/venvManager.ts", - "lines": 852 + "lines": 851 }, { "file": "src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts", - "lines": 787 + "lines": 803 }, { "file": "src/code_analysis/export/exportManifest.ts", diff --git a/apps/vscode-extension/test/tooling/lintContract.test.cjs b/apps/vscode-extension/test/tooling/lintContract.test.cjs index 233442be..5b73802d 100644 --- a/apps/vscode-extension/test/tooling/lintContract.test.cjs +++ b/apps/vscode-extension/test/tooling/lintContract.test.cjs @@ -30,6 +30,10 @@ const WARN_BUDGET_RULES = [ // Budget rules that reached zero and were promoted to errors (ROADMAP T59). const PROMOTED_RULES = ['@typescript-eslint/no-floating-promises']; +// The flat-config block (by its name) where folders free of `any` make +// no-explicit-any an error (story #56). +const ANY_FREE_BLOCK = 'codexr/any-free-folders'; + async function loadEslintConfig() { const configUrl = pathToFileURL(path.join(projectRoot, 'eslint.config.mjs')).href; return (await import(configUrl)).default; @@ -78,9 +82,13 @@ test('the warn-only budget rules are configured as warnings over src', async () // The type-aware ones live in their own block (they need the TypeScript // program); the merge below follows flat-config order, last block wins. // A budget rule set to "off" would let its count drift while the - // --max-warnings ceiling still looks tight. + // --max-warnings ceiling still looks tight. The any-free folders block is + // the one deliberate exception: it makes no-explicit-any stricter (an + // error) for the folders listed there, never looser. const config = await loadEslintConfig(); - const rules = Object.assign({}, ...config.filter((block) => block.rules).map((block) => block.rules)); + const rules = Object.assign({}, ...config + .filter((block) => block.rules && block.name !== ANY_FREE_BLOCK) + .map((block) => block.rules)); for (const rule of WARN_BUDGET_RULES) { const value = rules[rule]; @@ -197,3 +205,70 @@ test('no-console is an error over all of src/, and the log sink is the only exce assert.deepEqual(block.ignores, ['src/core/logging/sink.ts']); assert.ok(fs.existsSync(path.join(projectRoot, 'src', 'core', 'logging', 'sink.ts')), 'the allowlisted sink exists'); }); + +// Idioms story #56 brought to zero in src/ (docs/cleanup/modernization.md §7). +// Each lock-in landed with the commit that reached zero; one switched off or +// downgraded would let the idiom come back unnoticed. +const MODERNIZED_IDIOM_RULES = [ + 'no-var', + 'prefer-rest-params', + '@typescript-eslint/no-namespace', + '@typescript-eslint/no-unsafe-function-type', + '@typescript-eslint/no-require-imports', + '@typescript-eslint/prefer-includes', + '@typescript-eslint/prefer-optional-chain', + 'prefer-template', + '@typescript-eslint/prefer-nullish-coalescing', + 'no-restricted-properties', +]; + +test('the modernized idioms stay locked over src/', async () => { + const config = await loadEslintConfig(); + const block = config.find((candidate) => candidate.rules + && candidate.rules['no-var'] !== undefined + && Array.isArray(candidate.files) && candidate.files.includes('src/**/*.ts')); + + assert.ok(block, 'one block locks the idioms over src/**/*.ts'); + for (const rule of MODERNIZED_IDIOM_RULES) { + const value = block.rules[rule]; + assert.equal(Array.isArray(value) ? value[0] : value, 'error', `${rule} is an error over src/`); + } +}); + +test('only the three files with deliberate lazy require() may use it', async () => { + // modernization.md §4: the tree provider's eight lazy requires are + // load-bearing, the other two break load-time cycles. Any other file + // imports statically. + const config = await loadEslintConfig(); + const exemptions = config.filter((block) => block.rules + && block.rules['@typescript-eslint/no-require-imports'] === 'off'); + + assert.equal(exemptions.length, 1, 'one exemption block'); + assert.deepEqual([...exemptions[0].files].sort(), [ + 'src/code_analysis/engine/watchers/directoryReAnalyzer.ts', + 'src/utils/getVisualizationConfiguration.ts', + 'src/views/ModularTreeDataProvider.ts', + ]); + for (const file of exemptions[0].files) { + assert.ok(fs.existsSync(path.join(projectRoot, file)), `${file} exists`); + } +}); + +test('folders typed free of any keep no-explicit-any as an error', async () => { + // Story #56 types the `any`s folder by folder; a folder at zero is locked + // there. The block may only tighten the rule, and every folder it names + // must exist (a moved folder would otherwise drop out of the lock silently). + const config = await loadEslintConfig(); + const blocks = config.filter((block) => block.name === ANY_FREE_BLOCK); + + assert.equal(blocks.length, 1, 'one any-free folders block'); + const [block] = blocks; + assert.deepEqual(Object.keys(block.rules), ['@typescript-eslint/no-explicit-any']); + assert.equal(block.rules['@typescript-eslint/no-explicit-any'], 'error'); + assert.ok(block.files.length > 0); + for (const pattern of block.files) { + assert.match(pattern, /^src\/.+\/\*\*\/\*\.ts$/, `${pattern} is a src/ folder glob`); + const folder = pattern.replace(/\/\*\*\/\*\.ts$/, ''); + assert.ok(fs.statSync(path.join(projectRoot, folder)).isDirectory(), `${folder} exists`); + } +}); diff --git a/docs/cleanup/modernization.md b/docs/cleanup/modernization.md index 3dfc2bf9..47b44431 100644 --- a/docs/cleanup/modernization.md +++ b/docs/cleanup/modernization.md @@ -156,6 +156,25 @@ Landed on `claude/project-thread-n2s3q6-modernize-py-js` (session log `.claude/d Row 2 leaves exactly three places on `typing` generics: `TargetTuple` (a runtime alias, see §3), `utils/xr_field_schema.py` (contract, 9) and `html/html_dom_parser.py` (2), whose `def emit_json_result(result: Dict[str, Any]) -> None:` line `livePanelDomIntegration.test.cjs` pins verbatim (an S pin: relaxing it needs its own characterization commit first, so the file was left whole rather than half-converted). +## 7. Progress (TypeScript) + +Landed on `claude/project-thread-n2s3q6-modernize-ts` (session log `.claude/docs/v1.2.1/sessions/56b-modernize-ts.md`), after #35 merged, so `executePython.ts` and the export files were in scope (the "left to #35" notes in §1, §4 and §5 no longer apply). Counts are from the A.1 script and the typed ESLint rules, on `src/`. Every lock-in lives in one `src/**/*.ts` block of `apps/vscode-extension/eslint.config.mjs`, asserted by `test/tooling/lintContract.test.cjs`; exceptions are per-file overrides there, never `eslint-disable` (suppressions stay 0). + +| Plan row | Idiom × area | Before | After | Lock-in | +|---|---|---:|---:|---| +| 1 (TS part) | `var`, `arguments`, `namespace`, `Function` type | 0 | 0 | `no-var`, `prefer-rest-params`, `@typescript-eslint/no-namespace`, `@typescript-eslint/no-unsafe-function-type` | +| 4 | inline `require()` of Node built-ins | 7 in 3 files (`executePython.ts` had none left after #35) | 0 | `@typescript-eslint/no-require-imports`; off for `ModularTreeDataProvider.ts` (8 lazy, load-bearing) and the two cycle breakers | +| 5 | `substr()` / `indexOf` presence compares | 1 / 0 (the script's 5 "compares" all use the index: `args[indexOf(x) + 1]`, `newline = buf.indexOf('\n')`) | 0 / 0 | `no-restricted-properties` on `substr`, `@typescript-eslint/prefer-includes` | +| 6 | `a && a.b` (typed `prefer-optional-chain`) | 10 in 7 files | 0 | `@typescript-eslint/prefer-optional-chain` | +| 7 | concatenation `prefer-template` reports | 8 in 6 files (script row: 23) | 0 (script row: 18, all literal + literal line wraps) | `prefer-template`. `createStructure.ts`'s SSE script builder checked byte-identical (sha256 of its output for xr/dom/none) | +| 8 | `any` (guardrail `any.total`) | 130 | 84 | `no-explicit-any: error` for the folders at zero (named block `codexr/any-free-folders`): `active_servers`, `code_analysis/engine/watchers`, `code_analysis/services`, `code_analysis/views/subsections/active_analyses` | +| 9 | `x \|\| d` with an object-typed `x` (`prefer-nullish-coalescing`, `ignorePrimitives` all) | 76 reported: 60 `\|\|`, 15 `if (!x) x = …`, 1 ternary | 12 `\|\|` kept on purpose | the rule with `ignorePrimitives` (all), `ignoreTernaryTests`, `ignoreIfStatements`; off for 8 files: parsed WebSocket/bridge JSON (`dependencyGraphBridge`, `projectEvolutionBridge`, `collaborationRoomServer`, `roomSharedState`), storage and settings (`visualizeDataState`, `sharedDimensionMappingSettingCore`, `serverSettingsManager`) and one S pin (`projectEvolutionService.ts:421`, matched by `historicalComparison.test.cjs:467`) | +| 10 | `.then()` where the promise is already returned or awaited | 0 of 24 | 0 | none (no rule without a new plugin). All 24 are fire-and-forget prompts (`void showXMessage(…).then(choice => …)`), the HTTP request handler's `.then().catch()`, promise caches/queues (`gitTimelineBlobIndex`, `gitTimelineBlobAnalyzer`, `gitAnalysisEligibility`), or a resolver inside `new Promise` | + +ESLint warning budget (`eslint.maxWarnings`): 204 → 158, all from `no-explicit-any` warnings that disappeared. `complexity.over10` 54 → 53, `complexity.over15` 9 → 8. + +Row 8 status, for the next pass (re-measure with `npm run guardrails:measure`): the biggest remaining files are `utils/jsonFieldAnalyzer.ts` and `utils/commandBuilder.ts` (5 each; the latter's `TArgs extends any[]` generics need a variance decision, not a rename), `platform/tree/baseInterfaces.ts` 5, `python_env/runtime/venvManager.ts` 5, `views/ModularTreeDataProvider.ts` 5, `commands/analysis/AnalysisCommands.ts` 5, `servers/storage/serverSettingsManager.ts` 4. `executePython.ts` keeps `type PythonPayload = any` and the `parsePythonOutput(…): any` signature that `livePanelDomIntegration.test.cjs` pins verbatim (S pin). + ## Appendix: how to re-run the numbers From the repository root, after `npm ci` (the scripts resolve `typescript` and `acorn` from the workspace). Copy each script to a scratch folder first: they are kept here, not in `scripts/`, because only #56 needs them.