From 19d4d0c77f385f6aceeca78e05026bfe0263e92f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 13:20:49 +0000 Subject: [PATCH] feat(ide): install VS Code extensions from Open VSX with themes, languages, grammars and snippets (#252, #254, #255, #257, #258) - ADR 0002: own extension host + Open VSX, never the Visual Studio Marketplace - Open VSX client (search, details, platform builds, SHA-256 check) and .vsix install with a hardened unzip - Extension store in the user-data folder: install, update, enable, disable, uninstall, disable all, --disable-extensions - Extensions view (Ctrl/Cmd+Shift+X) with registry search, installed list and a details page with the README - Colour themes of extensions in the theme picker, applied to Monaco and the workbench tokens - Languages, language configuration, TextMate grammars (vscode-textmate + oniguruma WASM) and snippets - CSP gains 'wasm-unsafe-eval' only; Extensions channel in the Output panel --- adr/0002-vscode-extensions-in-the-ide.md | 67 +++ adr/README.md | 1 + apps/ide/README.md | 6 + apps/ide/THIRD_PARTY_NOTICES.md | 71 +++ apps/ide/package.json | 9 +- apps/ide/src/main/extensions/contributions.ts | 276 ++++++++++ .../ide/src/main/extensions/extensionStore.ts | 261 ++++++++++ .../src/main/extensions/extensionsService.ts | 355 +++++++++++++ apps/ide/src/main/extensions/manifest.ts | 204 ++++++++ apps/ide/src/main/extensions/openVsx.ts | 287 +++++++++++ apps/ide/src/main/extensions/plist.ts | 129 +++++ apps/ide/src/main/extensions/vsix.ts | 201 ++++++++ apps/ide/src/main/index.ts | 9 +- apps/ide/src/main/ipc.ts | 5 +- apps/ide/src/main/security.ts | 7 +- apps/ide/src/preload/index.ts | 19 + apps/ide/src/renderer/editor/monaco.ts | 23 +- .../extensions/contributionsController.ts | 96 ++++ .../src/renderer/extensions/extensions.css | 55 ++ .../renderer/extensions/extensionsModel.ts | 68 +++ .../src/renderer/extensions/extensionsView.ts | 480 ++++++++++++++++++ .../renderer/extensions/extensionsWiring.ts | 87 ++++ .../src/renderer/extensions/languageModel.ts | 203 ++++++++ .../extensions/monacoContributions.ts | 100 ++++ apps/ide/src/renderer/extensions/textmate.ts | 156 ++++++ .../ide/src/renderer/extensions/themeModel.ts | 172 +++++++ apps/ide/src/renderer/main.ts | 61 ++- apps/ide/src/renderer/workbench.ts | 12 +- apps/ide/src/shared/api.ts | 5 + apps/ide/src/shared/extensions.ts | 288 +++++++++++ apps/ide/src/shared/output.ts | 2 + apps/ide/src/shared/settings.ts | 4 + apps/ide/test/extensions.test.ts | 338 ++++++++++++ apps/ide/test/extensionsRenderer.test.ts | 152 ++++++ apps/ide/test/helpers/zip.ts | 66 +++ apps/ide/test/output.test.ts | 4 +- apps/ide/test/security.test.ts | 6 +- docs/ide/extensions.md | 63 +++ package-lock.json | 60 ++- 39 files changed, 4379 insertions(+), 29 deletions(-) create mode 100644 adr/0002-vscode-extensions-in-the-ide.md create mode 100644 apps/ide/src/main/extensions/contributions.ts create mode 100644 apps/ide/src/main/extensions/extensionStore.ts create mode 100644 apps/ide/src/main/extensions/extensionsService.ts create mode 100644 apps/ide/src/main/extensions/manifest.ts create mode 100644 apps/ide/src/main/extensions/openVsx.ts create mode 100644 apps/ide/src/main/extensions/plist.ts create mode 100644 apps/ide/src/main/extensions/vsix.ts create mode 100644 apps/ide/src/renderer/extensions/contributionsController.ts create mode 100644 apps/ide/src/renderer/extensions/extensions.css create mode 100644 apps/ide/src/renderer/extensions/extensionsModel.ts create mode 100644 apps/ide/src/renderer/extensions/extensionsView.ts create mode 100644 apps/ide/src/renderer/extensions/extensionsWiring.ts create mode 100644 apps/ide/src/renderer/extensions/languageModel.ts create mode 100644 apps/ide/src/renderer/extensions/monacoContributions.ts create mode 100644 apps/ide/src/renderer/extensions/textmate.ts create mode 100644 apps/ide/src/renderer/extensions/themeModel.ts create mode 100644 apps/ide/src/shared/extensions.ts create mode 100644 apps/ide/test/extensions.test.ts create mode 100644 apps/ide/test/extensionsRenderer.test.ts create mode 100644 apps/ide/test/helpers/zip.ts create mode 100644 docs/ide/extensions.md diff --git a/adr/0002-vscode-extensions-in-the-ide.md b/adr/0002-vscode-extensions-in-the-ide.md new file mode 100644 index 000000000..e3111fa23 --- /dev/null +++ b/adr/0002-vscode-extensions-in-the-ide.md @@ -0,0 +1,67 @@ +# ADR 0002: Run VS Code extensions in the Code-XR IDE with our own extension host and Open VSX + +- **Status:** Accepted +- **Date:** 2026-11-27 +- **Deciders:** Adrián Montes Linares (@aMonteSl) +- **Context:** ADR 0001 (Electron + Monaco), the IDE epics #11 and #163, and the extensions epic (stream `ide-extensions`) +- **Design notes:** [`docs/ide/extensions.md`](../docs/ide/extensions.md) + +## Context + +The Code-XR IDE is a custom Electron + Monaco workbench (ADR 0001): about 30,000 lines of hand-written TypeScript with its own explorer, tabs, Source Control, terminal, Problems, Output, settings, command palette, LSP bridge, debugger and AI agent hub. People coming from VS Code expect their extensions: a colour theme, a language they need highlighted, a linter, a formatter. And Code-XR itself is a VS Code extension: running it unchanged inside the IDE would prove the IDE is a real host and would keep one code base for both. + +Three questions must be answered: + +1. **How do extensions run?** A VS Code extension is a Node.js module that `require('vscode')` and calls an API of about 700 functions and classes, plus a `package.json` whose `contributes` section declares themes, grammars, languages, snippets, commands, menus, views, settings and keybindings without any code. +2. **Where do they come from?** The Visual Studio Marketplace is the default source in VS Code. +3. **What is legal and safe?** + +## Options considered + +### A. Fork Code-OSS, or embed VS Code's workbench with `@codingame/monaco-vscode-api` + +`monaco-vscode-api` (MIT) re-packages VS Code's own services on top of Monaco, including the real extension host (in a worker or a Node process) and the real workbench parts. It is the route with the highest compatibility: the API is VS Code's own code. OpenVSCode Server, code-server, VSCodium and Eclipse Che (Che-Code) reach the same result by forking VS Code outright. + +Rejected for now. Its services take over exactly what the IDE has built by hand and is still building in parallel (layout, theming, keybindings, views, the editor model and its tabs); adopting it means replacing the workbench, not adding a feature. It pins the IDE to Monaco builds that follow VS Code's monthly releases, and ADR 0001 already rejected a fork for its maintenance cost. It stays the fallback if the coverage gaps of option C turn out to dominate (see "Revisit when"). + +### B. Eclipse Theia's plugin system + +Theia (EPL-2.0) implements the VS Code API in its own plugin host. Its implementation cannot be lifted out without Theia's dependency-injection framework, which ADR 0001 rejected, and its coverage is still partial in the areas that matter to Code-XR (webviews, tree views). + +### C. Our own extension host, Theia-style, scoped to what people use (chosen) + +Follow VS Code's process model with our own code: + +- **Declarative contributions are handled by the workbench itself**, with no extension code running: colour themes (VS Code theme JSON turned into a Monaco theme and the workbench's colour tokens), TextMate grammars (`vscode-textmate` + `vscode-oniguruma`, both MIT, the libraries VS Code uses), languages and their language configuration, snippets, and the settings schema. This is most of what people install by count: themes and language support. +- **Extension code runs in a separate Node process per window**, the *extension host*, started with Electron's own Node (`ELECTRON_RUN_AS_NODE`), like the language servers (#21). It intercepts `require('vscode')` and hands each extension an API object of its own. Extensions never run in the renderer and never get the renderer's privileges; a crash or a hung extension never takes the window down. +- **The API is implemented incrementally**, by what popular extensions and `vscode-languageclient` call: commands, messages and quick picks, output channels, status bar, configuration, text documents and their events, diagnostics, language features bridged to Monaco providers, workspace file system and file watchers, tree views and webviews. **Anything not implemented degrades instead of throwing**: unknown `register*` functions return a no-op `Disposable`, and every such call is logged once per extension in an *Extensions* channel of the Output panel. That log is the coverage measurement that decides what to implement next. + +Trade-offs accepted: compatibility is partial and has to be measured per extension; proposed APIs, notebooks, the debug API, authentication providers, custom editors and remote development are out of scope at first; a language pack only translates VS Code's own UI strings, which the IDE does not use, so it installs but changes nothing visible. + +## Marketplace: Open VSX, never the Visual Studio Marketplace + +The [Visual Studio Marketplace Terms of Use](https://cdn.vsassets.io/v/M190_20210811.1/_content/Microsoft-Visual-Studio-Marketplace-Terms-of-Use.pdf) allow installing Marketplace offerings only in Visual Studio products and services. The IDE therefore uses **[Open VSX](https://open-vsx.org)**, the vendor-neutral registry run by the Eclipse Foundation, which VSCodium, Theia, Gitpod, Eclipse Che, code-server and Cursor use. Its REST API is public and needs no key (`/api/-/search`, `/api/{namespace}/{name}`, the `.vsix` and its `sha256`). The registry URL is a setting, so a company can point the IDE at its own Open VSX instance. A `.vsix` file can also be installed from disk. + +Consequences: some Microsoft extensions are not on Open VSX and their licences forbid use outside VS Code (Pylance, C/C++, C# Dev Kit, Remote Development, Live Share, GitHub Copilot). The IDE neither works around this nor downloads them from Microsoft. Their open-source counterparts are on Open VSX (basedpyright, clangd, etc.). + +## Licensing + +- The IDE is GPL-3.0; the extension host and the API shim are our own code. Libraries used: `vscode-textmate`, `vscode-oniguruma`, `vscode-uri` (MIT). The API typings (`@types/vscode`) are MIT and only used to check the shim. +- Extensions are not shipped with the IDE: the person installs them at run time, each under its own licence, which the Extensions view shows before installing. + +## Security + +An extension is arbitrary code that runs with the person's rights, as in VS Code. The IDE does not pretend otherwise, and applies the same rules VS Code does, plus what its own baseline (README "Security baseline") requires: + +- **Nothing is downloaded unless the person asks** (searching or installing in the Extensions view). The `.vsix` is checked against the `sha256` the registry publishes, and unpacked with path checks (no `..`, no absolute paths, no links) into `/extensions/`. +- **Installing shows who publishes it** (Open VSX's verified-publisher flag), its licence, and that it will run code with the person's rights. +- **Workspace trust (#177):** in Restricted Mode only extensions that declare `capabilities.untrustedWorkspaces.supported` are activated, as in VS Code. Declarative contributions (themes, grammars) still apply. +- **The renderer stays sandboxed.** Extension code never runs in it. Webviews of extensions run in sandboxed iframes from their own origin with their own CSP, and talk to the host only through `postMessage` relayed by the main process. The renderer CSP gains `'wasm-unsafe-eval'` only, for the Oniguruma regex engine of TextMate grammars (VS Code does the same); `eval` stays forbidden. +- Every extension can be disabled or uninstalled, and the host can be restarted, from the Extensions view. + +## Revisit when + +- The *Extensions* coverage log shows that the extensions people actually use fail on API areas too large to write by hand (notebooks, debug, custom editors), or +- `monaco-vscode-api` can be adopted per service without replacing the workbench. + +Then option A becomes the better trade, and this host is retired. diff --git a/adr/README.md b/adr/README.md index 30b3d3212..af1b4f456 100644 --- a/adr/README.md +++ b/adr/README.md @@ -5,3 +5,4 @@ Decisions that shape Code-XR beyond a single feature, one file per decision, num | # | Decision | Status | |---|---|---| | [0001](0001-code-xr-ide-platform.md) | Build the Code-XR IDE on Electron + Monaco | Accepted | +| [0002](0002-vscode-extensions-in-the-ide.md) | Run VS Code extensions in the IDE with our own extension host and Open VSX | Accepted | diff --git a/apps/ide/README.md b/apps/ide/README.md index 5f245c2c3..7a857d444 100644 --- a/apps/ide/README.md +++ b/apps/ide/README.md @@ -174,6 +174,8 @@ Following Electron's [security checklist](https://www.electronjs.org/docs/latest | Git runs without a shell, on paths checked inside the open folder; discard asks natively and trashes untracked files | `src/main/git/` (`runGit`, `resolveGitPath`, `gitIpc.ts`) | Unit tests (`..`, absolute paths, symlinks out, globs, option-like branch names); smoke refuses `git.headContent('../package.json')`. | | The renderer cannot start or address a language server: it names documents by `codexr-file:` URI inside the open folder and sends only allow-listed requests with rebuilt parameters | `src/main/lsp/` (`lspUri.ts`, `lspProtocol.ts`), `LSP_REQUEST_METHODS` in `src/shared/lsp.ts` | Unit tests (`test/lsp.test.ts`: `..`, encoded separators, other schemes, refused methods, forged completion data). | | No network request unless the person asks: the update check runs from Help > Check for Updates…, or at start-up only if `update.checkOnStartup` is turned on (off by default); it reads the public GitHub releases list, downloads nothing and only opens the release page in the browser | `src/main/updates/` (`updateRelease.ts` pure, `updateCheck.ts`) | Unit tests (`test/updateCheck.test.ts`: tags, drafts, pre-releases, versions); never run in the smoke run. | +| Extensions (#251) are unpacked only from checked archives: entries under `extension/` only, no `..`, absolute paths, drive letters or links, size limits; an Open VSX download must match the registry's SHA-256; a native dialog shows publisher, verification, licence and whether it runs code before anything is installed; nothing goes online unless the person searches or installs | `src/main/extensions/` (`vsix.ts`, `openVsx.ts`, `extensionsService.ts`) | Unit tests (`test/extensions.test.ts`: zip-slip, symlink and garbage archives, wrong and missing checksums, http downloads, tampered `extensions.json`). | +| The renderer may compile WebAssembly (`'wasm-unsafe-eval'`) for the TextMate regex engine of extension grammars (#258); `eval` stays blocked | `buildContentSecurityPolicy` | Unit tests; smoke checks `eval` throws. | | The dev server URL is ignored in a packaged build | `src/main/index.ts` (`app.isPackaged`) | Code review. | Running as root (containers, some CI images) requires `--no-sandbox`, which the scripts add only in that case. It turns off Chromium's OS-level sandbox and `app.enableSandbox()`; the per-window `sandbox: true` preference and its assertion stay. @@ -304,6 +306,10 @@ The parsers (`statusParser.ts`, `blameParser.ts`) are pure and unit-tested on st 3. Register the handler in `src/main/ipc.ts` through `handle()`, which already rejects untrusted frames. Validate every argument: the renderer is untrusted. 4. Add a unit test for any pure logic, and extend the smoke probe if the capability is security-relevant. +## VS Code extensions (stream `ide-extensions`, epic #251) + +The Extensions view (activity bar, puzzle icon, `Ctrl/Cmd+Shift+X`) installs VS Code extensions from **Open VSX** (never the Visual Studio Marketplace, whose terms only allow Microsoft products; ADR [0002](../../adr/0002-vscode-extensions-in-the-ide.md)) or from a `.vsix` file, and enables, disables and uninstalls them. Colour themes, languages, TextMate grammars and snippets apply at once; extensions with code run in the extension host (#259, in progress). Design, state and how to try it: [`docs/ide/extensions.md`](../../docs/ide/extensions.md). + ## AI agent hub (stream `ai-agents`) The Agents view (activity bar, speech-bubble icon) connects the IDE to LLM providers with the person's **own API keys**. There is no Code-XR server in between: every call goes straight from the main process to the provider, and nothing is sent until a provider is configured and used. diff --git a/apps/ide/THIRD_PARTY_NOTICES.md b/apps/ide/THIRD_PARTY_NOTICES.md index 54429476e..e3a57ac45 100644 --- a/apps/ide/THIRD_PARTY_NOTICES.md +++ b/apps/ide/THIRD_PARTY_NOTICES.md @@ -83,3 +83,74 @@ Usage in this package: Usage in this package: - Bundled into the renderer by Vite: sanitises the Markdown preview's HTML before it reaches the page (#179, `src/renderer/editor/markdownPreview.ts`). The same version Monaco already depends on. + +## vscode-textmate (TextMate grammars of extensions) + +- Project: `vscode-textmate` on npm, 9.3.2, by Microsoft Corporation +- Source: https://github.com/microsoft/vscode-textmate +- License: MIT + +Usage in this package: + +- Bundled into the renderer by Vite: tokenizes files with the TextMate grammars that VS Code extensions contribute (#258, `src/renderer/extensions/textmate.ts`). + +## vscode-oniguruma (regular expressions of TextMate grammars) + +- Project: `vscode-oniguruma` on npm, 2.0.1, by Microsoft Corporation; WebAssembly build of Oniguruma 6.9.5 by K.Kosako +- Source: https://github.com/microsoft/vscode-oniguruma, https://github.com/kkos/oniguruma +- License: MIT (bindings); BSD-2-Clause (Oniguruma) + +Usage in this package: + +- Bundled into the renderer by Vite, with its `onig.wasm` served from the app (#258). It is why the CSP allows `'wasm-unsafe-eval'`. + +Oniguruma's licence text, as `vscode-oniguruma` ships it: + +``` +Oniguruma LICENSE +----------------- + +Copyright (c) 2002-2020 K.Kosako +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. +``` + +## yauzl (reading .vsix archives) + +- Project: `yauzl` on npm, 3.4.0, by Josh Wolfe +- Source: https://github.com/thejoshwolfe/yauzl +- License: MIT + +Usage in this package: + +- Bundled into the main process by Vite: reads the `.vsix` (zip) files of extensions before they are unpacked (#254, `src/main/extensions/vsix.ts`). + +## jsonc-parser (JSON with comments) + +- Project: `jsonc-parser` on npm, 3.3.1, by Microsoft Corporation +- Source: https://github.com/microsoft/node-jsonc-parser +- License: MIT + +Usage in this package: + +- Bundled into the main process by Vite: reads extension manifests, colour themes, language configurations and snippets, which VS Code allows to contain comments (#254). diff --git a/apps/ide/package.json b/apps/ide/package.json index b66d4e531..be25b25bc 100644 --- a/apps/ide/package.json +++ b/apps/ide/package.json @@ -22,17 +22,24 @@ }, "devDependencies": { "@types/node": "^22.20.7", + "@types/vscode": "1.146.0", + "@types/yauzl": "3.4.0", "@xterm/addon-fit": "0.11.0", "@xterm/xterm": "6.0.0", "dompurify": "3.4.15", "electron": "^45.5.0", "electron-builder": "26.18.1", + "jsonc-parser": "3.3.1", "marked": "14.0.0", "material-icon-theme": "^5.40.0", "monaco-editor": "0.57.0", "vite": "^8.3.8", "vscode-jsonrpc": "9.0.3", - "vscode-languageserver-types": "3.18.4" + "vscode-languageserver-types": "3.18.4", + "vscode-oniguruma": "2.0.1", + "vscode-textmate": "9.3.2", + "vscode-uri": "3.2.0", + "yauzl": "3.4.0" }, "dependencies": { "node-pty": "1.2.0-beta.18", diff --git a/apps/ide/src/main/extensions/contributions.ts b/apps/ide/src/main/extensions/contributions.ts new file mode 100644 index 000000000..bc53b5d2e --- /dev/null +++ b/apps/ide/src/main/extensions/contributions.ts @@ -0,0 +1,276 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { EXTENSION_THEME_PREFIX, type ContributedGrammar, type ContributedLanguage, type ContributedSnippet, type ContributedTheme, type ExtensionContributions, type GrammarContent, type ResolvedTheme, type ThemeTokenRule } from '../../shared/extensions.ts'; +import { readJsonc, resolveInExtension, type LoadedExtension } from './extensionStore.ts'; +import { parsePlist, type PlistValue } from './plist.ts'; + +/** + * The declarative contributions of the enabled extensions (#257, #258): + * colour themes, languages, TextMate grammars and snippets. These run no + * extension code: the main process reads the files the manifest names + * (always inside the extension's folder) and the workbench applies them. + * Grammars are handed out by an opaque reference, never by path. + */ + +function record(value: unknown): Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record : {}; +} + +function list(value: unknown): Record[] { + return Array.isArray(value) ? value.map(record) : []; +} + +function strings(value: unknown): string[] { + if (typeof value === 'string') { + return [value]; + } + return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []; +} + +function str(value: unknown): string | null { + return typeof value === 'string' && value !== '' ? value : null; +} + +const UI_THEMES = new Set(['vs', 'vs-dark', 'hc-black', 'hc-light']); +const MAX_CONTRIBUTION_FILE = 8 * 1024 * 1024; + +function themeId(extensionId: string, theme: Record): string { + return `${EXTENSION_THEME_PREFIX}${extensionId}/${str(theme.id) ?? str(theme.label) ?? str(theme.path) ?? 'theme'}`; +} + +/** A file named by the manifest, inside the extension, small enough to read; else null. */ +function contributionFile(extension: LoadedExtension, relative: unknown): string | null { + if (typeof relative !== 'string') { + return null; + } + const file = resolveInExtension(extension.location, relative); + if (!file) { + return null; + } + try { + const stat = fs.statSync(file); + return stat.isFile() && stat.size <= MAX_CONTRIBUTION_FILE ? file : null; + } catch { + return null; + } +} + +export class ContributionIndex { + private readonly extensions: readonly LoadedExtension[]; + private readonly grammarFiles = new Map(); + private readonly themeEntries = new Map; label: string; uiTheme: ContributedTheme['uiTheme'] }>(); + private readonly onWarning: (message: string) => void; + readonly contributions: ExtensionContributions; + + constructor(enabled: readonly LoadedExtension[], onWarning: (message: string) => void = () => undefined) { + this.extensions = enabled; + this.onWarning = onWarning; + this.contributions = this.collect(); + } + + private collect(): ExtensionContributions { + const themes: ContributedTheme[] = []; + const languages: ContributedLanguage[] = []; + const grammars: ContributedGrammar[] = []; + const snippets: ContributedSnippet[] = []; + for (const extension of this.extensions) { + const c = extension.manifest.contributes; + const extensionId = extension.manifest.id; + for (const theme of list(c.themes)) { + const id = themeId(extensionId, theme); + const uiTheme = UI_THEMES.has(String(theme.uiTheme)) ? theme.uiTheme as ContributedTheme['uiTheme'] : 'vs-dark'; + const label = str(theme.label) ?? str(theme.id) ?? id; + if (!contributionFile(extension, theme.path)) { + this.onWarning(`${extensionId}: theme "${label}" names a file that is missing or outside the extension.`); + continue; + } + this.themeEntries.set(id, { extension, theme, label, uiTheme }); + themes.push({ id, label, extensionId, uiTheme }); + } + for (const language of list(c.languages)) { + const id = str(language.id); + if (!id) { + continue; + } + let configuration: unknown = null; + const configFile = contributionFile(extension, language.configuration); + if (configFile) { + try { + configuration = readJsonc(configFile); + } catch (error) { + this.onWarning(`${extensionId}: ${(error as Error).message}`); + } + } + languages.push({ + id, + extensionId, + aliases: strings(language.aliases), + extensions: strings(language.extensions), + filenames: strings(language.filenames), + filenamePatterns: strings(language.filenamePatterns), + firstLine: str(language.firstLine), + mimetypes: strings(language.mimetypes), + configuration, + }); + } + list(c.grammars).forEach((grammar, index) => { + const scopeName = str(grammar.scopeName); + const file = contributionFile(extension, grammar.path); + if (!scopeName || !file) { + this.onWarning(`${extensionId}: a grammar without a scope name or a readable file was skipped.`); + return; + } + const ref = `${extensionId}#${index}`; + this.grammarFiles.set(ref, file); + const pairs = (value: unknown): Record => Object.fromEntries(Object.entries(record(value)).filter((entry): entry is [string, string] => typeof entry[1] === 'string')); + grammars.push({ + extensionId, + language: str(grammar.language), + scopeName, + ref, + embeddedLanguages: pairs(grammar.embeddedLanguages), + tokenTypes: pairs(grammar.tokenTypes), + injectTo: strings(grammar.injectTo), + }); + }); + for (const entry of list(c.snippets)) { + const file = contributionFile(extension, entry.path); + if (!file) { + continue; + } + try { + snippets.push(...parseSnippets(readJsonc(file), extensionId, str(entry.language))); + } catch (error) { + this.onWarning(`${extensionId}: snippets ${String(entry.path)}: ${(error as Error).message}`); + } + } + } + return { themes, languages, grammars, snippets }; + } + + grammarContent(ref: string): GrammarContent | null { + const file = this.grammarFiles.get(ref); + if (!file) { + return null; + } + const content = fs.readFileSync(file, 'utf8'); + return { format: /\.json$/i.test(file) ? 'json' : 'plist', content }; + } + + /** A contributed theme, with its `include` chain and any `.tmTheme` read. */ + theme(id: string): ResolvedTheme | null { + const entry = this.themeEntries.get(id); + if (!entry) { + return null; + } + const file = contributionFile(entry.extension, entry.theme.path); + if (!file) { + return null; + } + const colors: Record = {}; + const tokenColors: ThemeTokenRule[] = []; + let semanticHighlighting = false; + loadThemeFile(entry.extension, file, colors, tokenColors, (value) => { semanticHighlighting = value; }, 0); + return { id, label: entry.label, uiTheme: entry.uiTheme, colors, tokenColors, semanticHighlighting }; + } +} + +/** Reads a theme file into `colors` and `tokenColors`, following `include` first (the including file wins). */ +function loadThemeFile(extension: LoadedExtension, file: string, colors: Record, tokenColors: ThemeTokenRule[], semantic: (value: boolean) => void, depth: number): void { + if (depth > 8) { + throw new Error('Theme include chain too deep.'); + } + const relative = (target: string): string | null => { + const absolute = path.resolve(path.dirname(file), target); + return contributionFile(extension, path.relative(extension.location, absolute).split(path.sep).join('/')); + }; + if (/\.tmTheme$/i.test(file)) { + const tm = readTmTheme(fs.readFileSync(file, 'utf8')); + Object.assign(colors, { ...tm.colors, ...colors }); + tokenColors.push(...tm.rules); + return; + } + const json = record(readJsonc(file)); + if (typeof json.include === 'string') { + const included = relative(json.include); + if (included) { + loadThemeFile(extension, included, colors, tokenColors, semantic, depth + 1); + } + } + for (const [key, value] of Object.entries(record(json.colors))) { + if (typeof value === 'string') { + colors[key] = value; + } + } + if (typeof json.semanticHighlighting === 'boolean') { + semantic(json.semanticHighlighting); + } + if (typeof json.tokenColors === 'string') { + const tm = relative(json.tokenColors); + if (tm) { + loadThemeFile(extension, tm, colors, tokenColors, semantic, depth + 1); + } + } else { + tokenColors.push(...toRules(json.tokenColors)); + } +} + +function toRules(raw: unknown): ThemeTokenRule[] { + const rules: ThemeTokenRule[] = []; + for (const item of list(raw)) { + const settings = record(item.settings); + const scope = typeof item.scope === 'string' ? item.scope.split(',').map((s) => s.trim()).filter(Boolean) : strings(item.scope); + const rule: { scope: string[]; foreground?: string; background?: string; fontStyle?: string } = { scope }; + for (const key of ['foreground', 'background', 'fontStyle'] as const) { + if (typeof settings[key] === 'string') { + rule[key] = settings[key] as string; + } + } + if (rule.foreground || rule.background || rule.fontStyle !== undefined) { + rules.push(rule); + } + } + return rules; +} + +/** A `.tmTheme`: its first scope-less entry holds the editor colours, the rest are token rules. */ +export function readTmTheme(text: string): { colors: Record; rules: ThemeTokenRule[] } { + const root = parsePlist(text) as Record | null; + const settings = Array.isArray(root?.settings) ? root.settings : []; + const colors: Record = {}; + const map: Record = { + background: 'editor.background', + foreground: 'editor.foreground', + caret: 'editorCursor.foreground', + selection: 'editor.selectionBackground', + lineHighlight: 'editor.lineHighlightBackground', + invisibles: 'editorWhitespace.foreground', + findHighlight: 'editor.findMatchHighlightBackground', + }; + const entries = settings.map(record); + const global = entries.find((entry) => entry.scope === undefined); + for (const [key, value] of Object.entries(record(global?.settings))) { + if (typeof value === 'string' && map[key]) { + colors[map[key]] = value; + } + } + return { colors, rules: toRules(entries.filter((entry) => entry !== global)) }; +} + +/** A snippets file: `{ name: { prefix, body, description, scope } }`. */ +export function parseSnippets(json: unknown, extensionId: string, language: string | null): ContributedSnippet[] { + const out: ContributedSnippet[] = []; + for (const [name, raw] of Object.entries(record(json))) { + const snippet = record(raw); + const prefixes = strings(snippet.prefix); + const body = Array.isArray(snippet.body) ? strings(snippet.body).join('\n') : str(snippet.body); + if (prefixes.length === 0 || body === null) { + continue; + } + const languages = language ? [language] : (str(snippet.scope)?.split(',').map((s) => s.trim()).filter(Boolean) ?? ['*']); + for (const lang of languages) { + out.push({ extensionId, language: lang, name, prefixes, body, description: str(snippet.description) ?? '' }); + } + } + return out; +} diff --git a/apps/ide/src/main/extensions/extensionStore.ts b/apps/ide/src/main/extensions/extensionStore.ts new file mode 100644 index 000000000..992293701 --- /dev/null +++ b/apps/ide/src/main/extensions/extensionStore.ts @@ -0,0 +1,261 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { parse as parseJsonc, type ParseError } from 'jsonc-parser'; +import type { ExtensionId } from '../../shared/extensions.ts'; +import { compareVersions, isSafeRelativePath, localizeManifest, ManifestError, parseManifest, type ExtensionManifest } from './manifest.ts'; +import { extractVsix, readVsixManifest } from './vsix.ts'; + +/** + * The extensions installed for this user (#254): one folder per extension + * version under `/extensions/`, and `extensions.json` beside them + * recording what is installed, from where, and what the person turned off. + * That file lives in the IDE's user-data folder, never in a project, so a + * folder cannot enable an extension by itself (#263). + * + * No Electron import: unit-tested in Node against a temporary folder. + */ + +export interface InstalledRecord { + readonly version: string; + /** The folder's name under the store's root. */ + readonly folder: string; + readonly source: 'open-vsx' | 'vsix'; + readonly installedAt: number; +} + +interface StoreFile { + readonly version: 1; + installed: Record; + disabled: ExtensionId[]; +} + +/** An installed extension with its manifest read from disk. */ +export interface LoadedExtension { + readonly manifest: ExtensionManifest; + readonly location: string; + readonly record: InstalledRecord; + readonly enabled: boolean; +} + +function emptyFile(): StoreFile { + return { version: 1, installed: {}, disabled: [] }; +} + +/** Reads a JSON-with-comments file, as VS Code accepts for manifests, themes and configurations. */ +export function readJsonc(file: string): unknown { + const errors: ParseError[] = []; + const value = parseJsonc(fs.readFileSync(file, 'utf8'), errors, { allowTrailingComma: true, disallowComments: false }); + if (value === undefined) { + throw new Error(`Cannot parse ${path.basename(file)}.`); + } + return value; +} + +/** Parses a manifest's text with its translations (`package.nls.json`). */ +export function manifestFromText(packageJson: string, nlsJson: string | null): ExtensionManifest { + let json: unknown; + try { + json = parseJsonc(packageJson, [], { allowTrailingComma: true }); + } catch { + json = undefined; + } + if (json === undefined) { + throw new ManifestError('extension/package.json is not valid JSON.'); + } + let nls: Record = {}; + if (nlsJson) { + const parsed = parseJsonc(nlsJson, [], { allowTrailingComma: true }) as unknown; + if (typeof parsed === 'object' && parsed !== null) { + nls = parsed as Record; + } + } + return parseManifest(localizeManifest(json, nls)); +} + +/** The manifest of an unpacked extension folder. */ +export function readManifestFromFolder(folder: string): ExtensionManifest { + const nlsFile = path.join(folder, 'package.nls.json'); + return manifestFromText(fs.readFileSync(path.join(folder, 'package.json'), 'utf8'), fs.existsSync(nlsFile) ? fs.readFileSync(nlsFile, 'utf8') : null); +} + +/** A file inside an extension, or null when the relative path would leave it. */ +export function resolveInExtension(location: string, relative: string): string | null { + const cleaned = relative.replace(/^\.\//, ''); + if (!isSafeRelativePath(cleaned)) { + return null; + } + const root = path.resolve(location); + const file = path.resolve(root, ...cleaned.split(/[\\/]+/)); + if (!file.startsWith(root + path.sep)) { + return null; + } + // A link inside the folder that points out of it is refused too. + try { + const real = fs.realpathSync(file); + const realRoot = fs.realpathSync(root); + if (real !== realRoot && !real.startsWith(realRoot + path.sep)) { + return null; + } + } catch { + // Not there (yet): the caller's read will fail on its own. + } + return file; +} + +export interface InstallOutcome { + readonly extension: LoadedExtension; + /** The version it replaced, if one was installed. */ + readonly replaced: string | null; +} + +export class ExtensionStore { + readonly root: string; + private readonly file: string; + private data: StoreFile; + private cache: Map | null = null; + + constructor(root: string) { + this.root = root; + this.file = path.join(root, 'extensions.json'); + fs.mkdirSync(root, { recursive: true }); + this.data = this.read(); + } + + private read(): StoreFile { + try { + const raw = JSON.parse(fs.readFileSync(this.file, 'utf8')) as Partial; + const installed: Record = {}; + for (const [id, value] of Object.entries(raw.installed ?? {})) { + if (value && typeof value.folder === 'string' && !value.folder.includes('/') && !value.folder.includes('\\') && value.folder !== '..' && typeof value.version === 'string') { + installed[id.toLowerCase()] = { + version: value.version, + folder: value.folder, + source: value.source === 'open-vsx' ? 'open-vsx' : 'vsix', + installedAt: typeof value.installedAt === 'number' ? value.installedAt : 0, + }; + } + } + const disabled = Array.isArray(raw.disabled) ? raw.disabled.filter((id): id is string => typeof id === 'string').map((id) => id.toLowerCase()) : []; + return { version: 1, installed, disabled }; + } catch { + return emptyFile(); + } + } + + private write(): void { + const temp = `${this.file}.tmp`; + fs.writeFileSync(temp, `${JSON.stringify(this.data, null, 2)}\n`, { mode: 0o600 }); + fs.renameSync(temp, this.file); + this.cache = null; + } + + /** Every installed extension whose folder and manifest still read; broken ones are skipped. */ + list(onError?: (id: string, error: Error) => void): readonly LoadedExtension[] { + if (!this.cache) { + const cache = new Map(); + for (const [id, record] of Object.entries(this.data.installed)) { + const location = path.join(this.root, record.folder); + try { + const manifest = readManifestFromFolder(location); + if (manifest.id !== id) { + throw new Error(`its manifest says ${manifest.id}`); + } + cache.set(id, { manifest, location, record, enabled: !this.data.disabled.includes(id) }); + } catch (error) { + onError?.(id, error as Error); + } + } + this.cache = cache; + } + return [...this.cache.values()].sort((a, b) => a.manifest.displayName.localeCompare(b.manifest.displayName)); + } + + get(id: ExtensionId): LoadedExtension | undefined { + this.list(); + return this.cache?.get(id.toLowerCase()); + } + + /** Reads a `.vsix`'s manifest without installing it (to show what is about to be installed). */ + async inspect(vsixFile: string): Promise { + const preview = await readVsixManifest(vsixFile); + return manifestFromText(preview.packageJson, preview.nlsJson); + } + + /** + * Installs a `.vsix`: unpacks it into a new folder, then records it and + * removes the version it replaces. A same-version reinstall replaces the folder. + */ + async install(vsixFile: string, source: InstalledRecord['source']): Promise { + const manifest = await this.inspect(vsixFile); + const folder = `${manifest.id}-${manifest.version}`; + const target = path.join(this.root, folder); + const previous = this.data.installed[manifest.id]; + const staging = path.join(this.root, `.staging-${process.pid}-${Date.now()}`); + await extractVsix(vsixFile, staging); + const unpacked = readManifestFromFolder(staging); + if (unpacked.id !== manifest.id || unpacked.version !== manifest.version) { + await fs.promises.rm(staging, { recursive: true, force: true }); + throw new ManifestError('The archive\'s manifest changed while it was unpacked.'); + } + await fs.promises.rm(target, { recursive: true, force: true }); + await fs.promises.rename(staging, target); + const record: InstalledRecord = { version: manifest.version, folder, source, installedAt: Date.now() }; + this.data.installed[manifest.id] = record; + this.write(); + if (previous && previous.folder !== folder) { + await fs.promises.rm(path.join(this.root, previous.folder), { recursive: true, force: true }); + } + const loaded = this.get(manifest.id); + if (!loaded) { + throw new ManifestError('The extension was unpacked but its manifest cannot be read back.'); + } + return { extension: loaded, replaced: previous && previous.version !== manifest.version ? previous.version : null }; + } + + async uninstall(id: ExtensionId): Promise { + const key = id.toLowerCase(); + const record = this.data.installed[key]; + if (!record) { + return false; + } + delete this.data.installed[key]; + this.data.disabled = this.data.disabled.filter((other) => other !== key); + this.write(); + await fs.promises.rm(path.join(this.root, record.folder), { recursive: true, force: true }); + return true; + } + + setEnabled(id: ExtensionId, enabled: boolean): void { + const key = id.toLowerCase(); + if (!this.data.installed[key]) { + return; + } + const others = this.data.disabled.filter((other) => other !== key); + this.data.disabled = enabled ? others : [...others, key]; + this.write(); + } + + disableAll(): void { + this.data.disabled = Object.keys(this.data.installed); + this.write(); + } + + /** Whether a newer or equal version is installed (for "Update" vs "Install" in the view). */ + installedVersion(id: ExtensionId): string | null { + return this.data.installed[id.toLowerCase()]?.version ?? null; + } + + isNewer(id: ExtensionId, version: string): boolean { + const installed = this.installedVersion(id); + return installed === null || compareVersions(version, installed) > 0; + } + + /** Leftovers of an interrupted install (staging or partial folders). */ + cleanUp(): void { + for (const name of fs.readdirSync(this.root)) { + if (name.startsWith('.staging-') || name.includes('.partial-')) { + fs.rmSync(path.join(this.root, name), { recursive: true, force: true }); + } + } + } +} diff --git a/apps/ide/src/main/extensions/extensionsService.ts b/apps/ide/src/main/extensions/extensionsService.ts new file mode 100644 index 000000000..554317dcd --- /dev/null +++ b/apps/ide/src/main/extensions/extensionsService.ts @@ -0,0 +1,355 @@ +import { BrowserWindow, dialog, net, type IpcMainInvokeEvent, type WebContents } from 'electron'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + DEFAULT_GALLERY_URL, EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, GALLERY_URL_SETTING, isExtensionId, + type ExtensionActivation, type ExtensionContributions, type ExtensionId, type ExtensionLogEvent, type GalleryQuery, type InstallResult, type InstalledDetails, type InstalledExtension, +} from '../../shared/extensions.ts'; +import { channelLog } from '../log.ts'; +import type { SettingsService } from '../settings/settingsService.ts'; +import { addTrustChangeListener, isWorkspaceTrusted } from '../trust/workspaceTrust.ts'; +import { ContributionIndex } from './contributions.ts'; +import { ExtensionStore, resolveInExtension, type LoadedExtension } from './extensionStore.ts'; +import { engineSupported, summarizeContributions, type ExtensionManifest } from './manifest.ts'; +import { GalleryError, normalizeGalleryUrl, OpenVsxClient, type FetchLike } from './openVsx.ts'; + +type Handle = (channel: string, handler: (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown) => void; + +const extLog = channelLog('extensions'); + +/** What the extension host reports for a window (#259); empty until the host runs. */ +export interface ActivationSource { + activation(contents: WebContents, id: ExtensionId): { state: ExtensionActivation; error?: string }; +} + +const ICON_TYPES: Record = { '.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' }; +const MAX_ICON_BYTES = 256 * 1024; + +function iconOf(extension: LoadedExtension): string | null { + if (!extension.manifest.icon) { + return null; + } + const file = resolveInExtension(extension.location, extension.manifest.icon); + const type = file ? ICON_TYPES[path.extname(file).toLowerCase()] : undefined; + if (!file || !type) { + return null; + } + try { + const bytes = fs.readFileSync(file); + return bytes.length > MAX_ICON_BYTES ? null : `data:${type};base64,${bytes.toString('base64')}`; + } catch { + return null; + } +} + +function readText(location: string, names: readonly string[]): string | null { + for (const name of names) { + const file = resolveInExtension(location, name); + if (file && fs.existsSync(file)) { + try { + return fs.readFileSync(file, 'utf8').slice(0, 512 * 1024); + } catch { + return null; + } + } + } + return null; +} + +/** + * The extensions of the IDE in the main process (#254, #255, #257, #258): + * the store on disk, the Open VSX client, the declarative contributions, and + * the IPC handlers of `window.codexr.extensions`. Installing always asks in a + * native dialog that the renderer cannot answer. + */ +export class ExtensionsService { + readonly store: ExtensionStore; + private index: ContributionIndex; + private readonly icons = new Map(); + private activations: ActivationSource | null = null; + private readonly changeListeners = new Set<() => void>(); + private readonly settings: SettingsService; + private readonly fetchImpl: FetchLike; + private readonly disabledByFlag: boolean; + + constructor(options: { root: string; settings: SettingsService; fetchImpl?: FetchLike; disableExtensions?: boolean }) { + this.store = new ExtensionStore(options.root); + this.store.cleanUp(); + this.settings = options.settings; + this.fetchImpl = options.fetchImpl ?? ((url, init) => net.fetch(url, init)); + this.disabledByFlag = options.disableExtensions === true; + this.index = this.buildIndex(); + if (this.disabledByFlag) { + extLog.warn('Started with --disable-extensions: no extension contributes or runs in this session.'); + } + // #263: trusting a folder changes which extensions may run in its window. + addTrustChangeListener((contents) => this.notify(contents)); + } + + /** The extensions whose contributions apply (enabled, and not turned off by the start-up flag). */ + enabled(): readonly LoadedExtension[] { + return this.disabledByFlag ? [] : this.store.list().filter((extension) => extension.enabled); + } + + private buildIndex(): ContributionIndex { + const all = this.store.list((id, error) => extLog.warn(`${id} is installed but cannot be read: ${error.message}`)); + void all; + return new ContributionIndex(this.enabled(), (message) => extLog.warn(message)); + } + + setActivationSource(source: ActivationSource): void { + this.activations = source; + } + + onDidChange(listener: () => void): () => void { + this.changeListeners.add(listener); + return () => this.changeListeners.delete(listener); + } + + get contributions(): ExtensionContributions { + return this.index.contributions; + } + + /** Whether an extension's code may run in this window (#263). */ + mayRun(contents: WebContents | null, extension: LoadedExtension): boolean { + if (this.disabledByFlag || !extension.enabled) { + return false; + } + return extension.manifest.supportsUntrusted || contents === null || isWorkspaceTrusted(contents); + } + + describe(contents: WebContents | null, extension: LoadedExtension): InstalledExtension { + const manifest = extension.manifest; + const hasCode = manifest.main !== null; + if (!this.icons.has(manifest.id)) { + this.icons.set(manifest.id, iconOf(extension)); + } + const restricted = hasCode && !manifest.supportsUntrusted && contents !== null && !isWorkspaceTrusted(contents); + const activation = hasCode && contents && this.activations ? this.activations.activation(contents, manifest.id) : { state: hasCode ? 'inactive' as const : 'none' as const }; + return { + id: manifest.id, + publisher: manifest.publisher, + name: manifest.name, + version: manifest.version, + displayName: manifest.displayName, + description: manifest.description, + categories: manifest.categories, + license: manifest.license, + repository: manifest.repository, + icon: this.icons.get(manifest.id) ?? null, + hasCode, + state: !extension.enabled || this.disabledByFlag ? 'disabled' : restricted ? 'restricted' : 'enabled', + activation: activation.state, + ...(activation.error ? { activationError: activation.error } : {}), + engine: manifest.engine, + engineWarning: !engineSupported(manifest.engine), + source: extension.record.source, + installedAt: extension.record.installedAt, + contributes: summarizeContributions(manifest), + supportsUntrusted: manifest.supportsUntrusted, + }; + } + + list(contents: WebContents | null): InstalledExtension[] { + return this.store.list().map((extension) => this.describe(contents, extension)); + } + + /** Tells one window (or all) that the list or a state changed. */ + notify(only?: WebContents): void { + for (const win of BrowserWindow.getAllWindows()) { + if (win.isDestroyed() || (only && win.webContents !== only)) { + continue; + } + win.webContents.send(EXTENSION_IPC_EVENTS.extensionsChanged, { installed: this.list(win.webContents) }); + } + } + + private changed(): void { + this.icons.clear(); + this.index = this.buildIndex(); + this.notify(); + for (const listener of this.changeListeners) { + listener(); + } + } + + private async gallery(): Promise { + const value = (await this.settings.snapshot(null)).effective[GALLERY_URL_SETTING]; + const url = typeof value === 'string' && normalizeGalleryUrl(value) ? value : DEFAULT_GALLERY_URL; + return new OpenVsxClient(url, this.fetchImpl); + } + + /** The native confirmation shown before anything is installed. */ + private async confirmInstall(contents: WebContents, manifest: ExtensionManifest, origin: string, verified: boolean | null): Promise { + const win = BrowserWindow.fromWebContents(contents); + const replacing = this.store.installedVersion(manifest.id); + const lines = [ + `${manifest.displayName} ${manifest.version}`, + `Identifier: ${manifest.id}`, + `Publisher: ${manifest.publisher}${verified === null ? '' : verified ? ' (verified by the registry)' : ' (NOT verified by the registry)'}`, + `Licence: ${manifest.license ?? 'not stated'}`, + `From: ${origin}`, + ]; + if (replacing) { + lines.push(`Replaces version ${replacing}.`); + } + lines.push('', manifest.main + ? 'This extension contains code. It runs on this computer with your user\'s rights, as in VS Code. Install extensions only from publishers you trust.' + : 'This extension only contributes themes, languages or snippets; it runs no code.'); + if (!engineSupported(manifest.engine)) { + lines.push('', `It asks for VS Code ${manifest.engine}; the IDE implements part of that API, so some features may not work.`); + } + const options = { + type: 'question' as const, + buttons: ['Install', 'Cancel'], + defaultId: 0, + cancelId: 1, + noLink: true, + title: 'Install extension', + message: `Install ${manifest.displayName}?`, + detail: lines.join('\n'), + }; + const { response } = win ? await dialog.showMessageBox(win, options) : await dialog.showMessageBox(options); + return response === 0; + } + + private async installFile(contents: WebContents, file: string, source: 'open-vsx' | 'vsix', origin: string, verified: boolean | null, expectedId?: ExtensionId): Promise { + const manifest = await this.store.inspect(file); + if (expectedId && manifest.id !== expectedId) { + return { ok: false, error: `The registry sent ${manifest.id} instead of ${expectedId}; it was not installed.` }; + } + if (!(await this.confirmInstall(contents, manifest, origin, verified))) { + return { ok: false, cancelled: true, error: 'Cancelled.' }; + } + const outcome = await this.store.install(file, source); + extLog.info(`Installed ${manifest.id} ${manifest.version} from ${origin}${outcome.replaced ? ` (replaced ${outcome.replaced})` : ''}.`); + this.changed(); + return { ok: true, extension: this.describe(contents, outcome.extension), replaced: outcome.replaced }; + } + + async install(contents: WebContents, id: unknown, version: unknown): Promise { + if (!isExtensionId(id) || (version !== undefined && (typeof version !== 'string' || !/^[0-9A-Za-z.+-]{1,64}$/.test(version)))) { + throw new Error('Invalid extension.'); + } + const gallery = await this.gallery(); + const temp = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'codexr-vsix-')); + try { + extLog.info(`Downloading ${id}${version ? ` ${version}` : ''} from ${gallery.url}…`); + const download = await gallery.download(id.toLowerCase(), version as string | undefined); + const file = path.join(temp, 'extension.vsix'); + await fs.promises.writeFile(file, download.bytes); + return await this.installFile(contents, file, 'open-vsx', new URL(gallery.url).host, download.verified, id.toLowerCase()); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + extLog.error(`Installing ${id} failed: ${message}`); + return { ok: false, error: message }; + } finally { + await fs.promises.rm(temp, { recursive: true, force: true }); + } + } + + async installVsix(contents: WebContents, file?: string): Promise { + let chosen = file; + if (!chosen) { + const win = BrowserWindow.fromWebContents(contents); + const options = { title: 'Install from VSIX', properties: ['openFile' as const], filters: [{ name: 'VS Code extension', extensions: ['vsix'] }] }; + const picked = win ? await dialog.showOpenDialog(win, options) : await dialog.showOpenDialog(options); + if (picked.canceled || picked.filePaths.length === 0) { + return { ok: false, cancelled: true, error: 'Cancelled.' }; + } + chosen = picked.filePaths[0] ?? ''; + } + try { + return await this.installFile(contents, chosen, 'vsix', path.basename(chosen), null); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + extLog.error(`Installing ${path.basename(chosen)} failed: ${message}`); + return { ok: false, error: message }; + } + } + + async uninstall(contents: WebContents, id: unknown): Promise { + if (!isExtensionId(id)) { + throw new Error('Invalid extension.'); + } + const extension = this.store.get(id); + if (!extension) { + return false; + } + const win = BrowserWindow.fromWebContents(contents); + const options = { type: 'question' as const, buttons: ['Uninstall', 'Cancel'], defaultId: 0, cancelId: 1, noLink: true, title: 'Uninstall extension', message: `Uninstall ${extension.manifest.displayName}?`, detail: `${extension.manifest.id} ${extension.manifest.version} and its files are removed.` }; + const { response } = win ? await dialog.showMessageBox(win, options) : await dialog.showMessageBox(options); + if (response !== 0) { + return false; + } + const removed = await this.store.uninstall(id); + if (removed) { + extLog.info(`Uninstalled ${id}.`); + this.changed(); + } + return removed; + } + + setEnabled(id: unknown, enabled: unknown): void { + if (!isExtensionId(id) || typeof enabled !== 'boolean') { + throw new Error('Invalid extension.'); + } + this.store.setEnabled(id, enabled); + extLog.info(`${enabled ? 'Enabled' : 'Disabled'} ${id}.`); + this.changed(); + } + + disableAll(): void { + this.store.disableAll(); + extLog.info('Disabled every installed extension.'); + this.changed(); + } + + details(contents: WebContents, id: unknown): InstalledDetails | null { + if (!isExtensionId(id)) { + throw new Error('Invalid extension.'); + } + const extension = this.store.get(id); + if (!extension) { + return null; + } + return { + extension: this.describe(contents, extension), + readme: readText(extension.location, ['README.md', 'readme.md', 'README.MD', 'Readme.md']), + changelog: readText(extension.location, ['CHANGELOG.md', 'changelog.md']), + }; + } + + log(event: ExtensionLogEvent): void { + extLog[event.level](event.message); + } + + register(handle: Handle): void { + handle(EXTENSION_IPC_CHANNELS.extensionsList, (event) => this.list(event.sender)); + handle(EXTENSION_IPC_CHANNELS.extensionsSearch, async (_event, query) => { + const q = (typeof query === 'object' && query !== null ? query : {}) as Partial; + try { + return await (await this.gallery()).search({ text: typeof q.text === 'string' ? q.text : '', ...(typeof q.category === 'string' ? { category: q.category } : {}), ...(q.sortBy ? { sortBy: q.sortBy } : {}), offset: typeof q.offset === 'number' ? q.offset : 0, size: typeof q.size === 'number' ? q.size : 30 }); + } catch (error) { + throw new Error(error instanceof GalleryError ? error.message : `Search failed: ${String(error)}`); + } + }); + handle(EXTENSION_IPC_CHANNELS.extensionsGalleryDetails, async (_event, id) => { + if (!isExtensionId(id)) { + throw new Error('Invalid extension.'); + } + return (await this.gallery()).details(id.toLowerCase()); + }); + handle(EXTENSION_IPC_CHANNELS.extensionsGalleryIcon, async (_event, url) => (typeof url === 'string' ? (await this.gallery()).icon(url) : null)); + handle(EXTENSION_IPC_CHANNELS.extensionsInstall, (event, id, version) => this.install(event.sender, id, version)); + handle(EXTENSION_IPC_CHANNELS.extensionsInstallVsix, (event) => this.installVsix(event.sender)); + handle(EXTENSION_IPC_CHANNELS.extensionsUninstall, (event, id) => this.uninstall(event.sender, id)); + handle(EXTENSION_IPC_CHANNELS.extensionsSetEnabled, (_event, id, enabled) => this.setEnabled(id, enabled)); + handle(EXTENSION_IPC_CHANNELS.extensionsDisableAll, () => this.disableAll()); + handle(EXTENSION_IPC_CHANNELS.extensionsDetails, (event, id) => this.details(event.sender, id)); + handle(EXTENSION_IPC_CHANNELS.extensionsContributions, () => this.index.contributions); + handle(EXTENSION_IPC_CHANNELS.extensionsTheme, (_event, id) => (typeof id === 'string' && id.length < 600 ? this.index.theme(id) : null)); + handle(EXTENSION_IPC_CHANNELS.extensionsGrammarContent, (_event, ref) => (typeof ref === 'string' && ref.length < 600 ? this.index.grammarContent(ref) : null)); + } +} diff --git a/apps/ide/src/main/extensions/manifest.ts b/apps/ide/src/main/extensions/manifest.ts new file mode 100644 index 000000000..ab938384f --- /dev/null +++ b/apps/ide/src/main/extensions/manifest.ts @@ -0,0 +1,204 @@ +import { extensionIdOf, HOST_VSCODE_API_VERSION, type ContributionSummary, type ExtensionId } from '../../shared/extensions.ts'; + +/** + * The `package.json` of a VS Code extension (#254), validated. Pure: no file + * access, unit-tested in Node. Only what the IDE reads is typed; the rest of + * the manifest is kept as `raw` for the extension host, which hands it to the + * extension as `extension.packageJSON`. + */ + +export interface ExtensionManifest { + readonly id: ExtensionId; + readonly publisher: string; + readonly name: string; + readonly version: string; + readonly displayName: string; + readonly description: string; + readonly engine: string; + readonly main: string | null; + readonly browser: string | null; + readonly icon: string | null; + readonly categories: readonly string[]; + readonly license: string | null; + readonly repository: string | null; + readonly activationEvents: readonly string[]; + readonly extensionDependencies: readonly ExtensionId[]; + readonly extensionPack: readonly ExtensionId[]; + readonly contributes: Readonly>; + /** `capabilities.untrustedWorkspaces.supported` is `true` or `"limited"`. */ + readonly supportsUntrusted: boolean; + readonly raw: Readonly>; +} + +export class ManifestError extends Error {} + +const NAME = /^[a-z0-9][a-z0-9._-]*$/i; + +function str(value: unknown): string | null { + return typeof value === 'string' && value.trim() !== '' ? value : null; +} + +function strings(value: unknown): string[] { + return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []; +} + +function record(value: unknown): Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record : {}; +} + +/** + * Replaces `%key%` placeholders with the strings of `package.nls.json`, as + * VS Code does for `displayName`, `description`, command titles and settings. + * Works on any JSON value; unknown keys stay as they are. + */ +export function localizeManifest(value: unknown, nls: Readonly>): unknown { + if (typeof value === 'string') { + const match = /^%([^%]+)%$/.exec(value); + if (match?.[1] !== undefined) { + const entry = nls[match[1]]; + if (typeof entry === 'string') { + return entry; + } + // { message, comment } entries (vscode-nls format). + const message = record(entry).message; + if (typeof message === 'string') { + return message; + } + } + return value; + } + if (Array.isArray(value)) { + return value.map((item) => localizeManifest(item, nls)); + } + if (typeof value === 'object' && value !== null) { + const out: Record = {}; + for (const [key, item] of Object.entries(value)) { + out[key] = localizeManifest(item, nls); + } + return out; + } + return value; +} + +function repositoryUrl(value: unknown): string | null { + const url = typeof value === 'string' ? value : str(record(value).url); + if (!url) { + return null; + } + const cleaned = url.replace(/^git\+/, '').replace(/\.git$/, ''); + return /^https:\/\//i.test(cleaned) ? cleaned : null; +} + +/** Parses and validates a manifest already read as JSON (and localised). */ +export function parseManifest(json: unknown): ExtensionManifest { + const raw = record(json); + const publisher = str(raw.publisher); + const name = str(raw.name); + const version = str(raw.version); + if (!publisher || !NAME.test(publisher)) { + throw new ManifestError('The extension has no valid "publisher".'); + } + if (!name || !NAME.test(name)) { + throw new ManifestError('The extension has no valid "name".'); + } + if (!version || !/^\d+\.\d+\.\d+([-+][0-9A-Za-z.-]+)?$/.test(version)) { + throw new ManifestError('The extension has no valid "version".'); + } + const engine = str(record(raw.engines).vscode); + if (!engine) { + throw new ManifestError('The extension does not declare "engines.vscode": it is not a VS Code extension.'); + } + const main = str(raw.main); + const icon = str(raw.icon); + for (const [field, value] of [['main', main], ['icon', icon]] as const) { + if (value !== null && !isSafeRelativePath(value)) { + throw new ManifestError(`"${field}" points outside the extension.`); + } + } + const untrusted = record(record(raw.capabilities).untrustedWorkspaces).supported; + return { + id: extensionIdOf(publisher, name), + publisher, + name, + version, + displayName: str(raw.displayName) ?? name, + description: str(raw.description) ?? '', + engine, + main, + browser: str(raw.browser), + icon, + categories: strings(raw.categories), + license: str(raw.license), + repository: repositoryUrl(raw.repository), + activationEvents: strings(raw.activationEvents), + extensionDependencies: strings(raw.extensionDependencies).map((id) => id.toLowerCase()), + extensionPack: strings(raw.extensionPack).map((id) => id.toLowerCase()), + contributes: record(raw.contributes), + supportsUntrusted: untrusted === true || untrusted === 'limited', + raw, + }; +} + +/** A path inside the extension: relative, `/` or `\` separated, no `..`, no drive, no NUL. */ +export function isSafeRelativePath(value: string): boolean { + if (value === '' || value.includes('\0') || /^[a-zA-Z]:/.test(value) || value.startsWith('/') || value.startsWith('\\')) { + return false; + } + return !value.split(/[\\/]+/).some((segment) => segment === '..'); +} + +/** The contributions as counts and names for the Extensions view. */ +export function summarizeContributions(manifest: ExtensionManifest): ContributionSummary { + const c = manifest.contributes; + const list = (key: string): Record[] => (Array.isArray(c[key]) ? (c[key] as unknown[]).map(record) : []); + const views = Object.values(record(c.views)).flatMap((entries) => (Array.isArray(entries) ? entries.map(record) : [])); + const configuration = Array.isArray(c.configuration) ? c.configuration.map(record) : [record(c.configuration)]; + return { + themes: list('themes').map((theme) => str(theme.label) ?? str(theme.id) ?? '').filter(Boolean), + iconThemes: list('iconThemes').map((theme) => str(theme.label) ?? str(theme.id) ?? '').filter(Boolean), + languages: list('languages').map((language) => str(language.id) ?? '').filter(Boolean), + grammars: list('grammars').length, + snippets: list('snippets').length, + commands: list('commands').map((command) => str(command.title) ?? str(command.command) ?? '').filter(Boolean), + views: views.map((view) => str(view.name) ?? str(view.id) ?? '').filter(Boolean), + settings: configuration.reduce((sum, section) => sum + Object.keys(record(section.properties)).length, 0), + keybindings: list('keybindings').length, + localizations: list('localizations').map((loc) => str(loc.languageName) ?? str(loc.languageId) ?? '').filter(Boolean), + }; +} + +/** A semver triple, prerelease ignored; null when it does not parse. */ +function triple(version: string): [number, number, number] | null { + const match = /^(\d+)\.(\d+)\.(\d+)/.exec(version.trim()); + return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null; +} + +export function compareVersions(a: string, b: string): number { + const x = triple(a) ?? [0, 0, 0]; + const y = triple(b) ?? [0, 0, 0]; + for (let i = 0; i < 3; i++) { + const d = (x[i] ?? 0) - (y[i] ?? 0); + if (d !== 0) { + return d; + } + } + return 0; +} + +/** + * Whether `engines.vscode` (`^1.80.0`, `>=1.60.0`, `1.x`, `*`) is satisfied by + * the API version the host implements. Only the minimum matters: VS Code + * itself treats the range as "at least". + */ +export function engineSupported(engine: string, hostVersion: string = HOST_VSCODE_API_VERSION): boolean { + const trimmed = engine.trim(); + if (trimmed === '*' || trimmed === '') { + return true; + } + const match = /(\d+)\.(\d+|x)(?:\.(\d+|x))?/.exec(trimmed); + if (!match) { + return true; + } + const wanted = `${match[1]}.${match[2] === 'x' ? 0 : match[2]}.${match[3] === undefined || match[3] === 'x' ? 0 : match[3]}`; + return compareVersions(hostVersion, wanted) >= 0; +} diff --git a/apps/ide/src/main/extensions/openVsx.ts b/apps/ide/src/main/extensions/openVsx.ts new file mode 100644 index 000000000..f618adab7 --- /dev/null +++ b/apps/ide/src/main/extensions/openVsx.ts @@ -0,0 +1,287 @@ +import { createHash } from 'node:crypto'; +import { extensionIdOf, GALLERY_SORTS, type ExtensionId, type GalleryDetails, type GalleryExtension, type GalleryQuery, type GallerySearchResult } from '../../shared/extensions.ts'; + +/** + * A client for an Open VSX registry (#254, ADR 0002): open-vsx.org by + * default, or a company's own instance (setting `extensions.gallery.serviceUrl`). + * Its REST API is public and needs no key. Every request is started by the + * person (a search, opening a details page, an install); nothing here runs on + * its own. `fetch` is injected: Electron's `net.fetch` in the app (it honours + * the system proxy), a fake server in the unit tests. + */ + +export type FetchLike = (url: string, init?: { signal?: AbortSignal; headers?: Record }) => Promise<{ + readonly ok: boolean; + readonly status: number; + readonly headers: { get(name: string): string | null }; + json(): Promise; + text(): Promise; + arrayBuffer(): Promise; +}>; + +export class GalleryError extends Error {} + +const TIMEOUT_MS = 20_000; +const DOWNLOAD_TIMEOUT_MS = 5 * 60_000; +/** The largest `.vsix` the IDE downloads. */ +export const MAX_VSIX_BYTES = 300 * 1024 * 1024; +const MAX_ICON_BYTES = 512 * 1024; + +/** The registry base URL from the setting, or null when it is not acceptable (https, or http on this machine). */ +export function normalizeGalleryUrl(value: string): string | null { + let url: URL; + try { + url = new URL(value.trim()); + } catch { + return null; + } + const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]'; + if (url.username || url.password || !(url.protocol === 'https:' || (url.protocol === 'http:' && local))) { + return null; + } + return url.toString().replace(/\/+$/, ''); +} + +/** Only https downloads (registries put files on a CDN of another host), or the registry's own origin. */ +function checkFileUrl(raw: unknown, base: string): string { + if (typeof raw !== 'string') { + throw new GalleryError('The registry answered without a file address.'); + } + const url = new URL(raw, `${base}/`); + if (url.protocol !== 'https:' && url.origin !== new URL(base).origin) { + throw new GalleryError(`Refused a download over ${url.protocol}`); + } + return url.toString(); +} + +/** Open VSX's name for the platform the IDE runs on. */ +export function targetPlatform(platform: string = process.platform, arch: string = process.arch): string { + const os = platform === 'win32' ? 'win32' : platform === 'darwin' ? 'darwin' : platform === 'linux' ? 'linux' : null; + const cpu = arch === 'x64' ? 'x64' : arch === 'arm64' ? 'arm64' : arch === 'arm' ? 'armhf' : null; + return os && cpu && !(os !== 'linux' && cpu === 'armhf') ? `${os}-${cpu}` : 'universal'; +} + +function record(value: unknown): Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record : {}; +} + +function text(value: unknown, fallback = ''): string { + return typeof value === 'string' ? value : fallback; +} + +function num(value: unknown): number { + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} + +function toGalleryExtension(raw: unknown): GalleryExtension | null { + const item = record(raw); + const namespace = text(item.namespace); + const name = text(item.name); + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(namespace) || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) { + return null; + } + const icon = record(item.files).icon; + return { + id: extensionIdOf(namespace, name), + namespace, + name, + version: text(item.version), + displayName: text(item.displayName) || name, + description: text(item.description), + iconUrl: typeof icon === 'string' && /^https:\/\//.test(icon) ? icon : null, + downloadCount: num(item.downloadCount), + averageRating: typeof item.averageRating === 'number' ? item.averageRating : null, + verified: item.verified === true, + timestamp: typeof item.timestamp === 'string' ? item.timestamp : null, + }; +} + +/** Splits `publisher.name` (the name may itself contain dots). */ +export function splitExtensionId(id: ExtensionId): { namespace: string; name: string } { + const dot = id.indexOf('.'); + return { namespace: id.slice(0, dot), name: id.slice(dot + 1) }; +} + +function compareDesc(a: string, b: string): number { + const parse = (v: string): number[] => v.split(/[.+-]/).slice(0, 3).map((part) => Number.parseInt(part, 10) || 0); + const x = parse(a); + const y = parse(b); + for (let i = 0; i < 3; i++) { + const d = (y[i] ?? 0) - (x[i] ?? 0); + if (d !== 0) { + return d; + } + } + return 0; +} + +export interface DownloadedVsix { + readonly bytes: Buffer; + readonly version: string; + readonly verified: boolean; + readonly sha256: string; +} + +export class OpenVsxClient { + private readonly base: string; + private readonly fetchImpl: FetchLike; + private readonly platform: string; + + constructor(base: string, fetchImpl: FetchLike, platform: string = targetPlatform()) { + const normalized = normalizeGalleryUrl(base); + if (!normalized) { + throw new GalleryError(`Not an acceptable registry address: ${base} (https, or http on this machine).`); + } + this.base = normalized; + this.fetchImpl = fetchImpl; + this.platform = platform; + } + + get url(): string { + return this.base; + } + + private async request(url: string, timeoutMs = TIMEOUT_MS): Promise>> { + let response; + try { + response = await this.fetchImpl(url, { signal: AbortSignal.timeout(timeoutMs), headers: { Accept: 'application/json' } }); + } catch (error) { + throw new GalleryError(`Cannot reach the extension registry (${new URL(url).host}): ${(error as Error).message}`); + } + if (!response.ok) { + throw new GalleryError(response.status === 404 ? 'Not found in the extension registry.' : `The extension registry answered ${response.status}.`); + } + return response; + } + + private async getJson(path: string): Promise> { + const response = await this.request(`${this.base}${path}`); + const body = record(await response.json()); + if (typeof body.error === 'string') { + throw new GalleryError(body.error); + } + return body; + } + + async search(query: GalleryQuery): Promise { + const params = new URLSearchParams(); + params.set('query', query.text.slice(0, 200)); + if (query.category) { + params.set('category', query.category.slice(0, 64)); + } + const sortBy = query.sortBy && (GALLERY_SORTS as readonly string[]).includes(query.sortBy) ? query.sortBy : 'relevance'; + params.set('sortBy', sortBy); + params.set('sortOrder', 'desc'); + params.set('offset', String(Math.max(0, Math.floor(query.offset ?? 0)))); + params.set('size', String(Math.min(50, Math.max(1, Math.floor(query.size ?? 30))))); + params.set('includeAllVersions', 'false'); + const body = await this.getJson(`/api/-/search?${params.toString()}`); + const extensions = (Array.isArray(body.extensions) ? body.extensions : []).map(toGalleryExtension).filter((item): item is GalleryExtension => item !== null); + return { offset: num(body.offset), totalSize: num(body.totalSize), extensions }; + } + + /** The registry's JSON for an extension: this platform's build when there is one, else the universal one. */ + private async metadata(id: ExtensionId, version?: string): Promise> { + const { namespace, name } = splitExtensionId(id); + const ns = encodeURIComponent(namespace); + const ext = encodeURIComponent(name); + const suffix = version ? `/${encodeURIComponent(version)}` : ''; + if (this.platform !== 'universal') { + try { + return await this.getJson(`/api/${ns}/${ext}/${this.platform}${suffix}`); + } catch (error) { + if (!(error instanceof GalleryError)) { + throw error; + } + } + } + return this.getJson(`/api/${ns}/${ext}${suffix}`); + } + + async details(id: ExtensionId): Promise { + const body = await this.metadata(id); + const base = toGalleryExtension(body); + if (!base) { + throw new GalleryError('The registry sent an extension without a valid name.'); + } + const files = record(body.files); + let readme: string | null = null; + if (typeof files.readme === 'string') { + try { + readme = (await (await this.request(checkFileUrl(files.readme, this.base))).text()).slice(0, 512 * 1024); + } catch { + readme = null; + } + } + const versions = Object.keys(record(body.allVersions)).filter((v) => v !== 'latest' && v !== 'pre-release').sort(compareDesc); + const publishedBy = record(body.publishedBy); + const targets = Array.isArray(body.allTargetPlatformVersions) + ? body.allTargetPlatformVersions.flatMap((entry) => (Array.isArray(record(entry).targetPlatforms) ? record(entry).targetPlatforms as unknown[] : [])).filter((t): t is string => typeof t === 'string') + : [text(body.targetPlatform, 'universal')]; + const repository = text(body.repository); + const homepage = text(body.homepage); + return { + ...base, + publisherDisplayName: text(body.namespaceDisplayName) || text(publishedBy.fullName) || base.namespace, + license: text(body.license) || null, + repository: /^https:\/\//.test(repository) ? repository.replace(/\.git$/, '') : null, + homepage: /^https:\/\//.test(homepage) ? homepage : null, + categories: Array.isArray(body.categories) ? body.categories.filter((c): c is string => typeof c === 'string') : [], + tags: Array.isArray(body.tags) ? body.tags.filter((t): t is string => typeof t === 'string').slice(0, 30) : [], + engine: text(record(body.engines).vscode) || null, + versions, + readme, + targetPlatforms: [...new Set(targets)], + }; + } + + /** + * Downloads the `.vsix` and checks it against the registry's SHA-256. + * A registry that publishes no checksum is refused: the archive could not + * be told apart from a corrupted or swapped one. + */ + async download(id: ExtensionId, version?: string): Promise { + const body = await this.metadata(id, version); + const files = record(body.files); + const downloadUrl = checkFileUrl(files.download, this.base); + if (typeof files.sha256 !== 'string') { + throw new GalleryError('The registry publishes no SHA-256 for this extension; it was not installed.'); + } + const expected = ((await (await this.request(checkFileUrl(files.sha256, this.base))).text()).trim().split(/\s+/)[0] ?? '').toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(expected)) { + throw new GalleryError('The registry sent a malformed SHA-256.'); + } + const response = await this.request(downloadUrl, DOWNLOAD_TIMEOUT_MS); + const length = Number(response.headers.get('content-length') ?? '0'); + if (length > MAX_VSIX_BYTES) { + throw new GalleryError('The extension is larger than the IDE downloads.'); + } + const bytes = Buffer.from(await response.arrayBuffer()); + if (bytes.length > MAX_VSIX_BYTES) { + throw new GalleryError('The extension is larger than the IDE downloads.'); + } + const actual = createHash('sha256').update(bytes).digest('hex'); + if (actual !== expected) { + throw new GalleryError('The downloaded file does not match the registry\'s SHA-256; it was not installed.'); + } + return { bytes, version: text(body.version), verified: body.verified === true, sha256: actual }; + } + + /** An icon as a `data:` URL, so the renderer never fetches from the network itself. */ + async icon(url: string): Promise { + if (!/^https:\/\//.test(url)) { + return null; + } + try { + const response = await this.request(url); + const type = ((response.headers.get('content-type') ?? '').split(';')[0] ?? '').trim().toLowerCase(); + if (!['image/png', 'image/jpeg', 'image/svg+xml', 'image/gif', 'image/webp'].includes(type)) { + return null; + } + const bytes = Buffer.from(await response.arrayBuffer()); + return bytes.length > MAX_ICON_BYTES ? null : `data:${type};base64,${bytes.toString('base64')}`; + } catch { + return null; + } + } +} diff --git a/apps/ide/src/main/extensions/plist.ts b/apps/ide/src/main/extensions/plist.ts new file mode 100644 index 000000000..1f2ec4818 --- /dev/null +++ b/apps/ide/src/main/extensions/plist.ts @@ -0,0 +1,129 @@ +/** + * A minimal reader for XML property lists, the format of `.tmTheme` colour + * themes (#257): dict, array, string, integer, real, true, false. Enough for + * TextMate themes; anything else reads as null. Pure, unit-tested. + */ + +export type PlistValue = string | number | boolean | null | PlistValue[] | { [key: string]: PlistValue }; + +class Reader { + private pos = 0; + private readonly text: string; + + constructor(text: string) { + this.text = text; + } + + private skip(): void { + for (;;) { + const rest = this.text.slice(this.pos); + const ws = /^\s+/.exec(rest); + if (ws) { + this.pos += ws[0].length; + continue; + } + if (rest.startsWith('', this.pos) + 3 : this.text.indexOf('>', this.pos) + 1; + if (end <= this.pos) { + throw new Error('Unterminated declaration.'); + } + this.pos = end; + continue; + } + return; + } + } + + /** Reads the next tag: `{ name, close, selfClosing }`. */ + private tag(): { name: string; close: boolean; selfClosing: boolean } { + this.skip(); + const match = /^<(\/?)([A-Za-z]+)[^>]*?(\/?)>/.exec(this.text.slice(this.pos)); + if (!match) { + throw new Error(`Expected a tag at ${this.pos}.`); + } + this.pos += match[0].length; + return { name: match[2] ?? '', close: match[1] === '/', selfClosing: match[3] === '/' }; + } + + private textUntil(name: string): string { + const end = this.text.indexOf(``, this.pos); + if (end < 0) { + throw new Error(`Unterminated <${name}>.`); + } + const raw = this.text.slice(this.pos, end); + this.pos = end + name.length + 3; + return decode(raw); + } + + document(): PlistValue { + const open = this.tag(); + if (open.name !== 'plist') { + return this.value(open); + } + const value = this.value(this.tag()); + return value; + } + + private value(open: { name: string; close: boolean; selfClosing: boolean }): PlistValue { + switch (open.name) { + case 'dict': { + const dict: { [key: string]: PlistValue } = {}; + if (open.selfClosing) { + return dict; + } + for (;;) { + const next = this.tag(); + if (next.close && next.name === 'dict') { + return dict; + } + if (next.name !== 'key') { + throw new Error('Expected in .'); + } + const key = this.textUntil('key'); + dict[key] = this.value(this.tag()); + } + } + case 'array': { + const array: PlistValue[] = []; + if (open.selfClosing) { + return array; + } + for (;;) { + const next = this.tag(); + if (next.close && next.name === 'array') { + return array; + } + array.push(this.value(next)); + } + } + case 'string': + return open.selfClosing ? '' : this.textUntil('string'); + case 'integer': + case 'real': { + const n = Number(this.textUntil(open.name)); + return Number.isFinite(n) ? n : null; + } + case 'true': + return true; + case 'false': + return false; + default: + if (!open.selfClosing) { + this.textUntil(open.name); + } + return null; + } + } +} + +function decode(raw: string): string { + return raw + .replace(//g, '$1') + .replace(/&#x([0-9a-f]+);/gi, (_m, hex: string) => String.fromCodePoint(Number.parseInt(hex, 16))) + .replace(/&#(\d+);/g, (_m, dec: string) => String.fromCodePoint(Number.parseInt(dec, 10))) + .replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '\'').replace(/&/g, '&'); +} + +export function parsePlist(text: string): PlistValue { + return new Reader(text).document(); +} diff --git a/apps/ide/src/main/extensions/vsix.ts b/apps/ide/src/main/extensions/vsix.ts new file mode 100644 index 000000000..d7608e531 --- /dev/null +++ b/apps/ide/src/main/extensions/vsix.ts @@ -0,0 +1,201 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import yauzl from 'yauzl'; +import { isSafeRelativePath } from './manifest.ts'; + +/** + * Reading and unpacking a `.vsix` (#254). A VSIX is a zip whose `extension/` + * folder is the extension; the rest (`[Content_Types].xml`, + * `extension.vsixmanifest`) is packaging. Archives are untrusted input, so + * every entry is checked before a byte is written: it must sit under + * `extension/`, be a relative path with no `..`, drive letter or NUL, not be + * a symbolic link, and the archive must stay inside the entry and size + * limits (a zip bomb stops at the limit, not at the disk). + */ + +export const VSIX_LIMITS = { + maxEntries: 30_000, + maxFileBytes: 256 * 1024 * 1024, + maxTotalBytes: 768 * 1024 * 1024, +}; + +export class VsixError extends Error {} + +const PREFIX = 'extension/'; + +interface Entry { + readonly name: string; + readonly relative: string; + readonly isDirectory: boolean; + readonly size: number; + readonly raw: yauzl.Entry; +} + +/** Whether a zip entry's Unix mode (high 16 bits of the external attributes) is a symbolic link. */ +export function isSymlinkEntry(externalFileAttributes: number): boolean { + const mode = (externalFileAttributes >>> 16) & 0o170000; + return mode === 0o120000; +} + +/** + * The path an entry unpacks to, relative to the extension folder, or null + * for packaging files outside `extension/`. Throws for anything unsafe. + */ +export function vsixEntryPath(name: string): string | null { + if (name.includes('\\') || name.includes('\0')) { + throw new VsixError(`Unsafe path in the archive: ${JSON.stringify(name)}`); + } + if (!name.startsWith(PREFIX)) { + if (name.startsWith('/') || name.split('/').includes('..')) { + throw new VsixError(`Unsafe path in the archive: ${JSON.stringify(name)}`); + } + return null; + } + const relative = name.slice(PREFIX.length).replace(/\/$/, ''); + if (relative === '') { + return ''; + } + if (!isSafeRelativePath(relative) || relative.split('/').some((segment) => segment === '' || segment === '.')) { + throw new VsixError(`Unsafe path in the archive: ${JSON.stringify(name)}`); + } + return relative; +} + +function open(file: string): Promise { + return new Promise((resolve, reject) => { + yauzl.open(file, { lazyEntries: true, autoClose: false, strictFileNames: true, validateEntrySizes: true }, (error, zip) => { + if (error || !zip) { + reject(new VsixError(`Not a valid .vsix (zip) file: ${error?.message ?? 'unknown error'}`)); + } else { + resolve(zip); + } + }); + }); +} + +function listEntries(zip: yauzl.ZipFile): Promise { + return new Promise((resolve, reject) => { + const entries: Entry[] = []; + let total = 0; + const fail = (error: Error): void => { + zip.close(); + reject(error); + }; + zip.on('error', (error: Error) => fail(new VsixError(`Broken archive: ${error.message}`))); + zip.on('entry', (raw: yauzl.Entry) => { + try { + if (entries.length >= VSIX_LIMITS.maxEntries) { + throw new VsixError(`The archive has more than ${VSIX_LIMITS.maxEntries} files.`); + } + const relative = vsixEntryPath(raw.fileName); + if (relative !== null) { + if (isSymlinkEntry(raw.externalFileAttributes)) { + throw new VsixError(`The archive contains a symbolic link: ${raw.fileName}`); + } + if (raw.uncompressedSize > VSIX_LIMITS.maxFileBytes) { + throw new VsixError(`A file in the archive is too large: ${raw.fileName}`); + } + total += raw.uncompressedSize; + if (total > VSIX_LIMITS.maxTotalBytes) { + throw new VsixError('The archive unpacks to more than the allowed size.'); + } + entries.push({ name: raw.fileName, relative, isDirectory: raw.fileName.endsWith('/'), size: raw.uncompressedSize, raw }); + } + zip.readEntry(); + } catch (error) { + fail(error as Error); + } + }); + zip.on('end', () => resolve(entries)); + zip.readEntry(); + }); +} + +function readEntry(zip: yauzl.ZipFile, entry: yauzl.Entry): Promise { + return new Promise((resolve, reject) => { + zip.openReadStream(entry, (error, stream) => { + if (error || !stream) { + reject(new VsixError(`Cannot read ${entry.fileName}: ${error?.message ?? ''}`)); + return; + } + const chunks: Buffer[] = []; + let size = 0; + stream.on('data', (chunk: Buffer) => { + size += chunk.length; + if (size > VSIX_LIMITS.maxFileBytes) { + stream.destroy(new VsixError(`A file in the archive is too large: ${entry.fileName}`)); + return; + } + chunks.push(chunk); + }); + stream.on('error', reject); + stream.on('end', () => resolve(Buffer.concat(chunks))); + }); + }); +} + +/** The VSIX's files read into memory by name (for the manifest and its translations). */ +export interface VsixPreview { + readonly packageJson: string; + readonly nlsJson: string | null; +} + +/** Reads `extension/package.json` (and `package.nls.json`) without unpacking anything. */ +export async function readVsixManifest(file: string): Promise { + const zip = await open(file); + try { + const entries = await listEntries(zip); + const find = (relative: string): Entry | undefined => entries.find((entry) => entry.relative === relative && !entry.isDirectory); + const pkg = find('package.json'); + if (!pkg) { + throw new VsixError('The archive has no extension/package.json: it is not a VS Code extension.'); + } + const nls = find('package.nls.json'); + return { + packageJson: (await readEntry(zip, pkg.raw)).toString('utf8'), + nlsJson: nls ? (await readEntry(zip, nls.raw)).toString('utf8') : null, + }; + } finally { + zip.close(); + } +} + +/** + * Unpacks the `extension/` folder of a VSIX into `target`, which must not + * exist yet. Writes into a sibling temporary folder first and renames it at + * the end, so a failed unpack leaves nothing half-installed. + */ +export async function extractVsix(file: string, target: string): Promise { + if (fs.existsSync(target)) { + throw new VsixError(`The folder already exists: ${target}`); + } + const temp = `${target}.partial-${process.pid}-${Date.now()}`; + const zip = await open(file); + try { + const entries = await listEntries(zip); + await fs.promises.mkdir(temp, { recursive: true }); + const root = path.resolve(temp); + for (const entry of entries) { + if (entry.relative === '') { + continue; + } + const destination = path.resolve(root, ...entry.relative.split('/')); + // Belt and braces: vsixEntryPath already refused anything that could leave the folder. + if (destination !== root && !destination.startsWith(root + path.sep)) { + throw new VsixError(`Unsafe path in the archive: ${entry.name}`); + } + if (entry.isDirectory) { + await fs.promises.mkdir(destination, { recursive: true }); + continue; + } + await fs.promises.mkdir(path.dirname(destination), { recursive: true }); + await fs.promises.writeFile(destination, await readEntry(zip, entry.raw), { flag: 'wx' }); + } + await fs.promises.rename(temp, target); + } catch (error) { + await fs.promises.rm(temp, { recursive: true, force: true }); + throw error; + } finally { + zip.close(); + } +} diff --git a/apps/ide/src/main/index.ts b/apps/ide/src/main/index.ts index dd68e3565..7f8446efd 100644 --- a/apps/ide/src/main/index.ts +++ b/apps/ide/src/main/index.ts @@ -3,6 +3,7 @@ import path from 'node:path'; import { applyProcessHardening } from './hardening.ts'; import { registerAppSchemeAsPrivileged, serveRenderer } from './appProtocol.ts'; import { registerIpcHandlers } from './ipc.ts'; +import { ExtensionsService } from './extensions/extensionsService.ts'; import { fileStorage, memoryStorage, SettingsService } from './settings/settingsService.ts'; import { KeybindingsService } from './settings/keybindingsService.ts'; import { KEYBINDINGS_FILE_NAME } from '../shared/keybindings.ts'; @@ -120,7 +121,13 @@ async function start(): Promise { }); const lsp = createLspHost(); languageServers = lsp; - registerIpcHandlers(origins, isDevelopment, core, terminalHost, settings, keybindings, output, agentServices, lsp); + // #251: VS Code extensions, in the user-data folder (a throwaway one in the smoke run). + const extensions = new ExtensionsService({ + root: isSmoke ? path.join(app.getPath('temp'), `codexr-smoke-extensions-${process.pid}`) : path.join(app.getPath('userData'), 'extensions'), + settings, + disableExtensions: process.argv.includes('--disable-extensions'), + }); + registerIpcHandlers(origins, isDevelopment, core, terminalHost, settings, keybindings, output, agentServices, lsp, extensions); // #171: the stored theme, before the first window paints. applyColorTheme((await settings.snapshot(null)).effective[COLOR_THEME_SETTING]); installApplicationMenu(isDevelopment); diff --git a/apps/ide/src/main/ipc.ts b/apps/ide/src/main/ipc.ts index a8ff44ff6..740b6ab6a 100644 --- a/apps/ide/src/main/ipc.ts +++ b/apps/ide/src/main/ipc.ts @@ -8,6 +8,7 @@ import { registerGitHandlers } from './git/gitIpc.ts'; import type { LspHost } from './lsp/lspHost.ts'; import { registerLspHandlers } from './lsp/lspIpc.ts'; import { registerTaskHandlers } from './tasks/taskHost.ts'; +import type { ExtensionsService } from './extensions/extensionsService.ts'; import { reportUnsaved } from './unsavedGuard.ts'; import { isOpenableExternalLink, isTrustedIpcCall } from './security.ts'; import { log } from './log.ts'; @@ -31,7 +32,7 @@ type Handler = (event: IpcMainInvokeEvent, ...args: unknown[]) => unknown; * through `handle`, which refuses calls from frames outside the trusted * origins, so a handler never has to check its caller itself. */ -export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: boolean, core: CoreServices, terminal: TerminalHost, settings: SettingsService, keybindings: KeybindingsService, output: OutputService, agents: AgentServices, lsp: LspHost): void { +export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: boolean, core: CoreServices, terminal: TerminalHost, settings: SettingsService, keybindings: KeybindingsService, output: OutputService, agents: AgentServices, lsp: LspHost, extensions: ExtensionsService): void { const registered = new Set(); const handle = (channel: string, handler: Handler): void => { if (!ALLOWED_IPC_CHANNELS.has(channel)) { @@ -241,6 +242,8 @@ export function registerIpcHandlers(origins: ReadonlySet, isDevelopment: registerLspHandlers(handle, lsp); // #176: tasks and Run Current File (tasks/taskHost.ts), in trusted folders only. registerTaskHandlers(handle, terminal, settings); + // #251: VS Code extensions (extensions/extensionsService.ts). + extensions.register(handle); // Every channel in the contract must have a handler: a missing one would // only surface as a rejected promise in the renderer. diff --git a/apps/ide/src/main/security.ts b/apps/ide/src/main/security.ts index 23fa8e1ab..48d356bee 100644 --- a/apps/ide/src/main/security.ts +++ b/apps/ide/src/main/security.ts @@ -95,12 +95,17 @@ export interface CspOptions { * `img-src` and `font-src` stay on the app, so injected CSS cannot load or * send anything off it. Development additionally allows the dev server's HMR * websocket. + * + * #258: `'wasm-unsafe-eval'` lets the page compile WebAssembly, which the + * Oniguruma regex engine of TextMate grammars is (vscode-oniguruma, fetched + * from the app itself). It does not allow `eval` or `new Function`; VS Code + * ships the same source. */ export function buildContentSecurityPolicy(options: CspOptions = {}): string { const dev = options.devServerOrigin; const directives: Array<[string, string[]]> = [ ['default-src', ["'none'"]], - ['script-src', ["'self'"]], + ['script-src', ["'self'", "'wasm-unsafe-eval'"]], ['style-src', ["'self'", "'unsafe-inline'"]], ['img-src', ["'self'", 'data:']], ['font-src', ["'self'"]], diff --git a/apps/ide/src/preload/index.ts b/apps/ide/src/preload/index.ts index b8b0b0949..c0954b410 100644 --- a/apps/ide/src/preload/index.ts +++ b/apps/ide/src/preload/index.ts @@ -7,6 +7,7 @@ import { IDE_COMMANDS, IPC_CHANNELS, IPC_EVENTS, type AutoStartMode, type FileAn import { GIT_IPC_CHANNELS, GIT_IPC_EVENTS } from '../shared/git.ts'; import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentChatEvent, type AgentProfileInput, type ApprovalDecision, type EditReviewResult, type ChatAttachment, type McpServerInput, type ModelPrice, type BudgetSettings, type ProviderInput } from '../shared/agents.ts'; import { TASK_IPC_CHANNELS, TASK_IPC_EVENTS, type TaskFinished } from '../shared/tasks.ts'; +import { EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, type ExtensionsChangedEvent, type ExtensionLogEvent, type GalleryQuery } from '../shared/extensions.ts'; import { LSP_IPC_CHANNELS, LSP_IPC_EVENTS, type LspDiagnosticsEvent, type LspLanguage, type LspRequestMethod } from '../shared/lsp.ts'; const KNOWN_COMMANDS: ReadonlySet = new Set(IDE_COMMANDS); @@ -95,6 +96,24 @@ const api: CodeXRApi = Object.freeze({ request: (method: LspRequestMethod, params: unknown) => ipcRenderer.invoke(LSP_IPC_CHANNELS.lspRequest, method, params), onDiagnostics: (listener: (event: LspDiagnosticsEvent) => void) => subscribe(LSP_IPC_EVENTS.lspDiagnostics, listener), }), + // #251: extensions by id; main asks natively before anything is installed or removed. + extensions: Object.freeze({ + list: () => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsList), + search: (query: GalleryQuery) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsSearch, query), + galleryDetails: (id: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsGalleryDetails, id), + galleryIcon: (url: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsGalleryIcon, url), + install: (id: string, version?: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsInstall, id, version), + installVsix: () => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsInstallVsix), + uninstall: (id: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsUninstall, id), + setEnabled: (id: string, enabled: boolean) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsSetEnabled, id, enabled), + disableAll: () => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsDisableAll), + details: (id: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsDetails, id), + contributions: () => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsContributions), + theme: (themeId: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsTheme, themeId), + grammarContent: (ref: string) => ipcRenderer.invoke(EXTENSION_IPC_CHANNELS.extensionsGrammarContent, ref), + onDidChange: (listener: (event: ExtensionsChangedEvent) => void) => subscribe(EXTENSION_IPC_EVENTS.extensionsChanged, listener), + onLog: (listener: (event: ExtensionLogEvent) => void) => subscribe(EXTENSION_IPC_EVENTS.extensionsLog, listener), + }), app: Object.freeze({ getInfo: () => ipcRenderer.invoke(IPC_CHANNELS.appGetInfo), onNotification: (listener: (notification: HostNotification) => void) => subscribe(IPC_EVENTS.hostNotification, listener), diff --git a/apps/ide/src/renderer/editor/monaco.ts b/apps/ide/src/renderer/editor/monaco.ts index 0de64780e..99636e284 100644 --- a/apps/ide/src/renderer/editor/monaco.ts +++ b/apps/ide/src/renderer/editor/monaco.ts @@ -30,12 +30,25 @@ for (const defaults of [monaco.typescript.typescriptDefaults, monaco.typescript. defaults.setDiagnosticsOptions({ noSemanticValidation: true, noSyntaxValidation: false }); } -/** Light or dark, following the operating system like the rest of the workbench. */ +/** #257: a colour theme of an extension, defined by extensions/themeController.ts; it wins over the OS scheme. */ +let themeOverride: string | null = null; +const systemQuery = window.matchMedia('(prefers-color-scheme: dark)'); +const applyTheme = (): void => monaco.editor.setTheme(themeOverride ?? (systemQuery.matches ? 'vs-dark' : 'vs')); +let following = false; + +/** Light or dark, following the operating system like the rest of the workbench (or an extension's theme, #257). */ export function followSystemTheme(): void { - const query = window.matchMedia('(prefers-color-scheme: dark)'); - const apply = (): void => monaco.editor.setTheme(query.matches ? 'vs-dark' : 'vs'); - apply(); - query.addEventListener('change', apply); + applyTheme(); + if (!following) { + following = true; + systemQuery.addEventListener('change', applyTheme); + } +} + +/** #257: uses a theme defined with `monaco.editor.defineTheme`, or null to follow the OS again. */ +export function setThemeOverride(name: string | null): void { + themeOverride = name; + applyTheme(); } export { monaco }; diff --git a/apps/ide/src/renderer/extensions/contributionsController.ts b/apps/ide/src/renderer/extensions/contributionsController.ts new file mode 100644 index 000000000..f6b6b984e --- /dev/null +++ b/apps/ide/src/renderer/extensions/contributionsController.ts @@ -0,0 +1,96 @@ +import type { ExtensionContributions, ExtensionsApi, ResolvedTheme } from '../../shared/extensions.ts'; +import { workbenchVariables } from './themeModel.ts'; +import type * as MonacoContributions from './monacoContributions.ts'; + +/** + * Applies the declarative contributions of the enabled extensions to this + * window (#257, #258) and follows changes: installing, enabling or removing + * an extension, or choosing another colour theme. The workbench colours are + * set here (CSS custom properties on the root element, no Monaco); Monaco's + * part lives in monacoContributions.ts and is loaded only when needed. + */ + +export interface ContributionsController { + /** The contributions as last loaded. */ + current(): ExtensionContributions; + /** Re-reads the contributions (an extension changed). */ + reload(): Promise; + /** Applies the theme the settings name (`workbench.colorThemeExtension`), '' for none. */ + setTheme(themeId: string): Promise; + /** Shows a theme without storing it (the theme picker); null goes back to the applied one. */ + previewTheme(themeId: string | null): Promise; +} + +const EMPTY: ExtensionContributions = { themes: [], languages: [], grammars: [], snippets: [] }; + +export function createContributionsController(api: ExtensionsApi, onError: (message: string) => void): ContributionsController { + let contributions = EMPTY; + let appliedThemeId = ''; + let shownThemeId = ''; + let setVariables: string[] = []; + let monacoPart: Promise | null = null; + const loadMonaco = (): Promise => (monacoPart ??= import('./monacoContributions.ts')); + + const needsMonaco = (c: ExtensionContributions): boolean => c.languages.length > 0 || c.grammars.length > 0 || c.snippets.length > 0; + + const paint = async (themeId: string): Promise => { + shownThemeId = themeId; + let theme: ResolvedTheme | null = null; + if (themeId !== '') { + try { + theme = await api.theme(themeId); + } catch (error) { + onError(`The theme could not be read: ${String(error)}`); + } + if (!theme) { + onError(`The colour theme ${themeId} is not available (its extension was disabled or removed); following the OS.`); + } + } + if (shownThemeId !== themeId) { + return; + } + const root = document.documentElement; + for (const name of setVariables) { + root.style.removeProperty(name); + } + setVariables = []; + if (theme) { + for (const [name, value] of Object.entries(workbenchVariables(theme))) { + root.style.setProperty(name, value); + setVariables.push(name); + } + } + root.dataset.extensionTheme = theme ? theme.id : ''; + if (theme || monacoPart) { + (await loadMonaco()).applyEditorTheme(theme); + } + }; + + const reload = async (): Promise => { + try { + contributions = await api.contributions(); + } catch (error) { + onError(`Could not read the extensions' contributions: ${String(error)}`); + return; + } + if (needsMonaco(contributions) || monacoPart) { + (await loadMonaco()).applyContributions(contributions, api, onError); + } + // A theme whose extension went away falls back to the OS. + if (appliedThemeId !== '') { + await paint(appliedThemeId); + } + }; + + return { + current: () => contributions, + reload, + async setTheme(themeId: string): Promise { + appliedThemeId = themeId; + await paint(themeId); + }, + async previewTheme(themeId: string | null): Promise { + await paint(themeId ?? appliedThemeId); + }, + }; +} diff --git a/apps/ide/src/renderer/extensions/extensions.css b/apps/ide/src/renderer/extensions/extensions.css new file mode 100644 index 000000000..e75624a99 --- /dev/null +++ b/apps/ide/src/renderer/extensions/extensions.css @@ -0,0 +1,55 @@ +/* #255: the Extensions view and the details page of an extension. Colours are the workbench tokens only. */ + +.side-pane[data-view='extensions']:not([hidden]) { display: flex; flex-direction: column; min-height: 0; height: 100%; } +.extensions-search-row { display: flex; padding: 0 8px 8px 12px; } +.extensions-scroll { flex: 1; min-height: 0; overflow: auto; padding-bottom: 12px; } +.extensions-section { display: flex; flex-direction: column; } +.extensions-section[hidden] { display: none; } +.extensions-section-title { margin: 6px 12px 4px; font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; color: var(--muted); } +.extensions-section .side-note { margin: 2px 12px 8px; } +.extensions-list { list-style: none; margin: 0; padding: 0; } +.extensions-more { margin: 6px 12px; align-self: flex-start; } +.extensions-more[hidden] { display: none; } + +.extension-row { display: flex; gap: 10px; padding: 8px 10px 8px 12px; cursor: pointer; border-left: 2px solid transparent; min-width: 0; } +.extension-row:hover { background: var(--hover); } +.extension-row:focus-visible { outline: 1px solid var(--accent); outline-offset: -1px; } +.extension-icon { flex: none; width: 36px; height: 36px; border-radius: 4px; object-fit: contain; } +.extension-icon.is-placeholder { background: var(--hover); } +.extension-icon.is-large { width: 96px; height: 96px; } +.extension-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } +.extension-title-line { display: flex; align-items: baseline; gap: 8px; min-width: 0; } +.extension-name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.extension-meta { flex: none; font-size: 11px; margin-left: auto; } +.extension-description { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.extension-footer { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; font-size: 12px; } +.extension-publisher { display: inline-flex; align-items: center; gap: 3px; color: var(--muted); } +.extension-verified svg { width: 13px; height: 13px; fill: none; stroke: var(--accent); stroke-width: 1.8; stroke-linejoin: round; } +.extension-state { color: var(--accent); } +.extension-actions { display: inline-flex; gap: 4px; margin-left: auto; } +.extension-action { margin: 0; width: auto; padding: 2px 8px; font-size: 12px; } +.extension-busy, .extension-installed-mark { font-size: 12px; } + +.extension-details { grid-area: editor; z-index: 39; display: flex; flex-direction: column; min-width: 0; min-height: 0; background: var(--editor); overflow: auto; } +.extension-details:focus { outline: none; } +.extension-details-loading { margin: 24px; } +.extension-details-head { display: flex; gap: 20px; align-items: flex-start; padding: 20px 24px 16px; border-bottom: 1px solid var(--line); } +.extension-details-title { flex: 1; min-width: 0; } +.extension-details-title h2 { margin: 0 0 4px; font-size: 22px; font-weight: 600; overflow-wrap: anywhere; } +.extension-details-publisher { display: flex; align-items: center; gap: 4px; margin: 0 0 6px; color: var(--muted); } +.extension-details-description { margin: 0 0 10px; } +.extension-details-actions { display: flex; flex-wrap: wrap; gap: 6px; } +.extension-details-actions .extension-action { padding: 4px 12px; font-size: 13px; } +.extension-details-body { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(200px, 280px); gap: 24px; padding: 16px 24px 24px; min-height: 0; } +.extension-details-readme { min-width: 0; } +.extension-details-readme .markdown-preview { border: 0; height: auto; } +.extension-details-readme .markdown-preview-header { display: none; } +.extension-details-readme .markdown-preview-body { overflow: visible; padding: 0; } +.extension-details-side { min-width: 0; } +.extension-details-side h3 { margin: 16px 0 6px; font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; color: var(--muted); } +.extension-details-facts { display: grid; grid-template-columns: auto 1fr; gap: 4px 10px; margin: 0; font-size: 12px; } +.extension-details-facts dt { color: var(--muted); } +.extension-details-facts dd { margin: 0; overflow-wrap: anywhere; } +@media (max-width: 900px) { + .extension-details-body { grid-template-columns: minmax(0, 1fr); } +} diff --git a/apps/ide/src/renderer/extensions/extensionsModel.ts b/apps/ide/src/renderer/extensions/extensionsModel.ts new file mode 100644 index 000000000..0a22e0c80 --- /dev/null +++ b/apps/ide/src/renderer/extensions/extensionsModel.ts @@ -0,0 +1,68 @@ +import type { GalleryExtension, InstalledExtension } from '../../shared/extensions.ts'; + +/** Pure helpers of the Extensions view (#255), unit-tested in Node. */ + +/** `1234567` -> `1.2M`, `45300` -> `45.3K`. */ +export function compactCount(value: number): string { + if (value >= 1_000_000) { + return `${trim(value / 1_000_000)}M`; + } + if (value >= 1_000) { + return `${trim(value / 1_000)}K`; + } + return String(Math.max(0, Math.round(value))); +} + +function trim(value: number): string { + return value >= 100 ? String(Math.round(value)) : value.toFixed(1).replace(/\.0$/, ''); +} + +/** What an installed extension's row says about it. */ +export function installedStateLabel(extension: InstalledExtension): string { + if (extension.state === 'disabled') { + return 'Disabled'; + } + if (extension.state === 'restricted') { + return 'Disabled in Restricted Mode'; + } + if (extension.activation === 'failed') { + return 'Failed to activate'; + } + if (extension.activation === 'active') { + return 'Active'; + } + return extension.engineWarning ? `Enabled (asks for VS Code ${extension.engine})` : 'Enabled'; +} + +/** The action a registry result offers. */ +export function rowAction(gallery: GalleryExtension, installed: InstalledExtension | undefined, busy: boolean): { kind: 'busy' | 'install' | 'update' | 'installed' } { + if (busy) { + return { kind: 'busy' }; + } + if (!installed) { + return { kind: 'install' }; + } + return { kind: newer(gallery.version, installed.version) ? 'update' : 'installed' }; +} + +function newer(a: string, b: string): boolean { + const parse = (v: string): number[] => v.split(/[.+-]/).slice(0, 3).map((part) => Number.parseInt(part, 10) || 0); + const x = parse(a); + const y = parse(b); + for (let i = 0; i < 3; i++) { + const d = (x[i] ?? 0) - (y[i] ?? 0); + if (d !== 0) { + return d > 0; + } + } + return false; +} + +/** Whether an installed extension matches the search text (name, id, publisher, description). */ +export function matchesInstalled(extension: InstalledExtension, text: string): boolean { + const needle = text.trim().toLowerCase(); + if (needle === '') { + return true; + } + return [extension.displayName, extension.id, extension.publisher, extension.description, ...extension.categories].some((field) => field.toLowerCase().includes(needle)); +} diff --git a/apps/ide/src/renderer/extensions/extensionsView.ts b/apps/ide/src/renderer/extensions/extensionsView.ts new file mode 100644 index 000000000..e1dd6fbaf --- /dev/null +++ b/apps/ide/src/renderer/extensions/extensionsView.ts @@ -0,0 +1,480 @@ +import type { ExtensionId, ExtensionsApi, GalleryDetails, GalleryExtension, InstalledDetails, InstalledExtension, InstallResult } from '../../shared/extensions.ts'; +import { el, icon } from '../dom.ts'; +import { compactCount, installedStateLabel, matchesInstalled, rowAction } from './extensionsModel.ts'; + +/** + * The Extensions view (#255): the installed extensions, a search of the Open + * VSX registry, and a details page over the editor area with the README. + * Nothing goes online until the person types a search or opens a registry + * page. Install and Uninstall always end in a native confirmation in the + * main process (the renderer cannot answer it). + */ + +export interface ExtensionsView { + focusSearch(text?: string): void; + /** The list changed (an event from the main process). */ + setInstalled(installed: readonly InstalledExtension[]): void; + showDetails(id: ExtensionId): void; + installVsix(): Promise; +} + +export interface ExtensionsViewHooks { + onStatus(message: string): void; + notify(kind: 'info' | 'warning' | 'error', message: string): void; + openExternalLink(url: string): void; + /** Where the details page goes: the workbench root (it sits over the editor area). */ + readonly detailsHost: HTMLElement; + /** Builds the README view (the Markdown preview of #179, loaded on first use). */ + renderMarkdown(text: string, container: HTMLElement): Promise; + /** After an install: offers the colour themes it brought, for example. */ + afterInstall(extension: InstalledExtension): void; +} + +const ICONS = { + vsix: 'M12 4v11M7 10l5 5 5-5M5 19h14', + refresh: 'M20 12a8 8 0 1 1-2.3-5.6M20 4v5h-5', + verified: 'M12 2l2.4 2.1 3.2-.3.7 3.1 2.8 1.6-1.3 2.9 1.3 2.9-2.8 1.6-.7 3.1-3.2-.3L12 22l-2.4-2.1-3.2.3-.7-3.1-2.8-1.6 1.3-2.9-1.3-2.9 2.8-1.6.7-3.1 3.2.3zM8.5 12l2.5 2.5 4.5-5', + close: 'M6 6l12 12M18 6L6 18', + puzzle: 'M4 4h7v7H4zM4 13h7v7H4zM13 13h7v7h-7zM16.5 3l4.5 4.5L16.5 12 12 7.5z', +}; + +const SEARCH_DELAY_MS = 350; +const PAGE = 30; + +export function createExtensionsView(container: HTMLElement, api: ExtensionsApi, hooks: ExtensionsViewHooks): ExtensionsView { + let installed: readonly InstalledExtension[] = []; + let results: GalleryExtension[] = []; + let total = 0; + let query = ''; + let searchSeq = 0; + let timer: ReturnType | undefined; + const busy = new Set(); + const iconCache = new Map>(); + + const iconButton = (label: string, path: string, testId: string, run: () => void): HTMLButtonElement => { + const button = el('button', { className: 'icon-button', attrs: { type: 'button', title: label, 'aria-label': label, 'data-testid': testId } }, [icon(path)]); + button.addEventListener('click', run); + return button; + }; + + const searchField = el('input', { className: 'search-input extensions-search', attrs: { type: 'search', placeholder: 'Search extensions in Open VSX', 'aria-label': 'Search extensions in Open VSX', spellcheck: 'false', 'data-testid': 'extensions-search' } }); + const installedList = el('ul', { className: 'extensions-list', attrs: { 'aria-label': 'Installed extensions', 'data-testid': 'extensions-installed' } }); + const resultsList = el('ul', { className: 'extensions-list', attrs: { 'aria-label': 'Open VSX results', 'data-testid': 'extensions-results' } }); + const installedTitle = el('h3', { className: 'extensions-section-title', text: 'Installed' }); + const resultsTitle = el('h3', { className: 'extensions-section-title', text: 'Open VSX' }); + const resultsNote = el('p', { className: 'muted side-note', attrs: { 'data-testid': 'extensions-results-note' } }); + const more = el('button', { className: 'secondary-button extensions-more', text: 'Show more', attrs: { type: 'button', hidden: '' } }); + const popular = el('button', { className: 'secondary-button extensions-more', text: 'Browse popular extensions', attrs: { type: 'button', 'data-testid': 'extensions-popular' } }); + const resultsSection = el('section', { className: 'extensions-section' }, [resultsTitle, resultsNote, resultsList, more]); + const installedNote = el('p', { className: 'muted side-note', text: 'No extensions installed yet. Search Open VSX above, or install a .vsix file.' }); + const installedSection = el('section', { className: 'extensions-section' }, [installedTitle, installedNote, installedList, popular]); + + container.append( + el('div', { className: 'side-bar-header' }, [ + el('h2', { className: 'side-bar-title', text: 'Extensions' }), + el('div', { className: 'side-bar-actions' }, [ + iconButton('Install from VSIX…', ICONS.vsix, 'extensions-install-vsix', () => void view.installVsix()), + iconButton('Refresh', ICONS.refresh, 'extensions-refresh', () => void refreshInstalled()), + ]), + ]), + el('div', { className: 'extensions-search-row' }, [searchField]), + el('div', { className: 'extensions-scroll' }, [resultsSection, installedSection]), + ); + resultsSection.hidden = true; + + function installedOf(id: ExtensionId): InstalledExtension | undefined { + return installed.find((extension) => extension.id === id); + } + + function galleryIcon(url: string | null, img: HTMLImageElement): void { + if (!url) { + return; + } + let pending = iconCache.get(url); + if (!pending) { + pending = api.galleryIcon(url).catch(() => null); + iconCache.set(url, pending); + } + void pending.then((data) => { + if (data) { + img.src = data; + img.classList.remove('is-placeholder'); + } + }); + } + + function iconElement(src: string | null): HTMLImageElement { + const img = el('img', { className: 'extension-icon', attrs: { alt: '', 'aria-hidden': 'true' } }); + if (src && src.startsWith('data:')) { + img.src = src; + return img; + } + img.classList.add('is-placeholder'); + return img; + } + + async function runInstall(id: ExtensionId, version?: string): Promise { + if (busy.has(id)) { + return; + } + busy.add(id); + render(); + hooks.onStatus(`Installing ${id}…`); + let result: InstallResult; + try { + result = await api.install(id, version); + } catch (error) { + result = { ok: false, error: String(error) }; + } + busy.delete(id); + finishInstall(result); + } + + function finishInstall(result: InstallResult): void { + if (result.ok) { + hooks.onStatus(`Installed ${result.extension.displayName} ${result.extension.version}.`); + hooks.notify('info', `${result.extension.displayName} ${result.extension.version} installed${result.replaced ? ` (was ${result.replaced})` : ''}.`); + hooks.afterInstall(result.extension); + } else if (!result.cancelled) { + hooks.notify('error', `The extension was not installed: ${result.error}`); + hooks.onStatus(''); + } else { + hooks.onStatus(''); + } + void refreshInstalled(); + } + + async function toggle(extension: InstalledExtension): Promise { + await api.setEnabled(extension.id, extension.state === 'disabled'); + } + + async function uninstall(extension: InstalledExtension): Promise { + busy.add(extension.id); + render(); + try { + if (await api.uninstall(extension.id)) { + hooks.notify('info', `${extension.displayName} uninstalled.`); + } + } catch (error) { + hooks.notify('error', `Could not uninstall ${extension.displayName}: ${String(error)}`); + } finally { + busy.delete(extension.id); + void refreshInstalled(); + } + } + + function actionButton(label: string, testId: string, run: () => void, primary = false): HTMLButtonElement { + const button = el('button', { className: primary ? 'primary-button extension-action' : 'secondary-button extension-action', text: label, attrs: { type: 'button', 'data-testid': testId } }); + button.addEventListener('click', (event) => { + event.stopPropagation(); + run(); + }); + return button; + } + + function installedRow(extension: InstalledExtension): HTMLElement { + const state = installedStateLabel(extension); + const actions: HTMLElement[] = []; + if (busy.has(extension.id)) { + actions.push(el('span', { className: 'muted extension-busy', text: 'Working…' })); + } else { + actions.push(actionButton(extension.state === 'disabled' ? 'Enable' : 'Disable', `extension-toggle-${extension.id}`, () => void toggle(extension))); + actions.push(actionButton('Uninstall', `extension-uninstall-${extension.id}`, () => void uninstall(extension))); + } + return row(extension.id, extension.icon, extension.displayName, extension.publisher, false, extension.description, `v${extension.version}`, state, actions, () => showDetails(extension.id)); + } + + function galleryRow(extension: GalleryExtension): HTMLElement { + const action = rowAction(extension, installedOf(extension.id), busy.has(extension.id)); + const actions: HTMLElement[] = []; + if (action.kind === 'busy') { + actions.push(el('span', { className: 'muted extension-busy', text: 'Installing…' })); + } else if (action.kind === 'install' || action.kind === 'update') { + actions.push(actionButton(action.kind === 'install' ? 'Install' : `Update to ${extension.version}`, `extension-install-${extension.id}`, () => void runInstall(extension.id), true)); + } else { + actions.push(el('span', { className: 'muted extension-installed-mark', text: 'Installed' })); + } + const item = row(extension.id, null, extension.displayName, extension.namespace, extension.verified, extension.description, `${compactCount(extension.downloadCount)} downloads`, null, actions, () => showDetails(extension.id, extension)); + const img = item.querySelector('img'); + if (img) { + galleryIcon(extension.iconUrl, img); + } + return item; + } + + function row(id: string, iconSrc: string | null, name: string, publisher: string, verified: boolean, description: string, meta: string, state: string | null, actions: HTMLElement[], open: () => void): HTMLElement { + const publisherLine = el('span', { className: 'extension-publisher' }, [document.createTextNode(publisher)]); + if (verified) { + publisherLine.append(el('span', { className: 'extension-verified', attrs: { title: 'Verified publisher', 'aria-label': 'verified publisher' } }, [icon(ICONS.verified)])); + } + const item = el('li', { className: 'extension-row', attrs: { tabindex: '0', role: 'button', 'data-extension-id': id, 'data-testid': `extension-row-${id}` } }, [ + iconElement(iconSrc), + el('div', { className: 'extension-main' }, [ + el('div', { className: 'extension-title-line' }, [ + el('span', { className: 'extension-name', text: name }), + el('span', { className: 'extension-meta muted', text: meta }), + ]), + el('div', { className: 'extension-description', text: description }), + el('div', { className: 'extension-footer' }, [publisherLine, ...(state ? [el('span', { className: 'extension-state', text: state })] : []), el('span', { className: 'extension-actions' }, actions)]), + ]), + ]); + item.addEventListener('click', open); + item.addEventListener('keydown', (event) => { + if ((event.key === 'Enter' || event.key === ' ') && event.target === item) { + event.preventDefault(); + open(); + } + }); + return item; + } + + function render(): void { + const filter = query.trim(); + const shownInstalled = installed.filter((extension) => matchesInstalled(extension, filter)); + installedList.replaceChildren(...shownInstalled.map(installedRow)); + installedNote.hidden = installed.length > 0; + installedTitle.textContent = filter ? `Installed (${shownInstalled.length})` : `Installed (${installed.length})`; + resultsList.replaceChildren(...results.map(galleryRow)); + more.hidden = results.length >= total || results.length === 0; + } + + async function refreshInstalled(): Promise { + try { + installed = await api.list(); + } catch (error) { + hooks.notify('error', `Could not list the extensions: ${String(error)}`); + } + render(); + if (details && detailsId) { + void fillDetails(detailsId, detailsGallery); + } + } + + async function search(text: string, offset: number, sortBy?: 'downloadCount'): Promise { + const seq = ++searchSeq; + resultsSection.hidden = false; + resultsTitle.textContent = sortBy ? 'Popular on Open VSX' : 'Open VSX'; + resultsNote.textContent = 'Searching…'; + try { + const page = await api.search({ text, offset, size: PAGE, ...(sortBy ? { sortBy } : {}) }); + if (seq !== searchSeq) { + return; + } + results = offset === 0 ? [...page.extensions] : [...results, ...page.extensions]; + total = page.totalSize; + resultsNote.textContent = total === 0 ? 'No extension matches.' : `${total.toLocaleString()} found`; + } catch (error) { + if (seq !== searchSeq) { + return; + } + results = []; + total = 0; + resultsNote.textContent = `The registry could not be searched: ${errorText(error)}`; + } + render(); + } + + let lastSort: 'downloadCount' | undefined; + searchField.addEventListener('input', () => { + query = searchField.value; + clearTimeout(timer); + render(); + if (query.trim() === '') { + searchSeq++; + results = []; + resultsSection.hidden = true; + render(); + return; + } + timer = setTimeout(() => { + lastSort = undefined; + void search(query.trim(), 0); + }, SEARCH_DELAY_MS); + }); + searchField.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + clearTimeout(timer); + lastSort = undefined; + void search(query.trim(), 0); + } + }); + more.addEventListener('click', () => void search(lastSort ? '' : query.trim(), results.length, lastSort)); + popular.addEventListener('click', () => { + lastSort = 'downloadCount'; + void search('', 0, 'downloadCount'); + }); + + // --- The details page, over the editor area. + let details: HTMLElement | null = null; + let detailsId: ExtensionId | null = null; + let detailsGallery: GalleryExtension | undefined; + const closeDetails = (): void => { + details?.remove(); + details = null; + detailsId = null; + }; + + function showDetails(id: ExtensionId, gallery?: GalleryExtension): void { + detailsId = id; + detailsGallery = gallery; + if (!details) { + details = el('section', { className: 'extension-details', attrs: { 'aria-label': 'Extension details', 'data-testid': 'extension-details', tabindex: '-1' } }); + details.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + closeDetails(); + } + }); + hooks.detailsHost.append(details); + } + details.replaceChildren(el('p', { className: 'muted extension-details-loading', text: 'Loading…' })); + details.focus(); + void fillDetails(id, gallery); + } + + async function fillDetails(id: ExtensionId, gallery?: GalleryExtension): Promise { + const local = installedOf(id); + let installedDetails: InstalledDetails | null = null; + let remote: GalleryDetails | null = null; + let remoteError: string | null = null; + if (local) { + installedDetails = await api.details(id).catch(() => null); + } else { + try { + remote = await api.galleryDetails(id); + } catch (error) { + remoteError = errorText(error); + } + } + if (!details || detailsId !== id) { + return; + } + const extension = installedDetails?.extension; + const name = extension?.displayName ?? remote?.displayName ?? gallery?.displayName ?? id; + const head = el('header', { className: 'extension-details-head' }); + const img = iconElement(extension?.icon ?? null); + img.classList.add('is-large'); + if (!extension) { + galleryIcon(remote?.iconUrl ?? gallery?.iconUrl ?? null, img); + } + const facts: [string, string][] = []; + const publisher = extension?.publisher ?? remote?.publisherDisplayName ?? gallery?.namespace ?? ''; + facts.push(['Identifier', id]); + facts.push(['Version', extension?.version ?? remote?.version ?? gallery?.version ?? '']); + const license = extension?.license ?? remote?.license; + if (license) { + facts.push(['Licence', license]); + } + if (remote) { + facts.push(['Downloads', remote.downloadCount.toLocaleString()]); + } + const engine = extension?.engine ?? remote?.engine; + if (engine) { + facts.push(['VS Code API', engine]); + } + if (extension) { + facts.push(['Source', extension.source === 'open-vsx' ? 'Open VSX' : '.vsix file']); + facts.push(['State', installedStateLabel(extension)]); + } + const actions: HTMLElement[] = []; + if (extension) { + actions.push(actionButton(extension.state === 'disabled' ? 'Enable' : 'Disable', 'extension-details-toggle', () => void toggle(extension))); + actions.push(actionButton('Uninstall', 'extension-details-uninstall', () => void uninstall(extension))); + } else if (remote || gallery) { + actions.push(actionButton(busy.has(id) ? 'Installing…' : 'Install', 'extension-details-install', () => void runInstall(id), true)); + } + const repository = extension?.repository ?? remote?.repository ?? remote?.homepage ?? null; + if (repository) { + actions.push(actionButton('Repository', 'extension-details-repository', () => hooks.openExternalLink(repository))); + } + const publisherLine = el('p', { className: 'extension-details-publisher' }, [document.createTextNode(publisher)]); + if (remote?.verified ?? gallery?.verified) { + publisherLine.append(el('span', { className: 'extension-verified', attrs: { title: 'Verified publisher' } }, [icon(ICONS.verified)]), document.createTextNode(' verified')); + } + const closeButton = iconButton('Close', ICONS.close, 'extension-details-close', closeDetails); + head.append(img, el('div', { className: 'extension-details-title' }, [ + el('h2', { text: name }), + publisherLine, + el('p', { className: 'extension-details-description', text: extension?.description ?? remote?.description ?? gallery?.description ?? '' }), + el('div', { className: 'extension-details-actions' }, actions), + ]), closeButton); + const factList = el('dl', { className: 'extension-details-facts' }, facts.flatMap(([term, value]) => [el('dt', { text: term }), el('dd', { text: value })])); + const body = el('div', { className: 'extension-details-body' }); + const side = el('aside', { className: 'extension-details-side' }, [factList]); + if (extension) { + side.append(contributionsList(extension)); + if (extension.activationError) { + side.append(el('p', { className: 'error', text: `Activation failed: ${extension.activationError}` })); + } + } + const readme = installedDetails?.readme ?? remote?.readme ?? null; + const readmeHost = el('article', { className: 'extension-details-readme', attrs: { 'data-testid': 'extension-details-readme' } }); + if (remoteError) { + readmeHost.append(el('p', { className: 'error', text: `The registry could not be reached: ${remoteError}` })); + } else if (readme) { + void hooks.renderMarkdown(readme, readmeHost).catch((error: unknown) => readmeHost.append(el('p', { className: 'error', text: `The README could not be shown: ${String(error)}` }))); + } else { + readmeHost.append(el('p', { className: 'muted', text: 'This extension has no README.' })); + } + body.append(readmeHost, side); + details.replaceChildren(head, body); + } + + function contributionsList(extension: InstalledExtension): HTMLElement { + const c = extension.contributes; + const items: [string, string][] = []; + const names = (values: readonly string[]): string => values.slice(0, 12).join(', ') + (values.length > 12 ? ` and ${values.length - 12} more` : ''); + if (c.themes.length) { items.push(['Colour themes', names(c.themes)]); } + if (c.iconThemes.length) { items.push(['Icon themes (not supported yet)', names(c.iconThemes)]); } + if (c.languages.length) { items.push(['Languages', names(c.languages)]); } + if (c.grammars) { items.push(['Grammars', String(c.grammars)]); } + if (c.snippets) { items.push(['Snippet files', String(c.snippets)]); } + if (c.commands.length) { items.push(['Commands', names(c.commands)]); } + if (c.views.length) { items.push(['Views', names(c.views)]); } + if (c.settings) { items.push(['Settings', String(c.settings)]); } + if (c.keybindings) { items.push(['Keybindings', String(c.keybindings)]); } + if (c.localizations.length) { items.push(['Language packs (VS Code UI only)', names(c.localizations)]); } + return el('section', { className: 'extension-details-contributions' }, [ + el('h3', { text: 'Contributes' }), + items.length ? el('dl', { className: 'extension-details-facts' }, items.flatMap(([term, value]) => [el('dt', { text: term }), el('dd', { text: value })])) : el('p', { className: 'muted', text: 'Nothing declarative.' }), + el('p', { className: 'muted', text: extension.hasCode ? `Runs code (${extension.activation === 'active' ? 'active' : extension.activation === 'failed' ? 'failed to activate' : 'activates when needed'}).` : 'Runs no code.' }), + ]); + } + + const view: ExtensionsView = { + focusSearch(text?: string): void { + if (text !== undefined) { + searchField.value = text; + searchField.dispatchEvent(new Event('input')); + } + searchField.focus(); + }, + setInstalled(list: readonly InstalledExtension[]): void { + installed = list; + render(); + if (details && detailsId) { + void fillDetails(detailsId, detailsGallery); + } + }, + showDetails(id: ExtensionId): void { + showDetails(id); + }, + async installVsix(): Promise { + hooks.onStatus('Choose a .vsix file…'); + let result: InstallResult; + try { + result = await api.installVsix(); + } catch (error) { + result = { ok: false, error: String(error) }; + } + finishInstall(result); + }, + }; + void refreshInstalled(); + return view; +} + +function errorText(error: unknown): string { + const text = error instanceof Error ? error.message : String(error); + // Electron prefixes errors that cross IPC with the channel name. + return text.replace(/^Error invoking remote method '[^']+': (Error: )?/, ''); +} diff --git a/apps/ide/src/renderer/extensions/extensionsWiring.ts b/apps/ide/src/renderer/extensions/extensionsWiring.ts new file mode 100644 index 000000000..616be5033 --- /dev/null +++ b/apps/ide/src/renderer/extensions/extensionsWiring.ts @@ -0,0 +1,87 @@ +import type { CodeXRApi } from '../../shared/api.ts'; +import type { ContributedTheme, InstalledExtension } from '../../shared/extensions.ts'; +import type { CommandRegistry } from '../commands/commandRegistry.ts'; +import { createContributionsController, type ContributionsController } from './contributionsController.ts'; +import { createExtensionsView, type ExtensionsView } from './extensionsView.ts'; +import './extensions.css'; + +/** + * Wires the extensions (#251) into the workbench, so main.ts only calls + * `installExtensions` and asks for the themes: the Extensions view, the + * declarative contributions, and the palette commands. + */ + +export interface ExtensionsWorkbench { + readonly view: ExtensionsView; + readonly contributions: ContributionsController; + /** The colour themes of the enabled extensions, for the theme picker. */ + themes(): readonly ContributedTheme[]; +} + +export interface ExtensionsWorkbenchDeps { + readonly api: CodeXRApi; + readonly registry: CommandRegistry; + readonly viewContainer: HTMLElement; + readonly detailsHost: HTMLElement; + showView(): void; + onStatus(message: string): void; + notify(kind: 'info' | 'warning' | 'error', message: string): void; + /** Opens the colour theme picker (after installing a theme). */ + selectColorTheme(): void; +} + +export function installExtensions(deps: ExtensionsWorkbenchDeps): ExtensionsWorkbench { + const { api } = deps; + const contributions = createContributionsController(api.extensions, (message) => deps.notify('warning', message)); + const view = createExtensionsView(deps.viewContainer, api.extensions, { + onStatus: deps.onStatus, + notify: deps.notify, + openExternalLink: (url) => void api.workspace.openExternalLink(url).catch((error: unknown) => deps.notify('error', String(error))), + detailsHost: deps.detailsHost, + async renderMarkdown(text, container) { + const { createMarkdownPreview } = await import('../editor/markdownPreview.ts'); + const preview = createMarkdownPreview({ + readImage: async () => null, + openExternalLink: (url) => api.workspace.openExternalLink(url), + openFile: () => undefined, + onStatus: deps.onStatus, + onClose: () => undefined, + }); + container.replaceChildren(preview.element); + preview.show('README.md', text); + }, + afterInstall(extension: InstalledExtension) { + if (extension.contributes.themes.length > 0 && extension.state === 'enabled') { + deps.notify('info', `${extension.displayName} adds colour themes: pick one with Preferences: Color Theme (Ctrl+K Ctrl+T).`); + } + }, + }); + + api.extensions.onDidChange((event) => { + view.setInstalled(event.installed); + void contributions.reload(); + }); + void contributions.reload(); + + const commands = [ + { id: 'extensions.showView', category: 'Extensions', title: 'Show Extensions', keybinding: 'CmdOrCtrl+Shift+X', run: () => { deps.showView(); view.focusSearch(); } }, + { id: 'extensions.installVsix', category: 'Extensions', title: 'Install from VSIX…', run: () => { deps.showView(); void view.installVsix(); } }, + { id: 'extensions.showInstalled', category: 'Extensions', title: 'Show Installed Extensions', run: () => { deps.showView(); view.focusSearch(''); } }, + { id: 'extensions.searchThemes', category: 'Extensions', title: 'Browse Colour Themes in Open VSX', run: () => { deps.showView(); view.focusSearch('theme'); } }, + { + id: 'extensions.disableAll', + category: 'Extensions', + title: 'Disable All Installed Extensions', + run: () => void api.extensions.disableAll().then(() => deps.notify('info', 'Every extension was disabled. Enable them again one by one in the Extensions view.')), + }, + ]; + for (const command of commands) { + deps.registry.register(command); + } + + return { + view, + contributions, + themes: () => contributions.current().themes, + }; +} diff --git a/apps/ide/src/renderer/extensions/languageModel.ts b/apps/ide/src/renderer/extensions/languageModel.ts new file mode 100644 index 000000000..eb079b74d --- /dev/null +++ b/apps/ide/src/renderer/extensions/languageModel.ts @@ -0,0 +1,203 @@ +import type { ContributedLanguage, ContributedSnippet } from '../../shared/extensions.ts'; + +/** + * Languages contributed by extensions (#258), as Monaco takes them: the + * language entry, its `language-configuration.json` with VS Code's string + * patterns turned into RegExps, and snippets. Pure (Monaco's IndentAction + * values are passed in), unit-tested in Node. + */ + +export interface MonacoLanguageEntry { + id: string; + extensions?: string[]; + filenames?: string[]; + filenamePatterns?: string[]; + firstLine?: string; + aliases?: string[]; + mimetypes?: string[]; +} + +/** Merges the entries several extensions contribute for one language id. */ +export function mergeLanguages(languages: readonly ContributedLanguage[]): { entry: MonacoLanguageEntry; configuration: unknown }[] { + const byId = new Map> & { firstLine?: string }; configuration: unknown }>(); + for (const language of languages) { + const current = byId.get(language.id) ?? { entry: { id: language.id, extensions: [], filenames: [], filenamePatterns: [], aliases: [], mimetypes: [] }, configuration: null }; + const add = (target: string[], values: readonly string[]): void => { + for (const value of values) { + if (!target.includes(value)) { + target.push(value); + } + } + }; + add(current.entry.extensions, language.extensions); + add(current.entry.filenames, language.filenames); + add(current.entry.filenamePatterns, language.filenamePatterns); + add(current.entry.aliases, language.aliases); + add(current.entry.mimetypes, language.mimetypes); + if (language.firstLine && current.entry.firstLine === undefined && safeRegExp(language.firstLine)) { + current.entry.firstLine = language.firstLine; + } + if (current.configuration === null && language.configuration !== null) { + current.configuration = language.configuration; + } + byId.set(language.id, current); + } + return [...byId.values()]; +} + +function record(value: unknown): Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record : {}; +} + +/** A RegExp from VS Code's `"pattern"` or `{ "pattern", "flags" }`, or null when it does not compile. */ +export function safeRegExp(value: unknown): RegExp | null { + let pattern: unknown = value; + let flags = ''; + if (typeof value === 'object' && value !== null) { + pattern = record(value).pattern; + flags = typeof record(value).flags === 'string' ? String(record(value).flags) : ''; + } + if (typeof pattern !== 'string' || pattern.length > 10_000) { + return null; + } + try { + return new RegExp(pattern, flags.replace(/[^gimsuy]/g, '')); + } catch { + return null; + } +} + +function pair(value: unknown): [string, string] | null { + return Array.isArray(value) && value.length === 2 && typeof value[0] === 'string' && typeof value[1] === 'string' ? [value[0], value[1]] : null; +} + +/** Monaco's `IndentAction` values, passed in so this module needs no Monaco. */ +export interface IndentActions { + None: number; + Indent: number; + IndentOutdent: number; + Outdent: number; +} + +/** `language-configuration.json` as a Monaco `LanguageConfiguration` (unknown or invalid parts left out). */ +export function toLanguageConfiguration(raw: unknown, indent: IndentActions): Record { + const config = record(raw); + const out: Record = {}; + const comments = record(config.comments); + const lineComment = typeof comments.lineComment === 'string' ? comments.lineComment : undefined; + const blockComment = pair(comments.blockComment); + if (lineComment || blockComment) { + out.comments = { ...(lineComment ? { lineComment } : {}), ...(blockComment ? { blockComment } : {}) }; + } + if (Array.isArray(config.brackets)) { + out.brackets = config.brackets.map(pair).filter((p): p is [string, string] => p !== null); + } + const pairs = (value: unknown): { open: string; close: string; notIn?: string[] }[] => (Array.isArray(value) ? value : []).flatMap((item) => { + const asPair = pair(item); + if (asPair) { + return [{ open: asPair[0], close: asPair[1] }]; + } + const r = record(item); + if (typeof r.open === 'string' && typeof r.close === 'string') { + const notIn = Array.isArray(r.notIn) ? r.notIn.filter((n): n is string => typeof n === 'string') : []; + return [{ open: r.open, close: r.close, ...(notIn.length ? { notIn } : {}) }]; + } + return []; + }); + if (config.autoClosingPairs !== undefined) { + out.autoClosingPairs = pairs(config.autoClosingPairs); + } + if (config.surroundingPairs !== undefined) { + out.surroundingPairs = pairs(config.surroundingPairs).map(({ open, close }) => ({ open, close })); + } + if (typeof config.autoCloseBefore === 'string') { + out.autoCloseBefore = config.autoCloseBefore; + } + const wordPattern = safeRegExp(config.wordPattern); + if (wordPattern) { + out.wordPattern = wordPattern; + } + const folding = record(config.folding); + const markers = record(folding.markers); + const start = safeRegExp(markers.start); + const end = safeRegExp(markers.end); + if (start && end || typeof folding.offSide === 'boolean') { + out.folding = { ...(typeof folding.offSide === 'boolean' ? { offSide: folding.offSide } : {}), ...(start && end ? { markers: { start, end } } : {}) }; + } + const rules = record(config.indentationRules); + const increase = safeRegExp(rules.increaseIndentPattern); + const decrease = safeRegExp(rules.decreaseIndentPattern); + if (increase && decrease) { + const next = safeRegExp(rules.indentNextLinePattern); + const unindented = safeRegExp(rules.unIndentedLinePattern); + out.indentationRules = { + increaseIndentPattern: increase, + decreaseIndentPattern: decrease, + ...(next ? { indentNextLinePattern: next } : {}), + ...(unindented ? { unIndentedLinePattern: unindented } : {}), + }; + } + if (Array.isArray(config.onEnterRules)) { + const actions: Record = { none: indent.None, indent: indent.Indent, indentOutdent: indent.IndentOutdent, outdent: indent.Outdent }; + out.onEnterRules = config.onEnterRules.flatMap((item) => { + const rule = record(item); + const beforeText = safeRegExp(rule.beforeText); + const action = record(rule.action); + const indentAction = typeof action.indent === 'string' ? actions[action.indent] : undefined; + if (!beforeText || indentAction === undefined) { + return []; + } + const afterText = safeRegExp(rule.afterText); + const previousLineText = safeRegExp(rule.previousLineText); + return [{ + beforeText, + ...(afterText ? { afterText } : {}), + ...(previousLineText ? { previousLineText } : {}), + action: { + indentAction, + ...(typeof action.appendText === 'string' ? { appendText: action.appendText } : {}), + ...(typeof action.removeText === 'number' ? { removeText: action.removeText } : {}), + }, + }]; + }); + } + return out; +} + +/** The language a file name belongs to among contributed entries: exact name, then the longest extension, then patterns. */ +export function detectLanguage(fileName: string, entries: readonly MonacoLanguageEntry[]): string | null { + const lower = fileName.toLowerCase(); + for (const entry of entries) { + if (entry.filenames?.some((name) => name.toLowerCase() === lower)) { + return entry.id; + } + } + let best: { id: string; length: number } | null = null; + for (const entry of entries) { + for (const ext of entry.extensions ?? []) { + if (lower.endsWith(ext.toLowerCase()) && (!best || ext.length > best.length)) { + best = { id: entry.id, length: ext.length }; + } + } + } + if (best) { + return best.id; + } + for (const entry of entries) { + if (entry.filenamePatterns?.some((pattern) => globToRegExp(pattern).test(lower))) { + return entry.id; + } + } + return null; +} + +function globToRegExp(glob: string): RegExp { + const name = glob.toLowerCase().split('/').pop() ?? ''; + const source = name.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.'); + return new RegExp(`^${source}$`); +} + +/** The snippets of one language (and the `*` ones that apply to all). */ +export function snippetsFor(snippets: readonly ContributedSnippet[], languageId: string): ContributedSnippet[] { + return snippets.filter((snippet) => snippet.language === languageId || snippet.language === '*'); +} diff --git a/apps/ide/src/renderer/extensions/monacoContributions.ts b/apps/ide/src/renderer/extensions/monacoContributions.ts new file mode 100644 index 000000000..c2414d6c1 --- /dev/null +++ b/apps/ide/src/renderer/extensions/monacoContributions.ts @@ -0,0 +1,100 @@ +import type { ExtensionContributions, ExtensionsApi, ResolvedTheme } from '../../shared/extensions.ts'; +import { monaco, setThemeOverride } from '../editor/monaco.ts'; +import { detectLanguage, mergeLanguages, snippetsFor, toLanguageConfiguration, type MonacoLanguageEntry } from './languageModel.ts'; +import { TextMateGrammars } from './textmate.ts'; +import { toMonacoTheme } from './themeModel.ts'; + +/** + * The Monaco half of the declarative contributions (#257, #258): languages, + * language configurations, TextMate grammars, snippets and the editor side of + * a colour theme. Loaded only when an enabled extension contributes one of + * them, so an IDE without extensions does not load Monaco earlier than before. + * + * Monaco cannot unregister a language: one whose extension is removed keeps + * its file associations until the window reloads (its grammar, configuration + * and snippets go at once). + */ + +const registeredLanguages = new Set(); +let disposables: monaco.IDisposable[] = []; +let grammars: TextMateGrammars | null = null; +let themeCounter = 0; + +export function applyContributions(contributions: ExtensionContributions, api: Pick, onError: (message: string) => void): void { + for (const disposable of disposables) { + disposable.dispose(); + } + disposables = []; + grammars?.dispose(); + grammars = null; + + const merged = mergeLanguages(contributions.languages); + const known = new Set(monaco.languages.getLanguages().map((language) => language.id)); + for (const { entry, configuration } of merged) { + if (!registeredLanguages.has(entry.id)) { + // A language Monaco already knows (an extension adding `.mjs` to javascript) keeps its own entry and gains the new names. + monaco.languages.register(entry); + registeredLanguages.add(entry.id); + } + if (configuration !== null && !known.has(entry.id)) { + try { + disposables.push(monaco.languages.setLanguageConfiguration(entry.id, toLanguageConfiguration(configuration, monaco.languages.IndentAction) as monaco.languages.LanguageConfiguration)); + } catch (error) { + onError(`The language configuration of ${entry.id} could not be applied: ${String(error)}`); + } + } + } + + grammars = new TextMateGrammars(contributions.grammars, (ref) => api.grammarContent(ref), onError); + grammars.attach(); + + const snippetLanguages = new Set(contributions.snippets.map((snippet) => snippet.language)); + for (const language of snippetLanguages) { + const selector = language === '*' ? '*' : language; + disposables.push(monaco.languages.registerCompletionItemProvider(selector, { + provideCompletionItems(model, position) { + const word = model.getWordUntilPosition(position); + const range = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn); + const list = language === '*' ? contributions.snippets.filter((s) => s.language === '*') : snippetsFor(contributions.snippets, model.getLanguageId()).filter((s) => s.language !== '*'); + return { + suggestions: list.flatMap((snippet) => snippet.prefixes.map((prefix) => ({ + label: { label: prefix, description: snippet.name }, + kind: monaco.languages.CompletionItemKind.Snippet, + insertText: snippet.body, + insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, + documentation: snippet.description ? `${snippet.description}\n\n${snippet.body}` : snippet.body, + detail: `Snippet from ${snippet.extensionId}`, + range, + }))), + }; + }, + })); + } + + reassignPlainTextModels(merged.map((m) => m.entry)); +} + +/** Files opened before their language was registered were opened as plain text: give them their language now. */ +function reassignPlainTextModels(entries: readonly MonacoLanguageEntry[]): void { + for (const model of monaco.editor.getModels()) { + if (model.getLanguageId() !== 'plaintext') { + continue; + } + const name = model.uri.path.split('/').pop() ?? ''; + const language = detectLanguage(name, entries); + if (language) { + monaco.editor.setModelLanguage(model, language); + } + } +} + +/** The editor side of a colour theme; null goes back to following the OS. */ +export function applyEditorTheme(theme: ResolvedTheme | null): void { + if (!theme) { + setThemeOverride(null); + return; + } + const name = `codexr-ext-${++themeCounter}`; + monaco.editor.defineTheme(name, toMonacoTheme(theme) as monaco.editor.IStandaloneThemeData); + setThemeOverride(name); +} diff --git a/apps/ide/src/renderer/extensions/textmate.ts b/apps/ide/src/renderer/extensions/textmate.ts new file mode 100644 index 000000000..aafd660be --- /dev/null +++ b/apps/ide/src/renderer/extensions/textmate.ts @@ -0,0 +1,156 @@ +import { INITIAL, parseRawGrammar, Registry, type IGrammar, type StateStack } from 'vscode-textmate'; +import { loadWASM, OnigScanner, OnigString } from 'vscode-oniguruma'; +import onigWasmUrl from 'vscode-oniguruma/release/onig.wasm?url'; +import type { ContributedGrammar, GrammarContent } from '../../shared/extensions.ts'; +import { monaco } from '../editor/monaco.ts'; + +/** + * TextMate grammars contributed by extensions (#258), tokenized with the + * libraries VS Code itself uses: `vscode-textmate` and the Oniguruma regex + * engine compiled to WebAssembly (`vscode-oniguruma`), bundled with the app + * and fetched from its own origin. Compiling WebAssembly is the one thing + * the CSP gained for this (`'wasm-unsafe-eval'`); `eval` stays blocked. + * + * Each token handed to Monaco carries its innermost scope + * (`keyword.control.ts`), which Monaco's theme matches by prefix, so a + * theme's `keyword.control` rule colours it. + */ + +/** A line longer than this is not tokenized (as in VS Code), so a minified file cannot freeze the editor. */ +const MAX_LINE = 20_000; +/** Milliseconds one line may take before the tokenizer gives up on it. */ +const TIME_LIMIT_MS = 500; + +class TextMateState implements monaco.languages.IState { + readonly stack: StateStack; + + constructor(stack: StateStack) { + this.stack = stack; + } + + clone(): TextMateState { + return new TextMateState(this.stack); + } + + equals(other: monaco.languages.IState): boolean { + return other instanceof TextMateState && other.stack.equals(this.stack); + } +} + +export type GrammarLoader = (ref: string) => Promise; + +let onigLib: Promise<{ createOnigScanner(patterns: string[]): OnigScanner; createOnigString(text: string): OnigString }> | null = null; + +function oniguruma(): NonNullable { + onigLib ??= fetch(onigWasmUrl) + .then((response) => response.arrayBuffer()) + .then((bytes) => loadWASM(bytes)) + .then(() => ({ + createOnigScanner: (patterns: string[]) => new OnigScanner(patterns), + createOnigString: (text: string) => new OnigString(text), + })); + return onigLib; +} + +export class TextMateGrammars { + private readonly byScope = new Map(); + private readonly injections = new Map(); + private readonly registry: Registry; + private readonly languageIds = new Map(); + private readonly registered = new Set(); + private readonly disposables: monaco.IDisposable[] = []; + private readonly onError: (message: string) => void; + + constructor(grammars: readonly ContributedGrammar[], load: GrammarLoader, onError: (message: string) => void) { + this.onError = onError; + for (const grammar of grammars) { + this.byScope.set(grammar.scopeName, grammar); + for (const target of grammar.injectTo) { + this.injections.set(target, [...(this.injections.get(target) ?? []), grammar.scopeName]); + } + } + this.registry = new Registry({ + onigLib: oniguruma(), + loadGrammar: async (scopeName) => { + const grammar = this.byScope.get(scopeName); + if (!grammar) { + return null; + } + const content = await load(grammar.ref); + if (!content) { + return null; + } + return parseRawGrammar(content.content, content.format === 'json' ? 'grammar.json' : 'grammar.tmLanguage'); + }, + getInjections: (scopeName) => this.injections.get(scopeName), + }); + } + + private languageNumber(languageId: string): number { + let id = this.languageIds.get(languageId); + if (id === undefined) { + id = this.languageIds.size + 1; + this.languageIds.set(languageId, id); + } + return id; + } + + /** Puts every language that has a grammar on TextMate, loading the grammar when Monaco first needs it. */ + attach(): void { + for (const grammar of this.byScope.values()) { + const languageId = grammar.language; + if (!languageId || this.registered.has(languageId)) { + continue; + } + this.registered.add(languageId); + const embedded: Record = {}; + for (const [scope, language] of Object.entries(grammar.embeddedLanguages)) { + embedded[scope] = this.languageNumber(language); + } + let started = false; + const start = (): void => { + if (started) { + return; + } + started = true; + this.registry + .loadGrammarWithConfiguration(grammar.scopeName, this.languageNumber(languageId), { embeddedLanguages: embedded }) + .then((loaded) => { + if (!loaded) { + throw new Error(`grammar ${grammar.scopeName} did not load`); + } + this.disposables.push(monaco.languages.setTokensProvider(languageId, tokensProvider(loaded))); + }) + .catch((error: unknown) => this.onError(`${grammar.extensionId}: the ${languageId} grammar could not be loaded (${String(error)}).`)); + }; + // Loaded when Monaco first meets the language, or now if a file of it is already open. + this.disposables.push(monaco.languages.onLanguage(languageId, start)); + if (monaco.editor.getModels().some((model) => model.getLanguageId() === languageId)) { + start(); + } + } + } + + dispose(): void { + for (const disposable of this.disposables.splice(0)) { + disposable.dispose(); + } + } +} + +function tokensProvider(grammar: IGrammar): monaco.languages.TokensProvider { + return { + getInitialState: () => new TextMateState(INITIAL), + tokenize(line: string, state: monaco.languages.IState): monaco.languages.ILineTokens { + const stack = (state as TextMateState).stack; + if (line.length > MAX_LINE) { + return { tokens: [{ startIndex: 0, scopes: '' }], endState: state }; + } + const result = grammar.tokenizeLine(line, stack, TIME_LIMIT_MS); + return { + endState: new TextMateState(result.ruleStack), + tokens: result.tokens.map((token) => ({ startIndex: token.startIndex, scopes: token.scopes[token.scopes.length - 1] ?? '' })), + }; + }, + }; +} diff --git a/apps/ide/src/renderer/extensions/themeModel.ts b/apps/ide/src/renderer/extensions/themeModel.ts new file mode 100644 index 000000000..b09612afd --- /dev/null +++ b/apps/ide/src/renderer/extensions/themeModel.ts @@ -0,0 +1,172 @@ +import type { ResolvedTheme } from '../../shared/extensions.ts'; + +/** + * A VS Code colour theme turned into what the workbench uses (#257): a Monaco + * theme (token rules and editor colours) and the workbench's own colour + * tokens (`--editor`, `--panel`, ...), plus every theme colour as a + * `--vscode-*` variable for extension webviews (#261). Pure, unit-tested. + */ + +export interface MonacoThemeData { + readonly base: 'vs' | 'vs-dark' | 'hc-black' | 'hc-light'; + readonly inherit: boolean; + readonly rules: { token: string; foreground?: string; background?: string; fontStyle?: string }[]; + readonly colors: Record; +} + +const HEX = /^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i; + +/** `#abc` -> `#aabbcc`, `#abcd` -> `#aabbccdd`; null for anything that is not a hex colour. */ +export function normalizeHex(value: unknown): string | null { + if (typeof value !== 'string' || !HEX.test(value.trim())) { + return null; + } + const hex = value.trim().slice(1).toLowerCase(); + return `#${hex.length <= 4 ? [...hex].map((c) => c + c).join('') : hex}`; +} + +/** + * Monarch token names (Monaco's built-in tokenizers) that a TextMate scope + * stands for, so a theme written for TextMate also colours the languages + * Monaco tokenizes itself. + */ +const MONARCH_ALIASES: readonly [string, readonly string[]][] = [ + ['comment', ['comment']], + ['string.regexp', ['regexp']], + ['string', ['string']], + ['constant.numeric', ['number']], + ['constant.language', ['keyword']], + ['constant', ['constant']], + ['keyword.operator', ['operator', 'delimiter']], + ['keyword', ['keyword']], + ['storage.type', ['keyword']], + ['storage', ['keyword']], + ['entity.name.type', ['type', 'type.identifier']], + ['entity.name.class', ['type', 'type.identifier']], + ['support.type', ['type']], + ['entity.name.function', ['function']], + ['support.function', ['function']], + ['entity.name.tag', ['tag']], + ['entity.other.attribute-name', ['attribute.name']], + ['variable.parameter', ['variable']], + ['variable', ['variable', 'identifier']], + ['punctuation', ['delimiter']], + ['meta.annotation', ['annotation']], + ['markup.heading', ['keyword.md']], + ['invalid', ['invalid']], +]; + +function monarchFor(scope: string): readonly string[] { + for (const [prefix, tokens] of MONARCH_ALIASES) { + if (scope === prefix || scope.startsWith(`${prefix}.`)) { + return tokens; + } + } + return []; +} + +/** The scope a rule applies to, as Monaco matches tokens: the last part of a descendant selector. */ +export function ruleToken(selector: string): string | null { + const trimmed = selector.trim(); + if (trimmed === '' || trimmed.startsWith('-') || trimmed.includes('|')) { + return null; + } + const parts = trimmed.split(/\s+/); + const last = parts[parts.length - 1] ?? ''; + return /^[A-Za-z0-9_.-]+$/.test(last) ? last : null; +} + +function strip(hex: string): string { + return hex.slice(1); +} + +export function toMonacoTheme(theme: ResolvedTheme): MonacoThemeData { + const rules: MonacoThemeData['rules'] = []; + const foreground = normalizeHex(theme.colors['editor.foreground']) ?? normalizeHex(theme.colors.foreground); + const background = normalizeHex(theme.colors['editor.background']); + // The empty token is the default text: without it Monaco keeps the base theme's. + if (foreground || background) { + rules.push({ token: '', ...(foreground ? { foreground: strip(foreground) } : {}), ...(background ? { background: strip(background) } : {}) }); + } + // For each Monarch alias, the most general scope wins (`keyword` over `keyword.control.import`); on a tie, the later rule. + const monarch = new Map(); + for (const rule of theme.tokenColors) { + const fg = normalizeHex(rule.foreground); + const bg = normalizeHex(rule.background); + const style = typeof rule.fontStyle === 'string' ? rule.fontStyle.trim() : undefined; + const settings = { + ...(fg ? { foreground: strip(fg) } : {}), + ...(bg ? { background: strip(bg) } : {}), + ...(style !== undefined ? { fontStyle: style } : {}), + }; + if (Object.keys(settings).length === 0) { + continue; + } + for (const selector of rule.scope) { + const token = ruleToken(selector); + if (!token) { + continue; + } + rules.push({ token, ...settings }); + const depth = token.split('.').length; + for (const alias of monarchFor(token)) { + const existing = monarch.get(alias); + if (!existing || depth <= existing.depth) { + monarch.set(alias, { depth, rule: { token: alias, ...settings } }); + } + } + } + } + // Monarch aliases first: an exact TextMate rule of the same name, later in the list, overrides it. + const colors: Record = {}; + for (const [key, value] of Object.entries(theme.colors)) { + const hex = normalizeHex(value); + if (hex) { + colors[key] = hex; + } + } + return { base: theme.uiTheme, inherit: true, rules: [...[...monarch.values()].map((entry) => entry.rule), ...rules], colors }; +} + +/** The workbench token and the theme colours it comes from, first found wins. */ +const WORKBENCH_TOKENS: readonly [string, readonly string[]][] = [ + ['--editor', ['editor.background']], + ['--panel', ['sideBar.background', 'panel.background', 'editor.background']], + ['--chrome', ['activityBar.background', 'titleBar.activeBackground', 'sideBar.background', 'editorGroupHeader.tabsBackground']], + ['--line', ['sideBar.border', 'panel.border', 'editorGroup.border', 'tab.border', 'contrastBorder', 'widget.border']], + ['--hover', ['list.hoverBackground', 'toolbar.hoverBackground', 'list.inactiveSelectionBackground']], + ['--fg', ['foreground', 'sideBar.foreground', 'editor.foreground']], + ['--muted', ['descriptionForeground', 'tab.inactiveForeground', 'editorLineNumber.foreground']], + ['--accent', ['focusBorder', 'button.background', 'activityBarBadge.background', 'textLink.foreground']], + ['--crit', ['errorForeground', 'editorError.foreground']], + ['--warn', ['editorWarning.foreground', 'list.warningForeground']], + ['--status', ['statusBar.background']], + ['--status-fg', ['statusBar.foreground']], + ['--symbol', ['symbolIcon.functionForeground', 'symbolIcon.methodForeground']], +]; + +/** The CSS custom properties to set on the root element for a theme. */ +export function workbenchVariables(theme: ResolvedTheme): Record { + const vars: Record = {}; + for (const [token, keys] of WORKBENCH_TOKENS) { + for (const key of keys) { + const hex = normalizeHex(theme.colors[key]); + if (hex) { + vars[token] = hex; + break; + } + } + } + for (const [key, value] of Object.entries(theme.colors)) { + const hex = normalizeHex(value); + if (hex && /^[A-Za-z0-9.]+$/.test(key)) { + vars[`--vscode-${key.replace(/\./g, '-')}`] = hex; + } + } + return vars; +} + +/** Whether a theme is dark (`vs-dark`, `hc-black`), for the OS colour scheme the pages see. */ +export function isDarkTheme(uiTheme: ResolvedTheme['uiTheme']): boolean { + return uiTheme === 'vs-dark' || uiTheme === 'hc-black'; +} diff --git a/apps/ide/src/renderer/main.ts b/apps/ide/src/renderer/main.ts index 3904e4ec2..12f24d531 100644 --- a/apps/ide/src/renderer/main.ts +++ b/apps/ide/src/renderer/main.ts @@ -39,6 +39,9 @@ import { menuAccelerators } from './settings/keybindingsModel.ts'; import { COLOR_THEME_SETTING, isColorTheme, settingOf, type ColorTheme } from '../shared/settings.ts'; import { themeChoices } from './settings/settingsModel.ts'; import { isMarkdownPath } from './editor/markdownPath.ts'; +import { installExtensions } from './extensions/extensionsWiring.ts'; +import type { ContributedTheme } from '../shared/extensions.ts'; +const EXTENSION_THEME_SETTING = 'workbench.colorThemeExtension'; import type { IdeCommand, KeybindingsReport, PythonEnvStatus, SettingsReport, WatchedEntry } from '../shared/api.ts'; const root = document.getElementById('app'); @@ -426,7 +429,14 @@ function applySettings(report: SettingsReport): void { outlineView.setSort(settingOf(report, 'outline.sortBy') === 'name' ? 'name' : 'position'); outline?.setBreadcrumbsEnabled(settingOf(report, 'breadcrumbs.enabled')); refreshMetricProblems(); + // #257: a colour theme of an extension, over the light/dark base the Color Theme setting picks. + const extensionTheme = settingOf(report, EXTENSION_THEME_SETTING); + if (extensionTheme !== appliedExtensionTheme) { + appliedExtensionTheme = extensionTheme; + void extensions.contributions.setTheme(extensionTheme); + } } +let appliedExtensionTheme = ''; function loadSettings(): Promise { return api.settings.get().then(applySettings, (error: unknown) => workbench.setStatus(`Could not read the settings: ${String(error)}`)); } @@ -542,19 +552,30 @@ function pick(label: string, choices: readonly Choice[], apply: (value: T) * Enter stores it in the user's settings, Escape goes back to the stored one. */ function selectColorTheme(): void { - const current = settingsReport ? settingOf(settingsReport, COLOR_THEME_SETTING) : 'system'; - const choices = themeChoices(isColorTheme(current) ? current : 'system'); - const items: PickItem[] = choices.map(({ id, label, description }) => ({ id, label, ...(description ? { description } : {}) })); + const base = settingsReport ? settingOf(settingsReport, COLOR_THEME_SETTING) : 'system'; + const extensionTheme = settingsReport ? settingOf(settingsReport, EXTENSION_THEME_SETTING) : ''; + const contributed = extensions.themes(); + const current = extensionTheme !== '' && contributed.some((theme) => theme.id === extensionTheme) ? extensionTheme : (isColorTheme(base) ? base : 'system'); + const choices = themeChoices(isColorTheme(base) && extensionTheme === '' ? base : 'system').map((choice) => (extensionTheme !== '' && choice.description ? { id: choice.id, label: choice.label } : choice)); + // #257: the themes of the enabled extensions, after the built-in ones. + const items: PickItem[] = [ + ...choices.map(({ id, label, description }) => ({ id, label, ...(description ? { description } : {}) })), + ...contributed.map((theme) => ({ id: theme.id, label: theme.label, description: theme.id === current ? `current · ${theme.extensionId}` : theme.extensionId })), + ]; + const baseOf = (theme: ContributedTheme): ColorTheme => (theme.uiTheme === 'vs' || theme.uiTheme === 'hc-light' ? 'light' : 'dark'); let previewed: string | undefined = current; - const preview = (theme: ColorTheme | null): void => { - api.settings.previewTheme(theme).catch((error: unknown) => workbench.setStatus(`Could not preview the theme: ${String(error)}`)); + const preview = (id: string | null): void => { + const theme = id === null ? undefined : contributed.find((candidate) => candidate.id === id); + const os: ColorTheme | null = id === null ? null : theme ? baseOf(theme) : isColorTheme(id) ? id : null; + api.settings.previewTheme(os).catch((error: unknown) => workbench.setStatus(`Could not preview the theme: ${String(error)}`)); + void extensions.contributions.previewTheme(id === null ? null : theme ? theme.id : ''); }; quickInput.open('', { label: 'Select color theme', initialId: current, view: (value) => pickListView(items, value), onActive: (id) => { - if (isColorTheme(id) && id !== previewed) { + if (id !== undefined && id !== previewed && (isColorTheme(id) || contributed.some((theme) => theme.id === id))) { previewed = id; preview(id); } @@ -565,13 +586,20 @@ function selectColorTheme(): void { } }, accept: (action) => { - if (action.kind !== 'pick' || !isColorTheme(action.id)) { + if (action.kind !== 'pick') { return; } - api.settings.update('user', COLOR_THEME_SETTING, action.id === 'system' ? null : action.id).then(applySettings, (error: unknown) => { - preview(null); - notifications.notify('error', `Could not change the theme: ${String(error)}`); - }); + const theme = contributed.find((candidate) => candidate.id === action.id); + if (!theme && !isColorTheme(action.id)) { + return; + } + const baseValue = theme ? baseOf(theme) : action.id; + api.settings.update('user', COLOR_THEME_SETTING, baseValue === 'system' ? null : baseValue) + .then(() => api.settings.update('user', EXTENSION_THEME_SETTING, theme ? theme.id : null)) + .then(applySettings, (error: unknown) => { + preview(null); + notifications.notify('error', `Could not change the theme: ${String(error)}`); + }); }, }); } @@ -611,6 +639,17 @@ const tasks = createTaskRunner({ showProblems: (task, problems) => problemsView.setTaskProblems(task, problems), setStatus: (message) => workbench.setStatus(message), }); +// #251: VS Code extensions: the Extensions view, their themes, languages and snippets. +const extensions = installExtensions({ + api, + registry, + viewContainer: workbench.extensionsView, + detailsHost: workbench.editorArea.parentElement ?? document.body, + showView: () => workbench.showView('extensions'), + onStatus: (message) => workbench.setStatus(message), + notify: (kind, message) => notifications.notify(kind, message), + selectColorTheme: () => selectColorTheme(), +}); registerAgentCommands(registry, { showAgents: () => workbench.showView('agents'), addProvider: () => agentsView.addProvider(), newChat: () => void agentsView.newChat() }); registerWorkbenchCommands(registry, { openCommandPalette: () => quickInput.open(COMMAND_PREFIX), diff --git a/apps/ide/src/renderer/workbench.ts b/apps/ide/src/renderer/workbench.ts index f8dc32938..73ba6e06f 100644 --- a/apps/ide/src/renderer/workbench.ts +++ b/apps/ide/src/renderer/workbench.ts @@ -30,12 +30,14 @@ const ACTIVITY: readonly ActivityItem[] = [ { id: 'xr', label: 'XR scene', icon: 'M2 8h20v9h-6l-2-3h-4l-2 3H2z' }, // The AI agent hub (agents/agentsView.ts). { id: 'agents', label: 'Agents', icon: 'M4 5h16v11H9l-5 4zM9 10h.01M12 10h.01M15 10h.01' }, + // #255: VS Code extensions from Open VSX (extensions/extensionsView.ts). + { id: 'extensions', label: 'Extensions', icon: 'M4 4h7v7H4zM4 13h7v7H4zM13 13h7v7h-7zM16.5 3l4.5 4.5L16.5 12 12 7.5z' }, // #18: the Settings view, at the foot of the activity bar as in VS Code. { id: 'settings', label: 'Settings', icon: 'M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6zM12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M4.9 19.1L7 17M17 7l2.1-2.1', bottom: true }, ]; /** `keybindings` has no activity item of its own: it is part of Settings (#18, part 3). */ -export type ViewId = 'explorer' | 'search' | 'scm' | 'analysis' | 'xr' | 'agents' | 'settings' | 'keybindings'; +export type ViewId = 'explorer' | 'search' | 'scm' | 'analysis' | 'xr' | 'agents' | 'extensions' | 'settings' | 'keybindings'; export interface Workbench { /** The explorer's part of its side-bar pane (the file tree). */ @@ -56,6 +58,8 @@ export interface Workbench { readonly analysisView: HTMLElement; /** The Agents view's pane of the side bar (AI agent hub). */ readonly agentsView: HTMLElement; + /** The Extensions view's pane of the side bar (#255, extensions/extensionsView.ts). */ + readonly extensionsView: HTMLElement; /** The Settings view's pane of the side bar (#18, settings/settingsView.ts). */ readonly settingsView: HTMLElement; /** The Keyboard Shortcuts pane (#18, part 3, settings/keybindingsView.ts), shown under the Settings item. */ @@ -118,10 +122,11 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null el('p', { className: 'muted side-note', text: 'Run an analysis from the Analysis view: its XR scene opens beside the code.' }), ]); const agentsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'agents', 'data-testid': 'agents-view' } }); + const extensionsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'extensions', 'data-testid': 'extensions-view' } }); const settingsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'settings', 'data-testid': 'settings-view' } }); const keybindingsView = el('div', { className: 'side-pane', attrs: { 'data-view': 'keybindings', 'data-testid': 'keybindings-view' } }); - const panes = new Map([['explorer', explorerPane], ['search', searchView], ['scm', scmView], ['analysis', analysisView], ['xr', xrView], ['agents', agentsView], ['settings', settingsView], ['keybindings', keybindingsView]]); - const sideBarFrame = el('aside', { className: 'side-bar', attrs: { 'aria-label': 'Explorer', 'data-testid': 'side-bar' } }, [explorerPane, searchView, scmView, analysisView, xrView, agentsView, settingsView, keybindingsView]); + const panes = new Map([['explorer', explorerPane], ['search', searchView], ['scm', scmView], ['analysis', analysisView], ['xr', xrView], ['agents', agentsView], ['extensions', extensionsView], ['settings', settingsView], ['keybindings', keybindingsView]]); + const sideBarFrame = el('aside', { className: 'side-bar', attrs: { 'aria-label': 'Explorer', 'data-testid': 'side-bar' } }, [explorerPane, searchView, scmView, analysisView, xrView, agentsView, extensionsView, settingsView, keybindingsView]); function showView(id: ViewId, reveal = true): void { if (reveal && (!layout.sideBarVisible || layout.zen)) { @@ -195,6 +200,7 @@ export function renderWorkbench(root: HTMLElement, storage: LayoutStorage | null isViewVisible: (id: ViewId) => !panes.get(id)?.hidden && layout.sideBarVisible && !layout.zen, analysisView, agentsView, + extensionsView, settingsView, keybindingsView, showView: (id: ViewId) => showView(id), diff --git a/apps/ide/src/shared/api.ts b/apps/ide/src/shared/api.ts index 34b84b03d..96c3fda89 100644 --- a/apps/ide/src/shared/api.ts +++ b/apps/ide/src/shared/api.ts @@ -18,6 +18,7 @@ import { AGENT_IPC_CHANNELS, AGENT_IPC_EVENTS, type AgentsApi } from './agents.t import { GIT_IPC_CHANNELS, GIT_IPC_EVENTS, type GitApi } from './git.ts'; import { LSP_IPC_CHANNELS, LSP_IPC_EVENTS, type LspApi } from './lsp.ts'; import { TASK_IPC_CHANNELS, TASK_IPC_EVENTS, type TasksApi } from './tasks.ts'; +import { EXTENSION_IPC_CHANNELS, EXTENSION_IPC_EVENTS, type ExtensionsApi } from './extensions.ts'; /** Facts about the running IDE, shown on the welcome screen and in About. */ export interface AppInfo { @@ -354,6 +355,8 @@ export interface CodeXRApi { readonly tasks: TasksApi; /** #21: language servers for Monaco (contract in lsp.ts). */ readonly lsp: LspApi; + /** #251: VS Code extensions (shared/extensions.ts). */ + readonly extensions: ExtensionsApi; readonly app: { getInfo(): Promise; /** Messages from the core (environment set up, a server stopped ...). */ @@ -660,6 +663,7 @@ export const IPC_CHANNELS = { ...LSP_IPC_CHANNELS, // #176: tasks keep their own channel list in tasks.ts. ...TASK_IPC_CHANNELS, + ...EXTENSION_IPC_CHANNELS, } as const; export type IpcChannel = (typeof IPC_CHANNELS)[keyof typeof IPC_CHANNELS]; @@ -691,6 +695,7 @@ export const IPC_EVENTS = { ...GIT_IPC_EVENTS, ...LSP_IPC_EVENTS, ...TASK_IPC_EVENTS, + ...EXTENSION_IPC_EVENTS, } as const; /** The error message a refused `writeFile` carries when the file changed on disk. */ diff --git a/apps/ide/src/shared/extensions.ts b/apps/ide/src/shared/extensions.ts new file mode 100644 index 000000000..a4e5cc89e --- /dev/null +++ b/apps/ide/src/shared/extensions.ts @@ -0,0 +1,288 @@ +/** + * VS Code extensions in the IDE (epic #251, ADR 0002): the contract between + * the renderer and the main process. Extensions come from Open VSX (never the + * Visual Studio Marketplace) or from a `.vsix` file, are unpacked into the + * IDE's user-data folder, and contribute either declaratively (themes, + * languages, grammars, snippets: applied by the workbench itself) or with + * code, which runs in the extension host process, never in the renderer. + * + * Shared by main, preload and renderer: no Node, Electron or DOM import. + */ + +/** `publisher.name`, lower-cased: VS Code compares extension ids without case. */ +export type ExtensionId = string; + +/** The canonical id of an extension, as VS Code builds it. */ +export function extensionIdOf(publisher: string, name: string): ExtensionId { + return `${publisher}.${name}`.toLowerCase(); +} + +/** A well-formed `publisher.name` id: what the renderer may send for an extension. */ +export function isExtensionId(value: unknown): value is ExtensionId { + return typeof value === 'string' && value.length <= 256 && /^[a-z0-9][a-z0-9-]*\.[a-z0-9][a-z0-9._-]*$/i.test(value); +} + +/** Why an installed extension does not run, when it does not. */ +export type ExtensionRunState = + /** Enabled; its code (if any) activates on its activation events. */ + | 'enabled' + /** Turned off by the person. */ + | 'disabled' + /** #263: the folder is in Restricted Mode and the extension does not declare it supports that. */ + | 'restricted'; + +/** Where the activation of an extension with code stands in this window's host. */ +export type ExtensionActivation = 'none' | 'inactive' | 'activating' | 'active' | 'failed'; + +/** What an extension contributes, as counts and names for the Extensions view. */ +export interface ContributionSummary { + readonly themes: readonly string[]; + readonly iconThemes: readonly string[]; + readonly languages: readonly string[]; + readonly grammars: number; + readonly snippets: number; + readonly commands: readonly string[]; + readonly views: readonly string[]; + readonly settings: number; + readonly keybindings: number; + readonly localizations: readonly string[]; +} + +/** An installed extension, as the Extensions view lists it. */ +export interface InstalledExtension { + readonly id: ExtensionId; + readonly publisher: string; + readonly name: string; + readonly version: string; + readonly displayName: string; + readonly description: string; + readonly categories: readonly string[]; + readonly license: string | null; + readonly repository: string | null; + /** Its icon as a `data:` URL (small PNG/SVG), or null. */ + readonly icon: string | null; + /** Whether it has code to run (`main`), not only declarative contributions. */ + readonly hasCode: boolean; + readonly state: ExtensionRunState; + readonly activation: ExtensionActivation; + /** The error of a failed activation, for the view. */ + readonly activationError?: string; + /** `engines.vscode` as declared. */ + readonly engine: string; + /** Its `engines.vscode` asks for a newer API than the host implements: it still runs, with a warning. */ + readonly engineWarning: boolean; + /** Open VSX or a `.vsix` file. */ + readonly source: 'open-vsx' | 'vsix'; + readonly installedAt: number; + readonly contributes: ContributionSummary; + /** True when it supports Restricted Mode (`capabilities.untrustedWorkspaces.supported`). */ + readonly supportsUntrusted: boolean; +} + +/** An extension in the registry's search results. */ +export interface GalleryExtension { + readonly id: ExtensionId; + readonly namespace: string; + readonly name: string; + readonly version: string; + readonly displayName: string; + readonly description: string; + /** An https URL on the registry, shown through the main process (see `galleryIcon`). */ + readonly iconUrl: string | null; + readonly downloadCount: number; + readonly averageRating: number | null; + /** The registry vouches for the publisher (Open VSX: `verified`). */ + readonly verified: boolean; + readonly timestamp: string | null; +} + +export interface GallerySearchResult { + readonly offset: number; + readonly totalSize: number; + readonly extensions: readonly GalleryExtension[]; +} + +export const GALLERY_SORTS = ['relevance', 'downloadCount', 'averageRating', 'timestamp'] as const; +export type GallerySort = (typeof GALLERY_SORTS)[number]; + +export interface GalleryQuery { + readonly text: string; + readonly category?: string; + readonly sortBy?: GallerySort; + readonly offset?: number; + readonly size?: number; +} + +/** The details page of an extension in the registry. */ +export interface GalleryDetails extends GalleryExtension { + readonly publisherDisplayName: string; + readonly license: string | null; + readonly repository: string | null; + readonly homepage: string | null; + readonly categories: readonly string[]; + readonly tags: readonly string[]; + readonly engine: string | null; + /** Versions offered, newest first. */ + readonly versions: readonly string[]; + readonly readme: string | null; + /** Target platforms this version is published for (`universal` when one build fits all). */ + readonly targetPlatforms: readonly string[]; +} + +/** What `install` reports. */ +export type InstallResult = + | { readonly ok: true; readonly extension: InstalledExtension; readonly replaced: string | null } + | { readonly ok: false; readonly cancelled?: boolean; readonly error: string }; + +/** The README of an installed extension, for its details tab. */ +export interface InstalledDetails { + readonly extension: InstalledExtension; + readonly readme: string | null; + readonly changelog: string | null; +} + +// --- Declarative contributions, resolved by the main process for the workbench (#257, #258). + +/** A colour theme contributed by an extension, as the theme picker lists it. */ +export interface ContributedTheme { + /** `/`: what the `workbench.colorTheme` setting stores. */ + readonly id: string; + readonly label: string; + readonly extensionId: ExtensionId; + /** VS Code's base: `vs` (light), `vs-dark`, `hc-black`, `hc-light`. */ + readonly uiTheme: 'vs' | 'vs-dark' | 'hc-black' | 'hc-light'; +} + +/** A theme file resolved: `include` chains merged, `.tmTheme` read. */ +export interface ResolvedTheme { + readonly id: string; + readonly label: string; + readonly uiTheme: ContributedTheme['uiTheme']; + readonly colors: Readonly>; + readonly tokenColors: readonly ThemeTokenRule[]; + readonly semanticHighlighting: boolean; +} + +export interface ThemeTokenRule { + readonly scope: readonly string[]; + readonly foreground?: string; + readonly background?: string; + readonly fontStyle?: string; +} + +/** A language contributed by an extension. */ +export interface ContributedLanguage { + readonly id: string; + readonly extensionId: ExtensionId; + readonly aliases: readonly string[]; + readonly extensions: readonly string[]; + readonly filenames: readonly string[]; + readonly filenamePatterns: readonly string[]; + readonly firstLine: string | null; + readonly mimetypes: readonly string[]; + /** The parsed `language-configuration.json`, if any (JSON with comments, already parsed). */ + readonly configuration: unknown; +} + +/** A TextMate grammar contributed by an extension. */ +export interface ContributedGrammar { + readonly extensionId: ExtensionId; + readonly language: string | null; + readonly scopeName: string; + /** Opaque handle to fetch its content with `grammarContent`. */ + readonly ref: string; + readonly embeddedLanguages: Readonly>; + readonly tokenTypes: Readonly>; + readonly injectTo: readonly string[]; +} + +/** The text of a grammar file and its format. */ +export interface GrammarContent { + readonly format: 'json' | 'plist'; + readonly content: string; +} + +/** One snippet, as `contributes.snippets` files hold them. */ +export interface ContributedSnippet { + readonly extensionId: ExtensionId; + readonly language: string; + readonly name: string; + readonly prefixes: readonly string[]; + readonly body: string; + readonly description: string; +} + +/** Everything declarative the workbench applies from the enabled extensions. */ +export interface ExtensionContributions { + readonly themes: readonly ContributedTheme[]; + readonly languages: readonly ContributedLanguage[]; + readonly grammars: readonly ContributedGrammar[]; + readonly snippets: readonly ContributedSnippet[]; +} + +export interface ExtensionsChangedEvent { + readonly installed: readonly InstalledExtension[]; +} + +/** One line for the *Extensions* channel of the Output panel. */ +export interface ExtensionLogEvent { + readonly level: 'info' | 'warn' | 'error'; + readonly message: string; +} + +export interface ExtensionsApi { + /** The installed extensions, with their state in this window. */ + list(): Promise; + /** Searches the registry (network: only when the person searches). */ + search(query: GalleryQuery): Promise; + /** The registry's page for an extension (README included). */ + galleryDetails(id: ExtensionId): Promise; + /** An icon of the registry as a `data:` URL (the CSP keeps the renderer off the network). */ + galleryIcon(url: string): Promise; + /** Asks, then downloads, checks and installs; `version` defaults to the latest. */ + install(id: ExtensionId, version?: string): Promise; + /** Asks for a `.vsix` file with a native dialog and installs it. */ + installVsix(): Promise; + uninstall(id: ExtensionId): Promise; + setEnabled(id: ExtensionId, enabled: boolean): Promise; + /** Turns every extension off (recovery). */ + disableAll(): Promise; + details(id: ExtensionId): Promise; + contributions(): Promise; + /** A contributed theme, resolved; null if its extension is gone or disabled. */ + theme(themeId: string): Promise; + grammarContent(ref: string): Promise; + onDidChange(listener: (event: ExtensionsChangedEvent) => void): () => void; + onLog(listener: (event: ExtensionLogEvent) => void): () => void; +} + +export const EXTENSION_IPC_CHANNELS = { + extensionsList: 'codexr:extensions:list', + extensionsSearch: 'codexr:extensions:search', + extensionsGalleryDetails: 'codexr:extensions:gallery-details', + extensionsGalleryIcon: 'codexr:extensions:gallery-icon', + extensionsInstall: 'codexr:extensions:install', + extensionsInstallVsix: 'codexr:extensions:install-vsix', + extensionsUninstall: 'codexr:extensions:uninstall', + extensionsSetEnabled: 'codexr:extensions:set-enabled', + extensionsDisableAll: 'codexr:extensions:disable-all', + extensionsDetails: 'codexr:extensions:details', + extensionsContributions: 'codexr:extensions:contributions', + extensionsTheme: 'codexr:extensions:theme', + extensionsGrammarContent: 'codexr:extensions:grammar-content', +} as const; + +export const EXTENSION_IPC_EVENTS = { + extensionsChanged: 'codexr:extensions:changed', + extensionsLog: 'codexr:extensions:log', +} as const; + +/** The default registry, and the setting that changes it. */ +export const DEFAULT_GALLERY_URL = 'https://open-vsx.org'; +export const GALLERY_URL_SETTING = 'extensions.gallery.serviceUrl'; + +/** Prefix of the `workbench.colorTheme` values that name an extension's theme. */ +export const EXTENSION_THEME_PREFIX = 'ext:'; + +/** The highest VS Code API version the host implements (for `engines.vscode`). */ +export const HOST_VSCODE_API_VERSION = '1.146.0'; diff --git a/apps/ide/src/shared/output.ts b/apps/ide/src/shared/output.ts index d4a3e6897..f8e86cd34 100644 --- a/apps/ide/src/shared/output.ts +++ b/apps/ide/src/shared/output.ts @@ -12,6 +12,8 @@ export const OUTPUT_CHANNELS = [ { id: 'servers', label: 'Servers and tunnel' }, // #21: the language servers (TypeScript, Python): start, stop, crashes, their own messages. { id: 'lsp', label: 'Language servers' }, + // #251: installs, the extension host, and the VS Code API calls the host does not implement yet. + { id: 'extensions', label: 'Extensions' }, ] as const; export type OutputChannelId = (typeof OUTPUT_CHANNELS)[number]['id']; diff --git a/apps/ide/src/shared/settings.ts b/apps/ide/src/shared/settings.ts index 555fab085..311df8a4a 100644 --- a/apps/ide/src/shared/settings.ts +++ b/apps/ide/src/shared/settings.ts @@ -77,6 +77,10 @@ export const SETTINGS: readonly SettingDefinition[] = [ // #176: Run Current File. Empty means the usual name on PATH (python3, or python on Windows; node). { key: 'run.pythonInterpreter', category: 'Run', title: 'Python Interpreter', description: 'What Run Current File runs a .py file with: a name on PATH or a full path (a virtual environment\'s python, for example). Empty uses python3, or python on Windows.', type: 'string', maxLength: 1000, default: '' }, { key: 'run.nodeInterpreter', category: 'Run', title: 'Node Interpreter', description: 'What Run Current File runs a .js or .ts file with: a name on PATH or a full path. Empty uses node (TypeScript needs Node 22.18 or later).', type: 'string', maxLength: 1000, default: '' }, + // #254: where the Extensions view searches and installs from (an Open VSX registry; never the Visual Studio Marketplace). + { key: 'extensions.gallery.serviceUrl', category: 'Extensions', title: 'Registry', description: 'The Open VSX registry the Extensions view searches and installs from: https, or http on this machine. Change it to use your organisation\'s own registry.', type: 'string', maxLength: 300, default: 'https://open-vsx.org', userOnly: true }, + // #257: a colour theme contributed by an installed extension; empty uses Color Theme above. + { key: 'workbench.colorThemeExtension', category: 'Workbench', title: 'Extension Color Theme', description: 'A colour theme from an installed extension (pick it with Preferences: Color Theme). Empty uses the Color Theme setting.', type: 'string', maxLength: 300, default: '', userOnly: true }, { key: 'terminal.integrated.fontSize', category: 'Terminal', title: 'Font Size', description: 'The terminal font size, in pixels.', type: 'number', min: 6, max: 72, integer: true, default: 13 }, ] as const; diff --git a/apps/ide/test/extensions.test.ts b/apps/ide/test/extensions.test.ts new file mode 100644 index 000000000..d06840191 --- /dev/null +++ b/apps/ide/test/extensions.test.ts @@ -0,0 +1,338 @@ +import { after, before, describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { compareVersions, engineSupported, isSafeRelativePath, localizeManifest, ManifestError, parseManifest, summarizeContributions } from '../src/main/extensions/manifest.ts'; +import { extractVsix, isSymlinkEntry, readVsixManifest, vsixEntryPath, VsixError } from '../src/main/extensions/vsix.ts'; +import { ExtensionStore, manifestFromText, resolveInExtension } from '../src/main/extensions/extensionStore.ts'; +import { ContributionIndex, parseSnippets, readTmTheme } from '../src/main/extensions/contributions.ts'; +import { parsePlist } from '../src/main/extensions/plist.ts'; +import { GalleryError, normalizeGalleryUrl, OpenVsxClient, splitExtensionId, targetPlatform, type FetchLike } from '../src/main/extensions/openVsx.ts'; +import { extensionIdOf, isExtensionId } from '../src/shared/extensions.ts'; +import { vsix, zip } from './helpers/zip.ts'; + +const BASE = { publisher: 'acme', name: 'demo', version: '1.2.3', engines: { vscode: '^1.80.0' } }; + +let tmp = ''; +before(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'codexr-ext-test-')); +}); +after(() => { + fs.rmSync(tmp, { recursive: true, force: true }); +}); + +function writeVsix(name: string, data: Buffer): string { + const file = path.join(tmp, name); + fs.writeFileSync(file, data); + return file; +} + +describe('extension ids (#254)', () => { + it('are publisher.name in lower case', () => { + assert.equal(extensionIdOf('Acme', 'Demo'), 'acme.demo'); + assert.equal(isExtensionId('acme.demo-x'), true); + assert.equal(isExtensionId('ms-python.python'), true); + assert.equal(isExtensionId('acme'), false); + assert.equal(isExtensionId('../x.y'), false); + assert.equal(isExtensionId(3), false); + assert.deepEqual(splitExtensionId('redhat.vscode-yaml'), { namespace: 'redhat', name: 'vscode-yaml' }); + }); +}); + +describe('extension manifest (#254)', () => { + it('reads the fields the IDE uses', () => { + const manifest = parseManifest({ ...BASE, displayName: 'Demo', main: './out/extension.js', icon: 'icon.png', repository: { url: 'git+https://github.com/acme/demo.git' }, capabilities: { untrustedWorkspaces: { supported: 'limited' } } }); + assert.equal(manifest.id, 'acme.demo'); + assert.equal(manifest.displayName, 'Demo'); + assert.equal(manifest.main, './out/extension.js'); + assert.equal(manifest.repository, 'https://github.com/acme/demo'); + assert.equal(manifest.supportsUntrusted, true); + }); + + it('refuses what is not a VS Code extension or points outside it', () => { + assert.throws(() => parseManifest({ ...BASE, engines: {} }), ManifestError); + assert.throws(() => parseManifest({ ...BASE, publisher: '' }), ManifestError); + assert.throws(() => parseManifest({ ...BASE, version: 'one' }), ManifestError); + assert.throws(() => parseManifest({ ...BASE, main: '../../evil.js' }), ManifestError); + assert.throws(() => parseManifest({ ...BASE, icon: '/etc/passwd' }), ManifestError); + assert.throws(() => parseManifest({ ...BASE, main: 'C:\\evil.js' }), ManifestError); + }); + + it('localises %placeholders% from package.nls.json', () => { + const localized = localizeManifest({ displayName: '%name%', contributes: { commands: [{ title: '%cmd%' }] }, other: '%missing%' }, { name: 'Nice', cmd: { message: 'Run it', comment: [] } }); + assert.deepEqual(localized, { displayName: 'Nice', contributes: { commands: [{ title: 'Run it' }] }, other: '%missing%' }); + }); + + it('summarises contributions', () => { + const summary = summarizeContributions(parseManifest({ ...BASE, contributes: { + themes: [{ label: 'Dark Demo', path: './t.json' }], + languages: [{ id: 'demo' }], + grammars: [{ scopeName: 'source.demo', path: 'g.json' }], + commands: [{ command: 'demo.run', title: 'Run' }], + views: { explorer: [{ id: 'demo.view', name: 'Demo View' }] }, + configuration: { properties: { 'demo.a': {}, 'demo.b': {} } }, + } })); + assert.deepEqual(summary.themes, ['Dark Demo']); + assert.deepEqual(summary.languages, ['demo']); + assert.equal(summary.grammars, 1); + assert.deepEqual(summary.commands, ['Run']); + assert.deepEqual(summary.views, ['Demo View']); + assert.equal(summary.settings, 2); + }); + + it('compares versions and engines', () => { + assert.ok(compareVersions('1.10.0', '1.9.9') > 0); + assert.equal(compareVersions('2.0.0', '2.0.0'), 0); + assert.equal(engineSupported('^1.80.0', '1.95.0'), true); + assert.equal(engineSupported('^1.99.0', '1.95.0'), false); + assert.equal(engineSupported('*', '1.0.0'), true); + assert.equal(engineSupported('>=1.x', '1.0.0'), true); + }); + + it('accepts only relative paths inside the extension', () => { + assert.equal(isSafeRelativePath('out/a.js'), true); + assert.equal(isSafeRelativePath('a/../../b'), false); + assert.equal(isSafeRelativePath('/a'), false); + assert.equal(isSafeRelativePath('a\0b'), false); + }); +}); + +describe('VSIX reading (#254)', () => { + it('maps entries under extension/ and refuses unsafe ones', () => { + assert.equal(vsixEntryPath('extension/package.json'), 'package.json'); + assert.equal(vsixEntryPath('extension.vsixmanifest'), null); + assert.equal(vsixEntryPath('extension/'), ''); + assert.throws(() => vsixEntryPath('extension/../evil'), VsixError); + assert.throws(() => vsixEntryPath('extension//etc/passwd'), VsixError); + assert.throws(() => vsixEntryPath('extension/a\\..\\b'), VsixError); + assert.throws(() => vsixEntryPath('../outside'), VsixError); + assert.equal(isSymlinkEntry((0o120777 << 16) >>> 0), true); + assert.equal(isSymlinkEntry((0o100644 << 16) >>> 0), false); + }); + + it('reads the manifest and unpacks the extension folder', async () => { + const file = writeVsix('ok.vsix', vsix({ ...BASE, displayName: '%n%' }, { 'package.nls.json': '{"n":"Localised"}', 'out/extension.js': 'exports.activate = () => {};' })); + const preview = await readVsixManifest(file); + assert.equal(manifestFromText(preview.packageJson, preview.nlsJson).displayName, 'Localised'); + const target = path.join(tmp, 'unpacked'); + await extractVsix(file, target); + assert.equal(fs.readFileSync(path.join(target, 'out', 'extension.js'), 'utf8'), 'exports.activate = () => {};'); + assert.equal(fs.existsSync(path.join(target, '[Content_Types].xml')), false); + }); + + it('refuses a zip-slip entry, a symbolic link and garbage, and leaves nothing behind', async () => { + const slip = writeVsix('slip.vsix', zip([{ name: 'extension/package.json', data: JSON.stringify(BASE) }, { name: 'extension/../../evil.txt', data: 'x' }])); + await assert.rejects(extractVsix(slip, path.join(tmp, 'slip')), /Unsafe path|invalid relative path|absolute path/); + const link = writeVsix('link.vsix', zip([{ name: 'extension/package.json', data: JSON.stringify(BASE) }, { name: 'extension/link', data: '/etc/passwd', mode: 0o120777 }])); + await assert.rejects(extractVsix(link, path.join(tmp, 'link')), /symbolic link/); + assert.equal(fs.readdirSync(tmp).some((name) => name.includes('.partial-')), false); + const garbage = writeVsix('garbage.vsix', Buffer.from('not a zip')); + await assert.rejects(readVsixManifest(garbage), VsixError); + const noManifest = writeVsix('none.vsix', zip([{ name: 'extension/readme.md', data: 'x' }])); + await assert.rejects(readVsixManifest(noManifest), /no extension\/package.json/); + }); +}); + +describe('extension store (#254, #263)', () => { + it('installs, updates, disables and uninstalls', async () => { + const root = path.join(tmp, 'store'); + const store = new ExtensionStore(root); + const v1 = writeVsix('v1.vsix', vsix(BASE, { 'README.md': '# Demo' })); + const first = await store.install(v1, 'vsix'); + assert.equal(first.extension.manifest.id, 'acme.demo'); + assert.equal(first.replaced, null); + assert.equal(store.list().length, 1); + assert.equal(store.isNewer('acme.demo', '1.2.4'), true); + assert.equal(store.isNewer('acme.demo', '1.2.3'), false); + + const v2 = writeVsix('v2.vsix', vsix({ ...BASE, version: '1.3.0' })); + const second = await store.install(v2, 'open-vsx'); + assert.equal(second.replaced, '1.2.3'); + assert.equal(fs.existsSync(path.join(root, 'acme.demo-1.2.3')), false, 'the old version folder is removed'); + assert.equal(store.get('ACME.demo')?.manifest.version, '1.3.0'); + + store.setEnabled('acme.demo', false); + // A new store reads the same file: the state survives a restart. + assert.equal(new ExtensionStore(root).get('acme.demo')?.enabled, false); + store.setEnabled('acme.demo', true); + assert.equal(store.get('acme.demo')?.enabled, true); + store.disableAll(); + assert.equal(store.get('acme.demo')?.enabled, false); + + assert.equal(await store.uninstall('acme.demo'), true); + assert.equal(store.list().length, 0); + assert.equal(fs.existsSync(path.join(root, 'acme.demo-1.3.0')), false); + assert.equal(await store.uninstall('acme.demo'), false); + }); + + it('ignores a tampered record that points outside the store', () => { + const root = path.join(tmp, 'tampered'); + fs.mkdirSync(root, { recursive: true }); + fs.writeFileSync(path.join(root, 'extensions.json'), JSON.stringify({ version: 1, installed: { 'acme.demo': { version: '1.0.0', folder: '../../etc', source: 'vsix' } }, disabled: [] })); + assert.equal(new ExtensionStore(root).list().length, 0); + }); + + it('resolves files only inside the extension', () => { + const location = path.join(tmp, 'resolve'); + fs.mkdirSync(location, { recursive: true }); + assert.equal(resolveInExtension(location, './themes/a.json'), path.join(location, 'themes', 'a.json')); + assert.equal(resolveInExtension(location, '../a.json'), null); + assert.equal(resolveInExtension(location, '/etc/passwd'), null); + }); +}); + +describe('declarative contributions (#257, #258)', () => { + it('resolves themes with include chains and .tmTheme files, languages, grammars and snippets', async () => { + const store = new ExtensionStore(path.join(tmp, 'contrib')); + const file = writeVsix('contrib.vsix', vsix({ + ...BASE, + name: 'kit', + contributes: { + themes: [{ label: 'Kit Dark', uiTheme: 'vs-dark', path: './themes/dark.json' }, { label: 'Kit Classic', uiTheme: 'vs', path: './themes/classic.json' }, { label: 'Missing', path: './nope.json' }], + languages: [{ id: 'kit', extensions: ['.kit'], aliases: ['Kit'], configuration: './kit.language-configuration.json' }], + grammars: [{ language: 'kit', scopeName: 'source.kit', path: './syntaxes/kit.tmLanguage.json' }, { scopeName: 'evil', path: '../../escape.json' }], + snippets: [{ language: 'kit', path: './snippets.json' }], + }, + }, { + 'themes/base.json': '{ "colors": { "editor.background": "#111111", "foreground": "#eeeeee" }, "tokenColors": [{ "scope": "comment", "settings": { "foreground": "#888888" } }] }', + // JSON with comments and an include: the including file wins. + 'themes/dark.json': '{ // dark\n "include": "./base.json", "colors": { "editor.background": "#222222", }, "tokenColors": [{ "scope": "keyword, storage", "settings": { "foreground": "#ff0000", "fontStyle": "bold" } }] }', + 'themes/classic.json': '{ "tokenColors": "./classic.tmTheme" }', + 'themes/classic.tmTheme': 'settingssettingsbackground#FFFFFFforeground#000000scopestringsettingsforeground#00AA00', + 'kit.language-configuration.json': '{ "comments": { "lineComment": "#" }, /* c */ "brackets": [["(", ")"]] }', + 'syntaxes/kit.tmLanguage.json': '{ "scopeName": "source.kit", "patterns": [] }', + 'snippets.json': '{ "Hello": { "prefix": ["hi", "hello"], "body": ["print(\\"$1\\")", "$0"], "description": "Say hi" } }', + })); + const installed = await store.install(file, 'vsix'); + const warnings: string[] = []; + const index = new ContributionIndex([installed.extension], (message) => warnings.push(message)); + const { themes, languages, grammars, snippets } = index.contributions; + assert.deepEqual(themes.map((theme) => theme.id), ['ext:acme.kit/Kit Dark', 'ext:acme.kit/Kit Classic']); + assert.equal(warnings.length, 2, 'the missing theme and the escaping grammar are reported'); + + const dark = index.theme('ext:acme.kit/Kit Dark'); + assert.equal(dark?.colors['editor.background'], '#222222'); + assert.equal(dark?.colors.foreground, '#eeeeee'); + assert.deepEqual(dark?.tokenColors.map((rule) => rule.scope), [['comment'], ['keyword', 'storage']]); + + const classic = index.theme('ext:acme.kit/Kit Classic'); + assert.equal(classic?.uiTheme, 'vs'); + assert.equal(classic?.colors['editor.background'], '#FFFFFF'); + assert.deepEqual(classic?.tokenColors, [{ scope: ['string'], foreground: '#00AA00' }]); + assert.equal(index.theme('ext:acme.kit/Missing'), null); + + assert.equal(languages[0]?.id, 'kit'); + assert.deepEqual(languages[0]?.configuration, { comments: { lineComment: '#' }, brackets: [['(', ')']] }); + assert.equal(grammars.length, 1); + assert.equal(index.grammarContent(grammars[0]?.ref ?? '')?.format, 'json'); + assert.equal(index.grammarContent('acme.kit#99'), null); + assert.deepEqual(snippets.map((s) => [s.language, s.prefixes, s.body]), [['kit', ['hi', 'hello'], 'print("$1")\n$0']]); + }); + + it('reads snippets scoped by language and .tmTheme global colours', () => { + assert.deepEqual(parseSnippets({ A: { prefix: 'a', body: 'x', scope: 'javascript,typescript' }, Bad: { body: 'no prefix' } }, 'e', null).map((s) => s.language), ['javascript', 'typescript']); + const tm = readTmTheme('settingssettingscaret#ff0000'); + assert.deepEqual(tm.colors, { 'editorCursor.foreground': '#ff0000' }); + assert.deepEqual(parsePlist('a3bcx & y'), { a: 3, b: true, c: 'x & y' }); + }); +}); + +/** A fake Open VSX that answers from a table of URLs. */ +function fakeRegistry(routes: Record): { fetch: FetchLike; calls: string[] } { + const calls: string[] = []; + const fetch: FetchLike = async (url) => { + calls.push(url); + const key = Object.keys(routes).find((route) => url === route || url.startsWith(`${route}?`)); + if (!key) { + return { ok: false, status: 404, headers: { get: () => null }, json: async () => ({}), text: async () => '', arrayBuffer: async () => new ArrayBuffer(0) }; + } + const body = routes[key]; + const bytes = Buffer.isBuffer(body) ? body : Buffer.from(typeof body === 'string' ? body : JSON.stringify(body)); + return { + ok: true, + status: 200, + headers: { get: (name: string) => (name.toLowerCase() === 'content-type' ? (Buffer.isBuffer(body) ? 'image/png' : 'application/json') : null) }, + json: async () => JSON.parse(bytes.toString('utf8')) as unknown, + text: async () => bytes.toString('utf8'), + arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.length) as ArrayBuffer, + }; + }; + return { fetch, calls }; +} + +describe('Open VSX client (#254)', () => { + const R = 'https://registry.test'; + + it('accepts https registries, or http on this machine', () => { + assert.equal(normalizeGalleryUrl('https://open-vsx.org/'), 'https://open-vsx.org'); + assert.equal(normalizeGalleryUrl('http://localhost:3000'), 'http://localhost:3000'); + assert.equal(normalizeGalleryUrl('http://evil.example'), null); + assert.equal(normalizeGalleryUrl('https://user:pw@open-vsx.org'), null); + assert.equal(normalizeGalleryUrl('file:///etc'), null); + assert.equal(targetPlatform('linux', 'x64'), 'linux-x64'); + assert.equal(targetPlatform('darwin', 'arm64'), 'darwin-arm64'); + assert.equal(targetPlatform('win32', 'arm'), 'universal'); + }); + + it('searches and parses results, skipping malformed entries', async () => { + const { fetch, calls } = fakeRegistry({ + [`${R}/api/-/search`]: { offset: 0, totalSize: 2, extensions: [{ namespace: 'dracula-theme', name: 'theme-dracula', version: '2.25.1', displayName: 'Dracula', downloadCount: 1000, verified: true, files: { icon: 'https://cdn.test/icon.png' } }, { namespace: '../x', name: 'y' }] }, + }); + const client = new OpenVsxClient(R, fetch, 'linux-x64'); + const result = await client.search({ text: 'dracula', sortBy: 'downloadCount', size: 500 }); + assert.equal(result.extensions.length, 1); + assert.equal(result.extensions[0]?.id, 'dracula-theme.theme-dracula'); + assert.equal(result.extensions[0]?.verified, true); + const query = new URL(calls[0] ?? '').searchParams; + assert.equal(query.get('query'), 'dracula'); + assert.equal(query.get('size'), '50', 'the page size is capped'); + assert.equal(query.get('sortBy'), 'downloadCount'); + }); + + it('downloads a platform build when there is one and checks the SHA-256', async () => { + const archive = vsix(BASE); + const sha = createHash('sha256').update(archive).digest('hex'); + const { fetch, calls } = fakeRegistry({ + [`${R}/api/acme/demo/linux-x64`]: { namespace: 'acme', name: 'demo', version: '1.2.3', verified: false, files: { download: 'https://cdn.test/demo.vsix', sha256: 'https://cdn.test/demo.sha256' } }, + 'https://cdn.test/demo.vsix': archive, + 'https://cdn.test/demo.sha256': `${sha} demo.vsix\n`, + }); + const download = await new OpenVsxClient(R, fetch, 'linux-x64').download('acme.demo'); + assert.equal(download.sha256, sha); + assert.equal(download.version, '1.2.3'); + assert.ok(calls.includes(`${R}/api/acme/demo/linux-x64`)); + }); + + it('falls back to the universal build and refuses a wrong or missing checksum', async () => { + const archive = vsix(BASE); + const universal = { namespace: 'acme', name: 'demo', version: '1.2.3', files: { download: 'https://cdn.test/demo.vsix', sha256: 'https://cdn.test/bad.sha256' } }; + const bad = fakeRegistry({ [`${R}/api/acme/demo`]: universal, 'https://cdn.test/demo.vsix': archive, 'https://cdn.test/bad.sha256': '0'.repeat(64) }); + await assert.rejects(new OpenVsxClient(R, bad.fetch, 'linux-x64').download('acme.demo'), /does not match/); + const none = fakeRegistry({ [`${R}/api/acme/demo`]: { ...universal, files: { download: 'https://cdn.test/demo.vsix' } } }); + await assert.rejects(new OpenVsxClient(R, none.fetch, 'universal').download('acme.demo'), /no SHA-256/); + const insecure = fakeRegistry({ [`${R}/api/acme/demo`]: { ...universal, files: { download: 'http://cdn.test/demo.vsix', sha256: 'https://cdn.test/x' } } }); + await assert.rejects(new OpenVsxClient(R, insecure.fetch, 'universal').download('acme.demo'), GalleryError); + }); + + it('reads details with the README and the versions newest first', async () => { + const { fetch } = fakeRegistry({ + [`${R}/api/acme/demo`]: { namespace: 'acme', name: 'demo', version: '1.10.0', license: 'MIT', repository: 'https://github.com/acme/demo.git', allVersions: { latest: 'x', '1.2.0': 'x', '1.10.0': 'x', '1.9.0': 'x' }, files: { readme: 'https://cdn.test/README.md' }, engines: { vscode: '^1.80.0' } }, + 'https://cdn.test/README.md': '# Demo', + }); + const details = await new OpenVsxClient(R, fetch, 'universal').details('acme.demo'); + assert.deepEqual(details.versions, ['1.10.0', '1.9.0', '1.2.0']); + assert.equal(details.readme, '# Demo'); + assert.equal(details.repository, 'https://github.com/acme/demo'); + assert.equal(details.engine, '^1.80.0'); + }); + + it('turns icons into data URLs and refuses other content', async () => { + const { fetch } = fakeRegistry({ 'https://cdn.test/icon.png': Buffer.from([0x89, 0x50]) }); + const client = new OpenVsxClient(R, fetch, 'universal'); + assert.equal(await client.icon('https://cdn.test/icon.png'), 'data:image/png;base64,iVA='); + assert.equal(await client.icon('http://cdn.test/icon.png'), null); + assert.equal(await client.icon('https://cdn.test/missing.png'), null); + }); +}); diff --git a/apps/ide/test/extensionsRenderer.test.ts b/apps/ide/test/extensionsRenderer.test.ts new file mode 100644 index 000000000..b0ddfa82c --- /dev/null +++ b/apps/ide/test/extensionsRenderer.test.ts @@ -0,0 +1,152 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import type { InstalledExtension, ResolvedTheme } from '../src/shared/extensions.ts'; +import { normalizeHex, ruleToken, toMonacoTheme, workbenchVariables } from '../src/renderer/extensions/themeModel.ts'; +import { detectLanguage, mergeLanguages, safeRegExp, snippetsFor, toLanguageConfiguration } from '../src/renderer/extensions/languageModel.ts'; +import { compactCount, installedStateLabel, matchesInstalled, rowAction } from '../src/renderer/extensions/extensionsModel.ts'; + +const THEME: ResolvedTheme = { + id: 'ext:acme.kit/Kit', + label: 'Kit', + uiTheme: 'vs-dark', + colors: { 'editor.background': '#1e1e1e', 'editor.foreground': '#ddd', 'sideBar.background': '#252526', 'statusBar.background': '#007acc', 'activityBar.background': 'not-a-colour', focusBorder: '#0078d4AA' }, + tokenColors: [ + { scope: ['comment'], foreground: '#6a9955', fontStyle: 'italic' }, + { scope: ['keyword.control', 'keyword'], foreground: '#C586C0' }, + { scope: ['source.js meta.function entity.name.function'], foreground: '#dcdcaa' }, + { scope: ['-comment', 'a | b'], foreground: '#ffffff' }, + { scope: ['constant.numeric'], foreground: '#b5cea8' }, + { scope: ['string'] }, + ], + semanticHighlighting: false, +}; + +describe('colour themes from extensions (#257)', () => { + it('normalises hex colours', () => { + assert.equal(normalizeHex('#ABC'), '#aabbcc'); + assert.equal(normalizeHex('#abcd'), '#aabbccdd'); + assert.equal(normalizeHex('#0078d4AA'), '#0078d4aa'); + assert.equal(normalizeHex('red'), null); + assert.equal(normalizeHex(undefined), null); + }); + + it('takes the innermost scope of a selector and skips exclusions', () => { + assert.equal(ruleToken('source.js meta.function entity.name.function'), 'entity.name.function'); + assert.equal(ruleToken('-comment'), null); + assert.equal(ruleToken(''), null); + }); + + it('builds a Monaco theme with default colours, TextMate rules and Monarch aliases', () => { + const theme = toMonacoTheme(THEME); + assert.equal(theme.base, 'vs-dark'); + assert.equal(theme.inherit, true); + assert.deepEqual(theme.rules.find((rule) => rule.token === ''), { token: '', foreground: 'dddddd', background: '1e1e1e' }); + assert.deepEqual(theme.rules.find((rule) => rule.token === 'comment'), { token: 'comment', foreground: '6a9955', fontStyle: 'italic' }); + assert.ok(theme.rules.some((rule) => rule.token === 'keyword.control' && rule.foreground === 'c586c0')); + assert.ok(theme.rules.some((rule) => rule.token === 'number' && rule.foreground === 'b5cea8'), 'constant.numeric also colours Monarch numbers'); + assert.ok(theme.rules.some((rule) => rule.token === 'function' && rule.foreground === 'dcdcaa')); + assert.equal(theme.rules.some((rule) => rule.token === 'string'), false, 'a rule with no settings is dropped'); + assert.equal(theme.colors['activityBar.background'], undefined, 'invalid colours are dropped'); + assert.equal(theme.colors['editor.foreground'], '#dddddd'); + }); + + it('maps theme colours onto the workbench tokens and --vscode-* variables', () => { + const vars = workbenchVariables(THEME); + assert.equal(vars['--editor'], '#1e1e1e'); + assert.equal(vars['--panel'], '#252526'); + assert.equal(vars['--chrome'], '#252526', 'falls through an invalid activityBar colour to the side bar'); + assert.equal(vars['--status'], '#007acc'); + assert.equal(vars['--accent'], '#0078d4aa'); + assert.equal(vars['--vscode-editor-background'], '#1e1e1e'); + assert.equal(vars['--vscode-activityBar-background'], undefined); + }); +}); + +describe('languages from extensions (#258)', () => { + const lang = (id: string, extra: Partial<{ extensions: string[]; filenames: string[]; filenamePatterns: string[]; firstLine: string; configuration: unknown }> = {}) => ({ + id, extensionId: 'acme.kit', aliases: [], extensions: [], filenames: [], filenamePatterns: [], firstLine: null, mimetypes: [], configuration: null, ...extra, + }); + + it('merges the entries of one language id', () => { + const merged = mergeLanguages([lang('toml', { extensions: ['.toml'] }), lang('toml', { extensions: ['.toml', '.tml'], filenames: ['Cargo.lock'], configuration: { a: 1 } })]); + assert.equal(merged.length, 1); + assert.deepEqual(merged[0]?.entry.extensions, ['.toml', '.tml']); + assert.deepEqual(merged[0]?.configuration, { a: 1 }); + }); + + it('detects a file\'s language by name, longest extension, then pattern', () => { + const entries = [{ id: 'yaml', extensions: ['.yml'] }, { id: 'docker-compose', extensions: ['.compose.yml'] }, { id: 'make', filenames: ['Makefile'] }, { id: 'env', filenamePatterns: ['.env.*'] }]; + assert.equal(detectLanguage('a.yml', entries), 'yaml'); + assert.equal(detectLanguage('x.compose.yml', entries), 'docker-compose'); + assert.equal(detectLanguage('makefile', entries), 'make'); + assert.equal(detectLanguage('.env.local', entries), 'env'); + assert.equal(detectLanguage('a.txt', entries), null); + }); + + it('turns language-configuration.json patterns into RegExps and drops invalid ones', () => { + assert.equal(safeRegExp('('), null); + assert.equal(safeRegExp({ pattern: '^\\s*#region', flags: 'i' })?.flags, 'i'); + const config = toLanguageConfiguration({ + comments: { lineComment: '#', blockComment: ['/*', '*/'] }, + brackets: [['{', '}'], ['bad']], + autoClosingPairs: [['(', ')'], { open: '"', close: '"', notIn: ['string'] }], + surroundingPairs: [['[', ']']], + wordPattern: '[a-z]+', + folding: { markers: { start: '^#region', end: '^#endregion' }, offSide: true }, + indentationRules: { increaseIndentPattern: ':\\s*$', decreaseIndentPattern: '^\\s*else' }, + onEnterRules: [{ beforeText: '^\\s*//', action: { indent: 'none', appendText: '// ' } }, { beforeText: '(', action: { indent: 'indent' } }], + }, { None: 0, Indent: 1, IndentOutdent: 2, Outdent: 3 }); + assert.deepEqual(config.comments, { lineComment: '#', blockComment: ['/*', '*/'] }); + assert.deepEqual(config.brackets, [['{', '}']]); + assert.deepEqual(config.autoClosingPairs, [{ open: '(', close: ')' }, { open: '"', close: '"', notIn: ['string'] }]); + assert.ok(config.wordPattern instanceof RegExp); + assert.equal((config.folding as { offSide: boolean }).offSide, true); + const rules = config.onEnterRules as { action: { indentAction: number; appendText?: string } }[]; + assert.equal(rules.length, 1, 'the rule whose pattern does not compile is dropped'); + assert.deepEqual(rules[0]?.action, { indentAction: 0, appendText: '// ' }); + }); + + it('picks the snippets of a language plus the global ones', () => { + const snippets = [{ extensionId: 'e', language: 'kit', name: 'a', prefixes: ['a'], body: 'a', description: '' }, { extensionId: 'e', language: '*', name: 'b', prefixes: ['b'], body: 'b', description: '' }, { extensionId: 'e', language: 'other', name: 'c', prefixes: ['c'], body: 'c', description: '' }]; + assert.deepEqual(snippetsFor(snippets, 'kit').map((s) => s.name), ['a', 'b']); + }); +}); + +describe('Extensions view model (#255)', () => { + const installed = (extra: Partial = {}): InstalledExtension => ({ + id: 'acme.demo', publisher: 'acme', name: 'demo', version: '1.2.0', displayName: 'Demo', description: 'Does demos', categories: ['Themes'], license: 'MIT', repository: null, icon: null, + hasCode: true, state: 'enabled', activation: 'inactive', engine: '^1.80.0', engineWarning: false, source: 'open-vsx', installedAt: 0, + contributes: { themes: [], iconThemes: [], languages: [], grammars: 0, snippets: 0, commands: [], views: [], settings: 0, keybindings: 0, localizations: [] }, supportsUntrusted: false, ...extra, + }); + const gallery = { id: 'acme.demo', namespace: 'acme', name: 'demo', version: '1.3.0', displayName: 'Demo', description: '', iconUrl: null, downloadCount: 0, averageRating: null, verified: false, timestamp: null }; + + it('formats download counts', () => { + assert.equal(compactCount(999), '999'); + assert.equal(compactCount(45_300), '45.3K'); + assert.equal(compactCount(1_000), '1K'); + assert.equal(compactCount(12_345_678), '12.3M'); + assert.equal(compactCount(250_000_000), '250M'); + }); + + it('labels the state of an installed extension', () => { + assert.equal(installedStateLabel(installed({ state: 'disabled' })), 'Disabled'); + assert.equal(installedStateLabel(installed({ state: 'restricted' })), 'Disabled in Restricted Mode'); + assert.equal(installedStateLabel(installed({ activation: 'active' })), 'Active'); + assert.equal(installedStateLabel(installed({ activation: 'failed' })), 'Failed to activate'); + assert.match(installedStateLabel(installed({ engineWarning: true })), /asks for VS Code/); + }); + + it('offers install, update or nothing', () => { + assert.equal(rowAction(gallery, undefined, false).kind, 'install'); + assert.equal(rowAction(gallery, installed(), false).kind, 'update'); + assert.equal(rowAction(gallery, installed({ version: '1.3.0' }), false).kind, 'installed'); + assert.equal(rowAction(gallery, undefined, true).kind, 'busy'); + }); + + it('filters the installed list', () => { + assert.equal(matchesInstalled(installed(), 'DEMO'), true); + assert.equal(matchesInstalled(installed(), 'themes'), true); + assert.equal(matchesInstalled(installed(), 'python'), false); + assert.equal(matchesInstalled(installed(), ' '), true); + }); +}); diff --git a/apps/ide/test/helpers/zip.ts b/apps/ide/test/helpers/zip.ts new file mode 100644 index 000000000..858d0a0d7 --- /dev/null +++ b/apps/ide/test/helpers/zip.ts @@ -0,0 +1,66 @@ +import { crc32, deflateRawSync } from 'node:zlib'; + +/** + * A minimal zip writer for the tests (#254): enough to build `.vsix` files, + * including malicious ones the real packager would never produce (`..` + * entries, absolute paths, symbolic links). + */ +export interface ZipEntry { + readonly name: string; + readonly data?: string | Buffer; + /** Unix mode in the external attributes (0o120777 for a symbolic link). */ + readonly mode?: number; +} + +export function zip(entries: readonly ZipEntry[]): Buffer { + const locals: Buffer[] = []; + const centrals: Buffer[] = []; + let offset = 0; + for (const entry of entries) { + const name = Buffer.from(entry.name, 'utf8'); + const raw = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data ?? '', 'utf8'); + const compressed = deflateRawSync(raw); + const crc = crc32(raw); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(0x0800, 6); + local.writeUInt16LE(8, 8); + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(compressed.length, 18); + local.writeUInt32LE(raw.length, 22); + local.writeUInt16LE(name.length, 26); + locals.push(local, name, compressed); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE((3 << 8) | 20, 4); + central.writeUInt16LE(20, 6); + central.writeUInt16LE(0x0800, 8); + central.writeUInt16LE(8, 10); + central.writeUInt32LE(crc, 16); + central.writeUInt32LE(compressed.length, 20); + central.writeUInt32LE(raw.length, 24); + central.writeUInt16LE(name.length, 28); + central.writeUInt32LE(((entry.mode ?? (entry.name.endsWith('/') ? 0o040755 : 0o100644)) << 16) >>> 0, 38); + central.writeUInt32LE(offset, 42); + centrals.push(central, name); + offset += 30 + name.length + compressed.length; + } + const centralSize = centrals.reduce((sum, part) => sum + part.length, 0); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(entries.length, 8); + end.writeUInt16LE(entries.length, 10); + end.writeUInt32LE(centralSize, 12); + end.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, ...centrals, end]); +} + +/** A `.vsix` of an extension: `files` are paths inside `extension/`. */ +export function vsix(manifest: Record, files: Record = {}): Buffer { + return zip([ + { name: '[Content_Types].xml', data: '' }, + { name: 'extension/package.json', data: JSON.stringify(manifest) }, + ...Object.entries(files).map(([name, data]) => ({ name: `extension/${name}`, data })), + ]); +} diff --git a/apps/ide/test/output.test.ts b/apps/ide/test/output.test.ts index b3591d40e..c12f567be 100644 --- a/apps/ide/test/output.test.ts +++ b/apps/ide/test/output.test.ts @@ -3,8 +3,8 @@ import assert from 'node:assert/strict'; import { channelForScope, isOutputChannel, MAX_LINE_LENGTH, OUTPUT_CHANNELS, OutputBuffer, outputLines, plainCoreText, redactSecrets } from '../src/shared/output.ts'; describe('output channels (#174)', () => { - it('lists five channels and recognises them', () => { - assert.deepEqual(OUTPUT_CHANNELS.map((channel) => channel.id), ['ide', 'core', 'python', 'servers', 'lsp']); + it('lists the channels and recognises them', () => { + assert.deepEqual(OUTPUT_CHANNELS.map((channel) => channel.id), ['ide', 'core', 'python', 'servers', 'lsp', 'extensions']); assert.equal(isOutputChannel('python'), true); assert.equal(isOutputChannel('terminal'), false); assert.equal(isOutputChannel(3), false); diff --git a/apps/ide/test/security.test.ts b/apps/ide/test/security.test.ts index 25b04c5b2..4cef0576e 100644 --- a/apps/ide/test/security.test.ts +++ b/apps/ide/test/security.test.ts @@ -55,7 +55,7 @@ describe('content security policy', () => { it('production allows only the app itself and never eval or inline scripts', () => { const csp = parseCsp(buildContentSecurityPolicy()); assert.deepEqual(csp.get('default-src'), ["'none'"]); - assert.deepEqual(csp.get('script-src'), ["'self'"]); + assert.deepEqual(csp.get('script-src'), ["'self'", "'wasm-unsafe-eval'"]); // Monaco (#14) injects