diff --git a/.gitignore b/.gitignore index ca1ab5c..c60edd2 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ src-tauri/browser-engine/ # Temporary runtime staging trees (normally removed automatically) src-tauri/.browser-stage-*/ +/packages/plugin-sdk/dist/ diff --git a/docs/completion.md b/docs/completion.md index 8760c5d..38c46f0 100644 --- a/docs/completion.md +++ b/docs/completion.md @@ -5,7 +5,7 @@ `api.completion` (`version: 1`) lets plugins show autocomplete in RuneStone editors and in their own text fields, and supply the suggestions. `api.completion` is optional. Older hosts do not have it, and `transport` can be absent. Make sure that a member exists before you call it. -The types are in `src/lib/completion/contracts.ts`. +The SDK type is `CompletionApi`. See [Install the SDK](plugin-development.md#install-the-sdk). | Member | Contract | | --- | --- | diff --git a/docs/development.md b/docs/development.md index 6346dbe..4b98b8a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -85,7 +85,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command | `formulas/` | Table formulas: the parser and evaluator (`engine.ts`), the rendered results, the formula help, and the `tableFormulas` setting (`index.ts`) | | `workspace/` | Tauri wrappers, document buffers, the note index and backlinks, paths, templates, and tab transfer (`tabTransfer.ts`) | | `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) | -| `plugins/` | The plugin runtime, the SDK types (`sdk.ts`), and Settings → Plug-ins | +| `plugins/` | The plugin runtime, the host types (`sdk.ts`, which also exports the SDK types), and Settings → Plug-ins | | `browser/` | The interface of the built-in browser | | `completion/`, `git/` | Contracts and services that plugins use | | `theme/` | Appearance settings, palettes, and the theme tokens (`tokens.css`) | @@ -97,6 +97,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command | Folder | Content | | --- | --- | | `browser-runtime/` | The browser engine, its tests, filter lists, and third-party notices | +| `packages/plugin-sdk/` | The plugin SDK `@runestone/plugin-sdk`. See [Plugin SDK](#plugin-sdk). | | `tests/unit//` | Unit tests (`*.spec.ts`) that run in Node | | `tests/smoke//` | Browser smoke tests (`*.smoke.mjs`) and their shared harness in `_harness/` | | `tests/native/` | Tests that attach to a running desktop app | @@ -169,7 +170,7 @@ Run these commands from the repository folder. They do not need an installer. | Command | Checks | | --- | --- | -| `pnpm check` | Svelte and TypeScript types of the app, then of the unit tests (`tests/tsconfig.json`) | +| `pnpm check` | Svelte and TypeScript types of the app, the unit tests (`tests/tsconfig.json`), the plugin SDK, and the example plugin | | `pnpm test` | Unit tests in `tests/unit/` | | `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust unit tests | | `pnpm smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). | @@ -184,6 +185,23 @@ Some tests need files from outside this repository. Without those files, the tes - `tests/unit/release/installerVersion.spec.ts` needs the NSIS compiler that the Tauri CLI downloads on Windows. - The Rust terminal tests start the real shells on the computer. +## Plugin SDK + +The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types. +The host imports it with relative paths in `src/lib/plugins/sdk.ts`, `src/lib/ui/actionIcons.ts`, and `src/lib/ui/tooltip.ts`. +Change a public type in the SDK, not in the host. Keep host-only types, such as the native transports, in `src/lib/plugins/sdk.ts`. +The menu types in `src/lib/ui/actionMenu.ts` and `src/lib/ui/managedActionMenu.ts` are the exception. The Terminal plugin keeps copies of these two files, and `pnpm check:menus` compares them. +`tests/unit/sdk/features.spec.ts` makes sure that their types and the SDK menu types are the same. +The SDK source must not import host files. It must use only TypeScript syntax that Node.js can remove, because the unit tests load it directly. + +| Command | Result | +| --- | --- | +| `pnpm sdk:build` | Compiles the SDK into `packages/plugin-sdk/dist/` with declaration files. The folder is outside Git. | +| `pnpm release:sdk --version [--dry-run]` | Builds the SDK, then commits and tags it in a local clone of the public repository. See [SDK releases](releases.md#sdk-releases). | + +`pnpm check` type checks the SDK with `packages/plugin-sdk/tsconfig.json` and the example plugin with `fixtures/plugins/tsconfig.json`. +`pnpm test` runs the SDK tests in `tests/unit/sdk/` and the release script tests in `tests/unit/release/releaseSdk.spec.ts`. + ## Browser smoke tests Smoke tests run the real interface in headless Chromium with a mock of the desktop host. diff --git a/docs/menu-surfaces.json b/docs/menu-surfaces.json index 5f5c40f..37ff720 100644 --- a/docs/menu-surfaces.json +++ b/docs/menu-surfaces.json @@ -145,7 +145,7 @@ "design": "Shared action menu", "check": "tests/smoke/menus/consistency.smoke.mjs" }, - "RuneStone/src/lib/plugins/sdk.ts": { + "RuneStone/packages/plugin-sdk/src/api.ts": { "counts": { "action": 1 }, diff --git a/docs/plugin-development.md b/docs/plugin-development.md index 7d07ff4..e76454f 100644 --- a/docs/plugin-development.md +++ b/docs/plugin-development.md @@ -4,6 +4,7 @@ This reference gives the package contract, the build procedure, and the API for RuneStone plugin authors. +- [Install the SDK](#install-the-sdk) - [Package contract](#package-contract) - [Build and package a plugin](#build-and-package-a-plugin) - [Build examples](#build-examples) @@ -16,11 +17,37 @@ This reference gives the package contract, the build procedure, and the API for - [Git API](#git-api) - [Background API](#background-api) +## Install the SDK + +The plugin SDK `@runestone/plugin-sdk` gives the API types, the feature checks, and the RuneStone icons and tooltip. +Install it in each plugin project from a release tag of its public repository. The SDK is not on the npm registry. + +```sh +pnpm add -D "git+https://git.knottywyvern.com/kwyvern/RuneStone_Plugin_SDK.git#v0.1.0" +``` + +- The repository is public. The installation needs no access token and no `.npmrc` file. +- Always give a tag. To change the SDK version, change the tag in `package.json`. +- Bundle the SDK helpers into the entry module. A type-only import adds no code. +- Do not copy RuneStone source files into a plugin, and do not import them from a RuneStone checkout. Use the SDK types and the host APIs. + +| SDK import | Contents | +| --- | --- | +| `@runestone/plugin-sdk` | `PluginApi` and its members, `PluginManifest`, `API_VERSION`, and the [feature checks](#compatibility) | +| `@runestone/plugin-sdk/icons` | `actionIcons` and `actionIcon(name)`. See [Commands](#commands). | +| `@runestone/plugin-sdk/tooltip` | `attachTooltip(element, label)`, the tooltip of RuneStone controls | + +For menus, use `api.ui.showActionMenu`. See [Menus](#menus). +The SDK source is `packages/plugin-sdk/` in this repository. For its versions and releases, see [SDK releases](releases.md#sdk-releases). +The [SDK README](../packages/plugin-sdk/README.md) has a minimal plugin in TypeScript. + +Example: `fixtures/plugins/workspace-overview/main.js` uses JSDoc types from the SDK and needs no compile step. `pnpm check` checks it with `fixtures/plugins/tsconfig.json`. + ## Package contract A plugin is one standard `.zip` file with `plugin.json` at the archive root. All plugins use the same package format and the same install, enable, disable, and removal lifecycle. -The interface types are in `src/lib/plugins/sdk.ts`. +The manifest type is `PluginManifest` in the [SDK](#install-the-sdk). ```json { @@ -184,11 +211,18 @@ export function activate(api) { Members marked optional can be absent on older RuneStone hosts. Before you call an optional member, make sure that it exists. If the plugin cannot work without it, show an error that tells the user to update RuneStone. +The SDK feature checks do this. Their error names each missing feature and tells the user to update RuneStone. -```js -if (!api.workspace.readBytes) throw new Error("Update RuneStone to use this plugin."); +```ts +import { hasFeature, requireFeature, requireFeatures } from "@runestone/plugin-sdk"; + +requireFeatures(api, ["pty", "workspace.readBytes"]); +const pty = requireFeature(api, "pty"); +if (hasFeature(api, "settings.subscribe")) watchSettings(); ``` +Without the SDK, examine the member directly: `if (!api.workspace.readBytes) throw new Error("Update RuneStone to use this plugin.");` + Older hosts ignore unknown fields in objects that you pass to the host, such as a view `icon` or `launch` handler. ### Activation and cleanup @@ -248,7 +282,7 @@ api.registerCommand({ id: "next", title: "Next image", icon: "skip-forward", run | `title` | Required text. | | `run` | Required function. Can return a promise. | | `category` | `"action"` (default) adds the command to the **Commands** menu. `"open"` adds it to the **Plug-in views** menu. | -| `icon` | Optional. A name from `src/lib/ui/actionIcons.ts`, such as `play`, `pause`, `skip-forward`, or `refresh`, or a view icon name. | +| `icon` | Optional. An `ActionIcon` name from the SDK, such as `play`, `pause`, `skip-forward`, or `refresh`, or a view icon name. | Give each command a recognizable icon. @@ -298,7 +332,7 @@ RuneStone translates only its own interface. It does not translate plugin text o ### Menus `ui.showActionMenu({ x, y, items, label?, parent? })` opens the shared action menu at a screen position. It returns `{ close() }`. -Each item is `{ label, icon?, shortcut?, run?, children?, disabled?, checked?, radio?, title? }` or `{ separator: true }`. The type is `ActionMenuItem` in `src/lib/ui/actionMenu.ts`. +Each item is `{ label, icon?, shortcut?, run?, children?, disabled?, checked?, radio?, title? }` or `{ separator: true }`. The SDK types are `ActionMenuItem` and `ActionMenuOptions`. The menu closes on selection, outside click, resize, window blur, scroll, and plugin shutdown. Use this menu instead of a custom menu. See the [interface design reference](ui-design.md). @@ -347,7 +381,7 @@ In `readMany`, one failed file does not stop the other reads. More than 64 paths ### Contributions -`contribute(key, value)` registers a host feature. The types are in `src/lib/plugins/contracts.ts`. +`contribute(key, value)` registers a host feature. The SDK type is `Contributions`. Only one enabled plugin can own each key. The host removes contributions before cleanup starts. | Key | Purpose | Owner | @@ -382,7 +416,7 @@ Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That ## Terminal API -`api.pty` (`version: 1`) starts shells in pseudo terminals. The types are `PtyApi` and `PtySession` in `src/lib/plugins/sdk.ts`. +`api.pty` (`version: 1`) starts shells in pseudo terminals. The SDK types are `PtyApi` and `PtySession`. | Member | Contract | | --- | --- | @@ -447,7 +481,7 @@ Make the data of a service a documented contract of the provider. Give its name, ## Git API `api.git` gives Git operations for the active workspace of the window. The host runs the `git` command, one operation at a time. -The types are in `src/lib/git/contracts.ts`. Every method checks for plugin shutdown first. +The SDK type is `GitApi`. Every method checks for plugin shutdown first. | Method | Contract | | --- | --- | diff --git a/docs/releases.md b/docs/releases.md index 56f3a60..420b669 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -30,6 +30,7 @@ Development servers, test runs, and intermediate compilation output are not buil | --- | --- | | RuneStone | `package.json`, `src-tauri/tauri.conf.json`, the package version and `[package.metadata.runestone]` in `src-tauri/Cargo.toml`, and the `runestone` entry in `src-tauri/Cargo.lock` | | Plugin | `plugin.json`, the project `package.json`, and any build metadata | +| Plugin SDK | `packages/plugin-sdk/package.json`. See [SDK releases](#sdk-releases). | On Windows, `pnpm build:installer --version ` sets the RuneStone fields when the installer is complete. If the build fails, the fields keep the previous version. See [Build the Windows installer](builds.md#build-the-windows-installer). @@ -147,3 +148,53 @@ Gitea link installation needs these conditions: For download limits, credential handling, and redirects, see [Gitea downloads](plugin-host.md#gitea-downloads). For GitHub publication steps, see [GitHub's release instructions](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository). + +## SDK releases + +The plugin SDK `@runestone/plugin-sdk` has its own version, in `packages/plugin-sdk/package.json`. The first release is `0.1.0`. +The [version rules](#versions) and the [hotfix rules](#hotfix-versions) apply. +An SDK release is a commit and a tag in the public SDK repository. It is not a ZIP or an installer. +`pnpm sdk:build` output in `packages/plugin-sdk/dist/` is compilation output, not a release. + +The source stays in this repository. The public repository is [RuneStone_Plugin_SDK](https://git.knottywyvern.com/kwyvern/RuneStone_Plugin_SDK). +It holds only the released files: `dist/`, `package.json`, `README.md`, `LICENSE`, and `NOTICE`. +Plugin authors install the SDK from a tag of that repository. See [Install the SDK](plugin-development.md#install-the-sdk). + +### Prepare the clone + +Do these steps one time. + +1. On the Gitea server, create the public repository `kwyvern/RuneStone_Plugin_SDK`. It can be empty. +2. Clone it beside the RuneStone repository, as `RuneStone_Plugin_SDK`. + For a different folder, set `RUNESTONE_SDK_REPO` to the clone. + Without that variable, the script uses `RuneStone_Plugin_SDK` in the `RUNESTONE_PLUGIN_REPOS` folder, or else in the parent folder of RuneStone. +3. Set the Git user name and email in the clone, if your global Git configuration does not have them. + +### Release the SDK + +1. Commit the SDK changes in RuneStone. Run `pnpm check` and `pnpm test`. +2. In the clone, get the latest commits and tags: `git pull --tags`. +3. Run `pnpm release:sdk --version --dry-run`. Read the plan. +4. Run `pnpm release:sdk --version `. +5. Run the push commands that the script prints. The script never pushes. +6. In RuneStone, commit the new version in `packages/plugin-sdk/package.json`. +7. Install the tag in a plugin project, build the plugin, and test it in RuneStone. + +The script builds the SDK, then replaces the released files in the clone. It commits them with the RuneStone commit in the message. +Then it creates the annotated tag `v`. +The new version goes into `packages/plugin-sdk/package.json` only after the tag exists. +If a step fails, the script restores that version field. It also resets the clone to its commit before the attempt. + +The script stops before it changes a file in these conditions: + +| Condition | Action | +| --- | --- | +| The version is not greater than the version in `packages/plugin-sdk/package.json` or in the clone | Give a greater version. | +| `packages/plugin-sdk/` has no `LICENSE` or `README.md` file | Add the file. The SDK uses the Apache License 2.0. | +| `packages/plugin-sdk/` has changes that are not committed | Commit them, so that the release has a source commit. | +| The clone is missing or is not the root of a Git repository | Clone the public repository, or set `RUNESTONE_SDK_REPO`. | +| The clone has changes, or it is not on a branch | Commit or remove the changes. Check out the release branch. | +| The tag `v` exists in the clone | Give a new version. Never move or replace a published tag. | + +The tag is the release. Do not attach files to a repository release for the SDK, and do not put SDK files in `releases/`. +To move the SDK to another service, or to mirror it, push the same commits and tags. Plugin authors then change only the repository URL. diff --git a/fixtures/plugins/tsconfig.json b/fixtures/plugins/tsconfig.json new file mode 100644 index 0000000..eb2b20e --- /dev/null +++ b/fixtures/plugins/tsconfig.json @@ -0,0 +1,22 @@ +{ + // Type checks the example plugins against the SDK source, as a plugin author checks against the installed package. + // `pnpm check` runs it. The file is outside the plugin folders, so no package contains it. + "compilerOptions": { + "target": "es2022", + "module": "esnext", + "moduleResolution": "bundler", + "lib": ["es2022", "dom", "dom.iterable"], + "types": [], + "allowJs": true, + "checkJs": true, + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "skipLibCheck": true, + "paths": { + "@runestone/plugin-sdk": ["../../packages/plugin-sdk/src/index.ts"], + "@runestone/plugin-sdk/*": ["../../packages/plugin-sdk/src/*.ts"] + } + }, + "include": ["*/**/*.js"] +} diff --git a/fixtures/plugins/workspace-overview/main.js b/fixtures/plugins/workspace-overview/main.js index acc5ecb..831e4e7 100644 --- a/fixtures/plugins/workspace-overview/main.js +++ b/fixtures/plugins/workspace-overview/main.js @@ -1,8 +1,14 @@ +// @ts-check +// JSDoc types from the plugin SDK. `pnpm check` checks this file with fixtures/plugins/tsconfig.json. +/** @import { PluginApi } from "@runestone/plugin-sdk" */ + +/** @param {PluginApi} api */ export function activate(api) { api.registerCommand({ id: "show-overview", title: "Show workspace overview", run: () => api.openView("overview") }); api.registerView({ id: "overview", title: "Workspace overview", + /** @param {HTMLElement} container */ async mount(container) { const status = document.createElement("p"); status.textContent = "Loading workspace files…"; diff --git a/package.json b/package.json index 79356b9..45a30b2 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "build:installer": "node scripts/buildInstaller.mjs", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json && tsc -p packages/plugin-sdk/tsconfig.json --noEmit && tsc -p fixtures/plugins/tsconfig.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "check:menus": "node scripts/menuSurfaceAudit.mjs", "tauri": "tauri", @@ -19,7 +19,9 @@ "browser:test": "npm --prefix browser-runtime test", "browser:test:engine": "npm --prefix browser-runtime run test:browser", "browser:stage": "npm --prefix browser-runtime run stage:host", - "package:plugin": "node scripts/packagePlugin.mjs" + "package:plugin": "node scripts/packagePlugin.mjs", + "sdk:build": "node scripts/buildSdk.mjs", + "release:sdk": "node scripts/releaseSdk.mjs" }, "license": "MIT", "dependencies": { diff --git a/packages/plugin-sdk/LICENSE b/packages/plugin-sdk/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/packages/plugin-sdk/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/plugin-sdk/NOTICE b/packages/plugin-sdk/NOTICE new file mode 100644 index 0000000..e4f013d --- /dev/null +++ b/packages/plugin-sdk/NOTICE @@ -0,0 +1,2 @@ +RuneStone Plugin SDK +Copyright 2026 Knotty Wyvern diff --git a/packages/plugin-sdk/README.md b/packages/plugin-sdk/README.md new file mode 100644 index 0000000..631152f --- /dev/null +++ b/packages/plugin-sdk/README.md @@ -0,0 +1,142 @@ +# RuneStone Plugin SDK + +`@runestone/plugin-sdk` gives TypeScript types and small helpers for [RuneStone](https://git.knottywyvern.com/kwyvern/RuneStone) plugins. +RuneStone is a desktop workspace for Markdown notes, code, and project work. Plugins add views, commands, and document editors to it. + +The SDK contains: + +- The types of the plugin API: `PluginApi` and its members, the `plugin.json` manifest, commands, views, document types, menus, and contributions +- `API_VERSION`, the plugin API version that the SDK describes +- Feature checks for API members that older RuneStone versions do not have +- The RuneStone action icons and the tooltip helper, as DOM functions + +The SDK does not run plugins and does not call RuneStone. RuneStone gives the `api` object to your plugin at activation. + +## Install + +Install the SDK from a release tag of its Git repository. The SDK is not on the npm registry. + +```sh +pnpm add -D "git+https://git.knottywyvern.com/kwyvern/RuneStone_Plugin_SDK.git#v0.1.0" +``` + +The result in `package.json`: + +```json +{ + "devDependencies": { + "@runestone/plugin-sdk": "git+https://git.knottywyvern.com/kwyvern/RuneStone_Plugin_SDK.git#v0.1.0" + } +} +``` + +The repository is public, so you need no access token and no `.npmrc` file. npm and Yarn accept the same URL. +Always give a tag. Without a tag, the package manager uses the latest commit, and your build can change without notice. +The package contains compiled JavaScript and declaration files, so the installation runs no build step. + +Use TypeScript 5.0 or later, with `moduleResolution` set to `bundler`, `node16`, or `nodenext`. Include the `DOM` library. + +## Write a plugin + +A plugin is one JavaScript module that exports `activate(api)`. This example adds a view and a command that opens it. + +```ts +import type { PluginApi } from "@runestone/plugin-sdk"; + +export function activate(api: PluginApi) { + api.registerView({ + id: "hello", + title: "Hello", + mount(container) { + const text = document.createElement("p"); + text.textContent = "Hello from a RuneStone plugin."; + container.append(text); + return () => text.remove(); + }, + }); + api.registerCommand({ id: "show-hello", title: "Show hello", icon: "puzzle", run: () => api.openView("hello") }); +} +``` + +Compile the module with a bundler, so the entry file contains the SDK helpers that it uses. RuneStone loads the entry from a Blob URL, so imports from `node_modules` do not resolve at run time. +Then make the plugin ZIP. See [Build and package a plugin](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md#build-and-package-a-plugin). + +A type-only import, such as `import type { PluginApi }`, adds no code to the bundle. + +## Check for features + +Members marked optional in `PluginApi` can be absent on older RuneStone versions. Examples are `api.pty`, `api.files`, and `api.workspace.readBytes`. +Make sure that a member exists before you use it. + +```ts +import { hasFeature, requireFeature, requireFeatures, type PluginApi } from "@runestone/plugin-sdk"; + +export function activate(api: PluginApi) { + // Stop the activation with one message that names each missing feature. + requireFeatures(api, ["pty", "workspace.readOptional"]); + const pty = requireFeature(api, "pty"); + + // Hide a control when the feature is absent. + if (hasFeature(api, "ui.showActionMenu")) showMenuButton(); +} +``` + +| Function | Result | +| --- | --- | +| `hasFeature(api, feature)` | `true` when RuneStone gives the member | +| `missingFeatures(api, features)` | The features of the list that RuneStone does not give | +| `requireFeature(api, feature)` | The member, with its type. A function stays bound to its object. | +| `requireFeatures(api, features)` | Nothing. Throws one error for all missing features. | + +When a feature is missing, `requireFeature` and `requireFeatures` throw a `MissingFeatureError`. Its `features` property lists the feature names. +Its message names each feature and its API path, and tells the user to update RuneStone. For example: +`This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature.` + +`pluginFeatures` lists all the feature names. The checks examine only whether the member exists. + +## Icons and tooltips + +RuneStone has no API for icons or tooltips. The SDK gives the host code as DOM functions, so your controls look and behave like the RuneStone controls. + +```ts +import { actionIcon } from "@runestone/plugin-sdk/icons"; +import { attachTooltip } from "@runestone/plugin-sdk/tooltip"; + +const button = document.createElement("button"); +button.setAttribute("aria-label", "Refresh"); +button.append(actionIcon("refresh")); +const removeTooltip = attachTooltip(button, () => "Refresh"); +``` + +| Import | Contents | +| --- | --- | +| `@runestone/plugin-sdk/icons` | `actionIcons`, the SVG markup of each icon. `actionIcon(name)` makes an SVG element with the `action-icon` class. | +| `@runestone/plugin-sdk/tooltip` | `attachTooltip(element, label)` shows a tooltip on hover and keyboard focus. It returns a cleanup function. | + +RuneStone styles the `action-icon` and `rs-tooltip` classes. Call the cleanup function of each tooltip when your view closes. + +For menus, call `api.ui.showActionMenu`. RuneStone draws the menu, so the SDK contains only its types: `ActionMenuItem` and `ActionMenuOptions`. + +## Versions + +The SDK has its own version number in the form `zz.yy.xx`, for example `0.1.0`. Each release has the tag `v`. +A hotfix adds a lowercase letter to the version, for example `0.1.0a`. + +`API_VERSION` is the `apiVersion` value of `plugin.json`. The SDK version and the RuneStone version are different numbers. +A new SDK release can add types for new RuneStone features. Use the feature checks for features that older RuneStone versions do not have. + +## Documentation and help + +- [Plugin development reference](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugin-development.md): the package format, the API, and the build procedure +- [Completion API](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/completion.md) +- [Install and manage plugins](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/plugins.md) +- [Release policy](https://git.knottywyvern.com/kwyvern/RuneStone/src/branch/master/docs/releases.md#sdk-releases) + +The SDK source is in the `packages/plugin-sdk` folder of the [RuneStone repository](https://git.knottywyvern.com/kwyvern/RuneStone). Report problems there. +This repository holds only the released files. + +Knotty Wyvern maintains RuneStone and the SDK. + +## License + +Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). diff --git a/packages/plugin-sdk/package.json b/packages/plugin-sdk/package.json new file mode 100644 index 0000000..64ca729 --- /dev/null +++ b/packages/plugin-sdk/package.json @@ -0,0 +1,31 @@ +{ + "name": "@runestone/plugin-sdk", + "version": "0.0.0", + "private": true, + "description": "Types and helpers for RuneStone plugins", + "license": "Apache-2.0", + "type": "module", + "sideEffects": false, + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./icons": { + "types": "./dist/icons.d.ts", + "default": "./dist/icons.js" + }, + "./tooltip": { + "types": "./dist/tooltip.d.ts", + "default": "./dist/tooltip.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist", + "README.md", + "LICENSE", + "NOTICE" + ] +} diff --git a/packages/plugin-sdk/src/api.ts b/packages/plugin-sdk/src/api.ts new file mode 100644 index 0000000..e74ca9e --- /dev/null +++ b/packages/plugin-sdk/src/api.ts @@ -0,0 +1,122 @@ +import type { BackgroundApi } from "./backgrounds.ts"; +import type { CompletionApi } from "./completion.ts"; +import type { Contributions } from "./contributions.ts"; +import type { GitApi } from "./git.ts"; +import type { ActionIcon } from "./icons.ts"; +import type { ActionMenuItem, ActionMenuOptions } from "./menu.ts"; + +/** Plugin API version 1. A compiled plugin exports `activate(api)`. */ +export type Dispose = () => void | Promise; +export interface PluginCommand { id: string; title: string; icon?: ActionIcon | PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise } +export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; launch?: () => void | Promise; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise } +export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string } +export interface PluginDocumentContext { id: string; path: string } +export interface PluginDocumentType { + id: string; + title: string; + icon?: "kanban" | "file"; + extensions: string[]; + content?: "text" | "binary"; + identify(path: string, source: string): { id: string } | null; + create?: { label: string; defaultName: string; extension: string; contents(): string }; + mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise; +} +export interface PtyProfile { id: string; title: string; kind: string } +export interface PtyOpenOptions { + /** The workspace root of the window. The host rejects the request when the workspace changed. */ + cwd: string; + cols: number; + rows: number; + profile?: string; + /** A start folder other than the workspace root. */ + directory?: string; + /** Receives raw terminal output. UTF-8 characters can be split between two calls. */ + onData(data: Uint8Array): void; + onExit?(code: number | null): void; +} +export interface PtySession { + readonly id: string; + write(data: string): Promise; + resize(cols: number, rows: number): Promise; + /** Stops the shell. Repeated calls return the same promise. */ + close(): Promise; +} +/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */ +export interface PtyApi { + readonly version: 1; + profiles(): Promise; + open(options: PtyOpenOptions): Promise; + openWindow(): Promise; + dictation(): Promise; +} +export interface FolderGrant { id: string; path: string; name: string } +export interface FolderEntry { name: string; size: number } +/** Folders outside the workspace that the user granted to this plugin. */ +export interface FilesApi { + readonly version: 1; + chooseFolder(options?: { title?: string }): Promise; + pictureFolder(name: string): Promise; + grants(): Promise; + revoke(grant: string): Promise; + list(grant: string): Promise; + readBytes(grant: string, name: string): Promise; + readSidecar(grant: string, name: string): Promise; + writeSidecar(grant: string, name: string, contents: string, expected: string | null): Promise; +} +export type ServiceMethods = Record unknown>; +/** Data that one plugin offers to other plugins in the same window. */ +export interface ServicesApi { + readonly version: 1; + provide(name: string, methods: ServiceMethods): { notify(): void; dispose(): void }; + get(plugin: string, name: string): Record Promise> | null; + subscribe(listener: (plugin: string, name: string) => void): Dispose; +} +/** Files in the active workspace. All paths are relative to the workspace root. */ +export interface WorkspaceApi { + list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>; + listMarkdown?(): Promise; + read(path: string): Promise; + readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>; + readBytes?(path: string): Promise; + readOptional?(path: string): Promise; + create?(path: string, contents: string): Promise; + write(path: string, contents: string, expected: string): Promise; + subscribe?(listener: () => void): Dispose; +} +/** The saved JSON settings of the plugin. */ +export interface SettingsApi { read(): Promise; write(value: unknown): Promise; subscribe?(listener: () => void): Dispose } +/** The files in the plugin package. */ +export interface AssetsApi { read(path: string): Promise } +/** Interface parts that the host draws. */ +export interface UiApi { showActionMenu(options: ActionMenuOptions): { close(): void } } +export interface PluginApi { + pty?: PtyApi; + files?: FilesApi; + services?: ServicesApi; + backgrounds?: BackgroundApi; + ui?: UiApi; + git?: GitApi; + completion?: CompletionApi; + readonly id: string; + readonly signal: AbortSignal; + contribute(key: K, value: Contributions[K]): void; + registerCommand(command: PluginCommand): void; + registerView(view: PluginView): void; + registerTabDrop?(receive: (data: string) => void | Promise): void; + updateViewTitle?(id: string, title: string): void; + updateViewIcon?(id: string, image: string | null): void; + registerDocumentType(type: PluginDocumentType): void; + openDocument(path: string): Promise; + openFile?(path: string): Promise; + renameDocument?(document: PluginDocumentContext, name: string): Promise; + openView(id: string, options?: PluginViewOpenOptions): void; + closeView?(id: string): void; + replaceView?(currentId: string, nextId: string): void; + replaceDocumentWithView?(document: PluginDocumentContext, nextId: string): void; + onDispose(cleanup: Dispose): void; + workspace: WorkspaceApi; + settings: SettingsApi; + assets: AssetsApi; +} +/** The entry module of a plugin. */ +export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise } diff --git a/packages/plugin-sdk/src/backgrounds.ts b/packages/plugin-sdk/src/backgrounds.ts new file mode 100644 index 0000000..5dad9f0 --- /dev/null +++ b/packages/plugin-sdk/src/backgrounds.ts @@ -0,0 +1,24 @@ +/** Background image frames behind the RuneStone interface. */ +export interface BackgroundFrame { + url: string; + blurredUrl?: string; + overlay: number; + position: 'center' | 'top left' | 'top' | 'top right' | 'left' | 'right' | 'bottom left' | 'bottom' | 'bottom right'; + size: 'cover' | 'contain' | 'auto'; + previous?: Omit; + transitionMs?: number; +} + +/** The folder methods are deprecated. Use `FilesApi` folder grants in new code. */ +export interface BackgroundApi { + readonly version: 1; + chooseFolder(): Promise; + defaultFolder?(): Promise; + list(folder: string): Promise<{ name: string }[]>; + read(folder: string, name: string): Promise; + readImageSettings?(folder: string): Promise; + writeImageSettings?(folder: string, contents: string, expected: string | null): Promise; + set(target: string, frame: BackgroundFrame | null): void; + get(target: string): BackgroundFrame | null; + subscribe(listener: (target: string) => void): () => void; +} diff --git a/packages/plugin-sdk/src/completion.ts b/packages/plugin-sdk/src/completion.ts new file mode 100644 index 0000000..9c9c385 --- /dev/null +++ b/packages/plugin-sdk/src/completion.ts @@ -0,0 +1,59 @@ +/** Autocomplete types. See the completion API in the RuneStone documentation (`docs/completion.md`). */ +export type CompletionDispose = () => void; +export interface CompletionSnapshot { + documentId: string; + revision: string | number; + text: string; + caret: number; + selectionEnd: number; + focused: boolean; + composing?: boolean; + sensitive?: boolean; + readOnly?: boolean; + kind: "prose" | "code"; + language?: string; +} +export interface CompletionRequest { + surfaceId: string; + documentId: string; + revision: string | number; + prefix: string; + suffix: string; + kind: "prose" | "code"; + language: string; + manual: boolean; + signal: AbortSignal; +} +export interface CompletionProvider { + id: string; + delayMs?: number; + timeoutMs?: number; + complete(request: CompletionRequest, publish: (text: string) => void): Promise; +} +export interface CompletionSurface { + id: string; + snapshot(): CompletionSnapshot; + preview(text: string | null): void; + insert(text: string, expected: CompletionSnapshot): boolean; +} +export interface CompletionHandle { + changed(): void; + request(): void; + accept(word?: boolean): boolean; + dismiss(): boolean; + dispose(): void; +} +export interface CompletionTransportRequest { + endpoint: string; + route: "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate"; + body?: string; + timeoutMs?: number; +} +export interface CompletionApi { + version: 1; + registerProvider(provider: CompletionProvider): CompletionDispose; + registerSurface(surface: CompletionSurface): CompletionHandle; + registerInput(element: HTMLInputElement | HTMLTextAreaElement, options: { id: string; kind?: "prose" | "code"; sensitive?: boolean }): CompletionHandle; + invalidate(): void; + transport?(request: CompletionTransportRequest, signal: AbortSignal, onLine: (line: string) => void): Promise; +} diff --git a/packages/plugin-sdk/src/contributions.ts b/packages/plugin-sdk/src/contributions.ts new file mode 100644 index 0000000..b60b2ed --- /dev/null +++ b/packages/plugin-sdk/src/contributions.ts @@ -0,0 +1,28 @@ +import type { Dispose } from "./api.ts"; +import type { GitLineInfo } from "./git.ts"; + +export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories"; +export interface TerminalProps { + cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean; + onClose: () => void; onMaximize?: () => void; activeFile?: boolean; + onRunFile?: () => Promise; getSelection?: () => string; onConfigureTasks?: () => Promise; +} +export interface TerminalMount { + update(props: TerminalProps): void; + command(action: Exclude): void | Promise; + dispose: Dispose; +} +/** Host features that `api.contribute(key, value)` registers. Only one enabled plugin can own each key. */ +export interface Contributions { + git: { blame(path: string, line: number): Promise }; + browser: { + newTab?(): Promise; + mountSettings(container: HTMLElement): Dispose | Promise; + mountBookmarks(container: HTMLElement): Dispose | Promise; + open(url: string): Promise; + }; + terminal: { + mount(container: HTMLElement, props: TerminalProps): TerminalMount; + shortcut(event: Pick): TerminalAction | null; + }; +} diff --git a/packages/plugin-sdk/src/features.ts b/packages/plugin-sdk/src/features.ts new file mode 100644 index 0000000..d6a6d97 --- /dev/null +++ b/packages/plugin-sdk/src/features.ts @@ -0,0 +1,130 @@ +import type { FilesApi, PluginApi, PtyApi, ServicesApi, SettingsApi, UiApi, WorkspaceApi } from "./api.ts"; +import type { BackgroundApi } from "./backgrounds.ts"; +import type { CompletionApi } from "./completion.ts"; +import type { GitApi } from "./git.ts"; + +/** + * The optional members of `PluginApi`, by path, and the type that `requireFeature` returns for each path. + * Older RuneStone hosts can omit these members. Required members, such as `workspace.read`, are not listed. + */ +export interface PluginFeatures { + pty: PtyApi; + files: FilesApi; + services: ServicesApi; + backgrounds: BackgroundApi; + git: GitApi; + "git.push": GitApi["push"]; + "git.pull": GitApi["pull"]; + "git.graph": GitApi["graph"]; + "git.commitDetails": GitApi["commitDetails"]; + "git.commitDiff": GitApi["commitDiff"]; + completion: CompletionApi; + "completion.transport": NonNullable; + "ui.showActionMenu": UiApi["showActionMenu"]; + registerTabDrop: NonNullable; + updateViewTitle: NonNullable; + updateViewIcon: NonNullable; + openFile: NonNullable; + renameDocument: NonNullable; + closeView: NonNullable; + replaceView: NonNullable; + replaceDocumentWithView: NonNullable; + "workspace.listMarkdown": NonNullable; + "workspace.readMany": NonNullable; + "workspace.readBytes": NonNullable; + "workspace.readOptional": NonNullable; + "workspace.create": NonNullable; + "workspace.subscribe": NonNullable; + "settings.subscribe": NonNullable; +} +export type PluginFeature = keyof PluginFeatures; + +const descriptions: { [K in PluginFeature]: string } = { + pty: "the terminal API", + files: "the folder grant API", + services: "the plugin service API", + backgrounds: "the background API", + git: "the Git API", + "git.push": "Git push", + "git.pull": "Git pull", + "git.graph": "the Git commit graph", + "git.commitDetails": "Git commit details", + "git.commitDiff": "Git commit diffs", + completion: "the completion API", + "completion.transport": "the completion model transport", + "ui.showActionMenu": "the shared action menu", + registerTabDrop: "tab drops from other windows", + updateViewTitle: "view title changes", + updateViewIcon: "view tab icons", + openFile: "opening files in the RuneStone editor", + renameDocument: "document renames", + closeView: "closing views", + replaceView: "view replacement", + replaceDocumentWithView: "replacing a document tab with a view", + "workspace.listMarkdown": "the Markdown file list", + "workspace.readMany": "reading many workspace files in one request", + "workspace.readBytes": "reading workspace files as bytes", + "workspace.readOptional": "reading optional workspace files", + "workspace.create": "creating workspace files", + "workspace.subscribe": "workspace change notifications", + "settings.subscribe": "settings change notifications", +}; + +/** All the feature paths that `hasFeature` and `requireFeature` accept. */ +export const pluginFeatures = Object.freeze(Object.keys(descriptions) as PluginFeature[]); + +/** A readable name of a feature, with its API path, for messages to users. */ +export function describeFeature(feature: PluginFeature): string { + if (!Object.hasOwn(descriptions, feature)) throw new TypeError(`Unknown plugin feature: ${String(feature)}`); + return `${descriptions[feature]} (api.${feature})`; +} + +/** The error that `requireFeature` and `requireFeatures` throw when the host does not have a feature. */ +export class MissingFeatureError extends Error { + readonly features: readonly PluginFeature[]; + constructor(features: readonly PluginFeature[]) { + const names = features.map(describeFeature); + super(`This plugin needs ${names.length > 1 ? names.slice(0, -1).join(", ") + " and " + names.at(-1) : names[0]}. Update RuneStone to a version that has ${names.length > 1 ? "these features" : "this feature"}.`); + this.name = "MissingFeatureError"; + this.features = Object.freeze([...features]); + } +} + +function lookup(api: PluginApi, feature: PluginFeature): { parent: unknown; value: unknown } { + describeFeature(feature); + let parent: unknown; + let value: unknown = api; + for (const key of feature.split(".")) { + parent = value; + value = parent !== null && typeof parent === "object" ? (parent as Record)[key] : undefined; + } + return { parent, value }; +} + +/** Returns `true` when the host gives this optional member of the plugin API. */ +export function hasFeature(api: PluginApi, feature: PluginFeature): boolean { + const { value } = lookup(api, feature); + return typeof value === "function" || (value !== null && typeof value === "object"); +} + +/** Returns the features in the list that the host does not give, in list order. */ +export function missingFeatures(api: PluginApi, features: readonly PluginFeature[]): PluginFeature[] { + return features.filter(feature => !hasFeature(api, feature)); +} + +/** + * Returns the member at the feature path, or throws a `MissingFeatureError` that tells the user to update RuneStone. + * A returned function stays bound to its parent object. + */ +export function requireFeature(api: PluginApi, feature: F): PluginFeatures[F] { + const { parent, value } = lookup(api, feature); + if (typeof value === "function") return value.bind(parent) as PluginFeatures[F]; + if (value !== null && typeof value === "object") return value as PluginFeatures[F]; + throw new MissingFeatureError([feature]); +} + +/** Throws one `MissingFeatureError` that names every missing feature in the list. */ +export function requireFeatures(api: PluginApi, features: readonly PluginFeature[]): void { + const missing = missingFeatures(api, features); + if (missing.length) throw new MissingFeatureError(missing); +} diff --git a/packages/plugin-sdk/src/git.ts b/packages/plugin-sdk/src/git.ts new file mode 100644 index 0000000..0a29c34 --- /dev/null +++ b/packages/plugin-sdk/src/git.ts @@ -0,0 +1,64 @@ +/** Git types. The host runs the `git` program for the active workspace. */ +export interface GitChange { + path: string; + originalPath?: string; + index: string; + worktree: string; +} + +export interface GitStatus { + available: boolean; + repository: boolean; + branch: string | null; + changes: GitChange[]; +} + +export interface GitLineInfo { + commit: string; + author: string; + /** The author date in ISO 8601 format. */ + date: string; + summary: string; +} + +/** Older hosts can have `git` without `push`, `pull`, `graph`, `commitDetails`, or `commitDiff`. Use `hasFeature` first. */ +export interface GitApi { + status(): Promise; + diff(path: string, staged: boolean): Promise; + stage(paths: string[]): Promise; + unstage(paths: string[]): Promise; + commit(message: string): Promise; + push(): Promise; + pull(): Promise; + graph(): Promise; + commitDetails(commit: string): Promise; + commitDiff(commit: string, path: string): Promise; + blame(path: string, line: number): Promise; +} + +export interface GitGraphCommit { + id: string; + parents: string[]; + refs: string[]; + summary: string; + author: string; + date: string; +} + +export interface GitGraph { + commits: GitGraphCommit[]; +} + +export interface GitCommitFile { + path: string; + originalPath?: string; + status: string; +} +export interface GitCommitDetails { + id: string; + parents: string[]; + author: string; + date: string; + message: string; + files: GitCommitFile[]; +} diff --git a/packages/plugin-sdk/src/icons.ts b/packages/plugin-sdk/src/icons.ts new file mode 100644 index 0000000..9fa1469 --- /dev/null +++ b/packages/plugin-sdk/src/icons.ts @@ -0,0 +1,95 @@ +// The action icons of RuneStone. Menus, commands, and plugin controls use the same artwork. +// Stroke icons share the same 24px grid and weight as the host icon buttons. +// The host styles the `action-icon` class: size, stroke, and color. Outside RuneStone, add your own style. +export const actionIcons = { + play: '', + pause: '', + 'skip-forward': '', + eye: '', + 'eye-off': '', + image: '', + settings: '', + archive: '', + save: '', + refresh: '', + 'arrow-left': '', + 'arrow-right': '', + terminal: '', + undo: '', + redo: '', + git: '', + globe: '', + puzzle: '', + 'split-right': '', + 'split-down': '', + kanban: '', + bookmark: '', + 'file-plus': '', + 'folder-plus': '', + + pin: '', + book: '', + folder: '', + rename: '', + 'zoom-in': '', + 'zoom-out': '', + close: '', + swap: '', + bullet: '', + number: '', + task: '', + heading: '', + quote: '', + table: '', + rule: '', + footnote: '', + cut: '', + copy: '', + paste: '', + 'paste-text': '', + format: '', + bold: '', + italic: '', + strike: '', + highlight: '', + code: '', + math: '', + comment: '', + clear: '', + left: '', + center: '', + right: '', + row: '', + column: '', + 'row-before': '', + 'row-after': '', + 'column-before': '', + 'column-after': '', + up: '', + down: '', + 'move-left': '', + 'move-right': '', + trash: '', + 'sort-asc': '', + 'sort-desc': '', + link: '', + external: '', + search: '', + filter: '', + extract: '', + select: '', + paragraph: '', + insert: '', + chevron: '', + plus: '', + grip: '', +} as const; +export type ActionIcon = keyof typeof actionIcons; + +/** Makes a new SVG element for an action icon. The element has `aria-hidden`, so give its control an accessible name. */ +export function actionIcon(name: ActionIcon): SVGSVGElement { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true"); + svg.classList.add("action-icon"); svg.innerHTML = actionIcons[name]; + return svg; +} diff --git a/packages/plugin-sdk/src/index.ts b/packages/plugin-sdk/src/index.ts new file mode 100644 index 0000000..59b7c37 --- /dev/null +++ b/packages/plugin-sdk/src/index.ts @@ -0,0 +1,11 @@ +// The public types and helpers of the RuneStone plugin API. +// The icon and tooltip helpers use the DOM. Import them from "@runestone/plugin-sdk/icons" and "@runestone/plugin-sdk/tooltip". +export type * from "./api.ts"; +export type * from "./backgrounds.ts"; +export type * from "./completion.ts"; +export type * from "./contributions.ts"; +export type * from "./git.ts"; +export type * from "./menu.ts"; +export type { ActionIcon } from "./icons.ts"; +export { API_VERSION, type PluginManifest } from "./manifest.ts"; +export { describeFeature, hasFeature, missingFeatures, MissingFeatureError, pluginFeatures, requireFeature, requireFeatures, type PluginFeature, type PluginFeatures } from "./features.ts"; diff --git a/packages/plugin-sdk/src/manifest.ts b/packages/plugin-sdk/src/manifest.ts new file mode 100644 index 0000000..ad5dbe3 --- /dev/null +++ b/packages/plugin-sdk/src/manifest.ts @@ -0,0 +1,8 @@ +/** The plugin API version that this SDK describes. It is the `apiVersion` value in `plugin.json`. */ +export const API_VERSION = 1; + +/** The contents of `plugin.json` at the root of a plugin ZIP. The host rejects other fields. */ +export interface PluginManifest { + schemaVersion: 1; id: string; name: string; author: string; description: string; + version: string; apiVersion: typeof API_VERSION; entry: string; access: "full-app"; +} diff --git a/packages/plugin-sdk/src/menu.ts b/packages/plugin-sdk/src/menu.ts new file mode 100644 index 0000000..fbfb425 --- /dev/null +++ b/packages/plugin-sdk/src/menu.ts @@ -0,0 +1,7 @@ +import type { ActionIcon } from "./icons.ts"; + +/** One row of the shared RuneStone action menu, or a separator. */ +export type ActionMenuItem = { label: string; icon?: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; checked?: boolean; radio?: boolean; title?: string } | { separator: true }; + +/** The options of `api.ui.showActionMenu`. `x` and `y` are viewport coordinates. */ +export type ActionMenuOptions = { x: number; y: number; items: ActionMenuItem[]; label?: string; parent?: HTMLElement }; diff --git a/packages/plugin-sdk/src/tooltip.ts b/packages/plugin-sdk/src/tooltip.ts new file mode 100644 index 0000000..8bdeda2 --- /dev/null +++ b/packages/plugin-sdk/src/tooltip.ts @@ -0,0 +1,52 @@ +/** + * A single themed tooltip for DOM controls, with hover and keyboard dismissal. + * The host styles the `rs-tooltip` class. Returns a cleanup function that removes the tooltip and its listeners. + */ +export function attachTooltip(target: HTMLElement, label: () => string) { + const tip = document.createElement('span'); + tip.className = 'rs-tooltip'; + tip.setAttribute('popover', 'manual'); + tip.setAttribute('role', 'tooltip'); + tip.id = `rs-tooltip-${crypto.randomUUID()}`; + document.body.append(tip); + let timer: ReturnType | undefined; + const previousDescription = target.getAttribute('aria-describedby'); + function hide() { + clearTimeout(timer); + if (tip.matches(':popover-open')) tip.hidePopover(); + if (previousDescription) target.setAttribute('aria-describedby', previousDescription); + else target.removeAttribute('aria-describedby'); + } + function show() { + clearTimeout(timer); + timer = setTimeout(() => { + if (!target.isConnected || !label()) return; + tip.textContent = label(); + tip.showPopover(); + const bounds = target.getBoundingClientRect(), size = tip.getBoundingClientRect(); + tip.style.left = `${Math.max(8, Math.min(bounds.left, innerWidth - size.width - 8))}px`; + tip.style.top = `${Math.max(8, bounds.bottom + size.height + 8 > innerHeight ? bounds.top - size.height - 8 : bounds.bottom + 8)}px`; + target.setAttribute('aria-describedby', [previousDescription, tip.id].filter(Boolean).join(' ')); + }, 300); + } + const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') hide(); }; + target.addEventListener('mouseenter', show); + target.addEventListener('mouseleave', hide); + target.addEventListener('focusin', show); + target.addEventListener('focusout', hide); + target.addEventListener('pointerdown', hide); + window.addEventListener('resize', hide); + window.addEventListener('scroll', hide, true); + window.addEventListener('keydown', escape); + return () => { + hide(); tip.remove(); + target.removeEventListener('mouseenter', show); + target.removeEventListener('mouseleave', hide); + target.removeEventListener('focusin', show); + target.removeEventListener('focusout', hide); + target.removeEventListener('pointerdown', hide); + window.removeEventListener('resize', hide); + window.removeEventListener('scroll', hide, true); + window.removeEventListener('keydown', escape); + }; +} diff --git a/packages/plugin-sdk/tsconfig.json b/packages/plugin-sdk/tsconfig.json new file mode 100644 index 0000000..c7297e1 --- /dev/null +++ b/packages/plugin-sdk/tsconfig.json @@ -0,0 +1,21 @@ +{ + // Builds dist/ with `pnpm sdk:build`. `pnpm check` runs this configuration with --noEmit. + // The source must stay erasable, because the host unit tests load it with node --experimental-strip-types. + "compilerOptions": { + "target": "es2022", + "module": "nodenext", + "lib": ["es2022", "dom", "dom.iterable"], + "types": [], + "strict": true, + "declaration": true, + "rootDir": "src", + "outDir": "dist", + "rewriteRelativeImportExtensions": true, + "verbatimModuleSyntax": true, + "isolatedModules": true, + "erasableSyntaxOnly": true, + "forceConsistentCasingInFileNames": true, + "skipLibCheck": true + }, + "include": ["src"] +} diff --git a/scripts/buildSdk.mjs b/scripts/buildSdk.mjs new file mode 100644 index 0000000..114ad9f --- /dev/null +++ b/scripts/buildSdk.mjs @@ -0,0 +1,43 @@ +// Builds the plugin SDK package into packages/plugin-sdk/dist. See docs/development.md#plugin-sdk. +// Usage: node scripts/buildSdk.mjs +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +export const sdkFolder = 'packages/plugin-sdk'; + +// Runs a command and rejects when it fails. +export function runCommand(command, args, options = {}) { + return new Promise((resolve, reject) => { + const child = spawn(command, args, { stdio: 'inherit', windowsHide: true, ...options }); + child.on('error', reject); + child.on('exit', code => code === 0 ? resolve() : reject(Error(`${path.basename(command)} ${args.join(' ')} failed with exit code ${code}.`))); + }); +} + +// The declaration files keep the `.ts` import paths of the source. Older TypeScript versions need `.js` paths. +export function declarationImports(text) { + return text.replace(/(\bfrom\s+["'])(\.{1,2}\/[^"']+)\.ts(["'])/g, '$1$2.js$3').replace(/(\bimport\(\s*["'])(\.{1,2}\/[^"']+)\.ts(["']\s*\))/g, '$1$2.js$3'); +} + +// Removes dist/, compiles the package with the TypeScript compiler of this repository, and returns the dist/ path. +export async function buildSdk(root, run = runCommand) { + const folder = path.join(root, sdkFolder); + const dist = path.join(folder, 'dist'); + await fs.rm(dist, { recursive: true, force: true }); + await run(process.execPath, [path.join(root, 'node_modules/typescript/bin/tsc'), '-p', path.join(folder, 'tsconfig.json')], { cwd: root }); + for (const name of await fs.readdir(dist)) { + if (!name.endsWith('.d.ts')) continue; + const file = path.join(dist, name); + await fs.writeFile(file, declarationImports(await fs.readFile(file, 'utf8'))); + } + await fs.access(path.join(dist, 'index.js')); + return dist; +} + +if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) { + const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + console.log('SDK build: ' + await buildSdk(root)); +} diff --git a/scripts/menuSurfaceAudit.mjs b/scripts/menuSurfaceAudit.mjs index c236746..9d79761 100644 --- a/scripts/menuSurfaceAudit.mjs +++ b/scripts/menuSurfaceAudit.mjs @@ -24,6 +24,8 @@ export async function discover() { const base = project === 'RuneStone' ? root : path.resolve(pluginRepos, project); let sources; try { sources = await files(path.join(base, 'src')); } catch (error) { if (error.code === 'ENOENT') { missing.push(project); continue; } throw error; } + // The plugin SDK declares the public menu API of RuneStone. + if (project === 'RuneStone') sources.push(...await files(path.join(base, 'packages/plugin-sdk/src'))); for (const file of sources) { const source = await readFile(file, 'utf8'); const counts = Object.fromEntries(Object.entries(patterns).map(([name, pattern]) => [name, [...source.matchAll(pattern)].length]).filter(([, count]) => count)); diff --git a/scripts/releaseSdk.mjs b/scripts/releaseSdk.mjs new file mode 100644 index 0000000..4078dee --- /dev/null +++ b/scripts/releaseSdk.mjs @@ -0,0 +1,185 @@ +// Releases the plugin SDK into a local clone of its public repository. See docs/releases.md#sdk-releases. +// Usage: node scripts/releaseSdk.mjs --version [--dry-run] +// The script commits and tags in the clone. It never pushes. It prints the push commands. +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { execFile } from 'node:child_process'; +import { realpathSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { compareReleases, releaseVersion } from './releaseVersion.mjs'; +import { buildSdk, sdkFolder } from './buildSdk.mjs'; + +const exists = file => fs.access(file).then(() => true, () => false); +export const packageName = '@runestone/plugin-sdk'; +export const repositoryName = 'RuneStone_Plugin_SDK'; +export const publicRepository = 'https://git.knottywyvern.com/kwyvern/RuneStone_Plugin_SDK.git'; +// The files that the release puts at the root of the public repository. LICENSE is required. NOTICE is optional. +export const releaseFiles = ['dist', 'package.json', 'README.md', 'LICENSE', 'NOTICE']; + +export function parseArguments(args) { + const options = { version: undefined, dryRun: false }; + for (let i = 0; i < args.length; i++) { + if (args[i] === '--dry-run') options.dryRun = true; + else if (args[i] === '--version' && args[i + 1] && !options.version) options.version = args[++i]; + else throw Error('Use --version followed by the SDK version, and optionally --dry-run.'); + } + if (!options.version) throw Error('Use --version followed by the SDK version, for example --version 0.1.0.'); + return options; +} + +// Runs git in a folder and returns its output without the final line break. Rejects when git fails. +export function git(cwd, args) { + return new Promise((resolve, reject) => { + execFile('git', ['-C', cwd, ...args], { windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (error, stdout, stderr) => { + if (error) reject(Error(`git ${args.join(' ')} failed in ${cwd}: ${String(stderr || error.message).trim()}`)); + else resolve(stdout.replace(/\r?\n$/, '')); + }); + }); +} +const gitOptional = (cwd, args) => git(cwd, args).catch(() => null); + +// The local clone of the public repository: RUNESTONE_SDK_REPO, or RuneStone_Plugin_SDK beside the plugin checkouts. +export function clonePath(root, env = process.env) { + if (env.RUNESTONE_SDK_REPO) return path.resolve(env.RUNESTONE_SDK_REPO); + return path.join(path.resolve(env.RUNESTONE_PLUGIN_REPOS || path.dirname(root)), repositoryName); +} + +// The package.json of the release: the source fields with the new version, without build scripts or development dependencies. +export function releasePackageJson(source, version) { + const { scripts, devDependencies, ...rest } = source; + const result = { ...rest, version }; + for (const field of ['types', 'exports', 'files', 'license']) if (!result[field]) throw Error(`The SDK package.json has no "${field}" field.`); + return result; +} + +// Checks the preconditions and returns the release plan. Changes no file. +export async function planSdkRelease(root, requestedVersion, env = process.env) { + const next = releaseVersion(requestedVersion); + const packageDir = path.join(root, sdkFolder); + const sourceFile = path.join(packageDir, 'package.json'); + const source = JSON.parse(await fs.readFile(sourceFile, 'utf8')); + if (source.name !== packageName) throw Error(`${sourceFile} is not the ${packageName} package.`); + const current = releaseVersion(source.version); + if (compareReleases(next.version, current.version) <= 0) throw Error(`The SDK version must be greater than the current version ${current.version}.`); + for (const file of ['README.md', 'LICENSE']) { + if (!(await exists(path.join(packageDir, file)))) throw Error(`The SDK package has no ${file} file. Add ${path.join(sdkFolder, file)} before a release.`); + } + const copies = []; + for (const file of releaseFiles) if (file !== 'dist' && file !== 'package.json' && await exists(path.join(packageDir, file))) copies.push(file); + if ((await git(root, ['status', '--porcelain', '--untracked-files=all', '--', sdkFolder])) !== '') { + throw Error(`${sdkFolder} has changes that are not committed. Commit them first, so that the release has a source commit.`); + } + const hostCommit = await git(root, ['rev-parse', 'HEAD']); + + const clone = clonePath(root, env); + if (!(await exists(clone))) throw Error(`The SDK repository clone is missing: ${clone}. Clone ${publicRepository} there, or set RUNESTONE_SDK_REPO.`); + const top = await gitOptional(clone, ['rev-parse', '--show-toplevel']); + if (!top || realpathSync.native(top) !== realpathSync.native(clone)) throw Error(`${clone} is not the root of a Git repository.`); + if ((await git(clone, ['status', '--porcelain', '--untracked-files=all'])) !== '') throw Error(`The SDK repository clone has changes: ${clone}. Commit or remove them first.`); + const branch = await gitOptional(clone, ['symbolic-ref', '--quiet', '--short', 'HEAD']); + if (!branch) throw Error(`The SDK repository clone is not on a branch: ${clone}.`); + const head = await gitOptional(clone, ['rev-parse', '--verify', '--quiet', 'HEAD']); + const tag = 'v' + next.version; + if (await gitOptional(clone, ['rev-parse', '--verify', '--quiet', 'refs/tags/' + tag])) throw Error(`The tag ${tag} exists in ${clone}. A release never replaces a tag.`); + const published = await fs.readFile(path.join(clone, 'package.json'), 'utf8').then(text => JSON.parse(text).version, () => null); + if (published && compareReleases(next.version, published) <= 0) throw Error(`The SDK version must be greater than the version ${published} in the clone.`); + const remotes = (await git(clone, ['remote'])).split(/\r?\n/).filter(Boolean); + + const quoted = `"${clone}"`; + return { + root, packageDir, sourceFile, source, current, next, clone, branch, head, tag, hostCommit, copies, + packageJson: releasePackageJson(source, next.version), + commitMessage: `Release ${packageName} ${next.version}\n\nBuilt from RuneStone ${hostCommit}.`, + pushCommands: [ + ...(remotes.includes('origin') ? [] : [`git -C ${quoted} remote add origin ${publicRepository}`]), + `git -C ${quoted} push origin ${branch}`, + `git -C ${quoted} push origin ${tag}`, + ], + }; +} + +export function describePlan(plan) { + return [ + `SDK version: ${plan.next.version} (current ${plan.current.version})`, + `Source: ${path.relative(plan.root, plan.packageDir) || '.'} at RuneStone ${plan.hostCommit}`, + `Clone: ${plan.clone} (branch ${plan.branch}${plan.head ? '' : ', no commits'})`, + `1. Build ${sdkFolder}/dist.`, + `2. Replace ${['dist', 'package.json', ...plan.copies].join(', ')} in the clone.`, + `3. Commit "${plan.commitMessage.split('\n')[0]}" and create the tag ${plan.tag}.`, + `4. Write the version ${plan.next.version} to ${sdkFolder}/package.json.`, + 'The script does not push. After the release, run:', + ...plan.pushCommands.map(command => ' ' + command), + ].join('\n'); +} + +async function copyFolder(from, to) { + await fs.mkdir(to, { recursive: true }); + for (const entry of await fs.readdir(from, { withFileTypes: true })) { + const source = path.join(from, entry.name), target = path.join(to, entry.name); + if (entry.isDirectory()) await copyFolder(source, target); + else if (entry.isFile()) await fs.copyFile(source, target); + else throw Error('The SDK build contains a link or a special file: ' + source); + } +} + +// Puts the clone back to its state before the release. The clone was clean at the start, so this removes only release changes. +async function restoreClone(plan, tagged) { + const { clone, head, tag } = plan; + if (tagged) await gitOptional(clone, ['tag', '-d', tag]); + if (head) await gitOptional(clone, ['reset', '--quiet', '--hard', head]); + else { + await gitOptional(clone, ['update-ref', '-d', 'HEAD']); + await gitOptional(clone, ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '.']); + } + await gitOptional(clone, ['clean', '-f', '-d', '-q']); +} + +// Runs the release. build(root) returns the dist folder. The source version changes only when the tag exists. +export async function runSdkRelease(plan, build = buildSdk) { + const before = await fs.readFile(plan.sourceFile, 'utf8'); + let changedClone = false, tagged = false, complete = false; + try { + const dist = await build(plan.root); + for (const file of ['index.js', 'index.d.ts']) await fs.access(path.join(dist, file)); + changedClone = true; + await fs.rm(path.join(plan.clone, 'dist'), { recursive: true, force: true }); + await copyFolder(dist, path.join(plan.clone, 'dist')); + await fs.writeFile(path.join(plan.clone, 'package.json'), JSON.stringify(plan.packageJson, null, 2) + '\n'); + for (const file of plan.copies) await fs.copyFile(path.join(plan.packageDir, file), path.join(plan.clone, file)); + // -f adds the files also when a .gitignore file in the clone lists dist/. + await git(plan.clone, ['add', '-A', '-f', '--', 'dist', 'package.json', ...plan.copies]); + await git(plan.clone, ['commit', '--quiet', '-m', plan.commitMessage]); + await git(plan.clone, ['tag', '-a', plan.tag, '-m', `${packageName} ${plan.next.version}`]); + tagged = true; + await fs.writeFile(plan.sourceFile, before.replace(/("version":\s*")[^"]+(")/, `$1${plan.next.version}$2`)); + if (JSON.parse(await fs.readFile(plan.sourceFile, 'utf8')).version !== plan.next.version) throw Error('The SDK version field did not change.'); + complete = true; + return { tag: plan.tag, commit: await git(plan.clone, ['rev-parse', 'HEAD']) }; + } finally { + if (!complete) { + if ((await fs.readFile(plan.sourceFile, 'utf8').catch(() => null)) !== before) await fs.writeFile(plan.sourceFile, before); + if (changedClone) await restoreClone(plan, tagged); + console.error('The SDK release did not complete. The version and the clone are restored.'); + } + } +} + +async function main() { + const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); + const options = parseArguments(process.argv.slice(2)); + const plan = await planSdkRelease(root, options.version); + console.log(describePlan(plan)); + if (options.dryRun) { + console.log('Dry run: no file changed.'); + return; + } + const result = await runSdkRelease(plan); + console.log(`\n${packageName} ${plan.next.version} is committed and tagged ${result.tag} (${result.commit}) in ${plan.clone}.`); + console.log('Push the branch and the tag:'); + for (const command of plan.pushCommands) console.log(' ' + command); + console.log(`Then commit the new version in ${sdkFolder}/package.json in RuneStone.`); +} + +if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) { + try { await main(); } catch (error) { console.error(error instanceof Error ? error.message : error); process.exitCode = 1; } +} diff --git a/src/lib/completion/contracts.ts b/src/lib/completion/contracts.ts index 60be153..cca3969 100644 --- a/src/lib/completion/contracts.ts +++ b/src/lib/completion/contracts.ts @@ -1,58 +1,2 @@ -export type CompletionDispose = () => void; -export interface CompletionSnapshot { - documentId: string; - revision: string | number; - text: string; - caret: number; - selectionEnd: number; - focused: boolean; - composing?: boolean; - sensitive?: boolean; - readOnly?: boolean; - kind: "prose" | "code"; - language?: string; -} -export interface CompletionRequest { - surfaceId: string; - documentId: string; - revision: string | number; - prefix: string; - suffix: string; - kind: "prose" | "code"; - language: string; - manual: boolean; - signal: AbortSignal; -} -export interface CompletionProvider { - id: string; - delayMs?: number; - timeoutMs?: number; - complete(request: CompletionRequest, publish: (text: string) => void): Promise; -} -export interface CompletionSurface { - id: string; - snapshot(): CompletionSnapshot; - preview(text: string | null): void; - insert(text: string, expected: CompletionSnapshot): boolean; -} -export interface CompletionHandle { - changed(): void; - request(): void; - accept(word?: boolean): boolean; - dismiss(): boolean; - dispose(): void; -} -export interface CompletionTransportRequest { - endpoint: string; - route: "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate"; - body?: string; - timeoutMs?: number; -} -export interface CompletionApi { - version: 1; - registerProvider(provider: CompletionProvider): CompletionDispose; - registerSurface(surface: CompletionSurface): CompletionHandle; - registerInput(element: HTMLInputElement | HTMLTextAreaElement, options: { id: string; kind?: "prose" | "code"; sensitive?: boolean }): CompletionHandle; - invalidate(): void; - transport?(request: CompletionTransportRequest, signal: AbortSignal, onLine: (line: string) => void): Promise; -} +// The completion types are part of the public plugin SDK (packages/plugin-sdk/src/completion.ts). +export type { CompletionApi, CompletionDispose, CompletionHandle, CompletionProvider, CompletionRequest, CompletionSnapshot, CompletionSurface, CompletionTransportRequest } from "../plugins/sdk.ts"; diff --git a/src/lib/git/contracts.ts b/src/lib/git/contracts.ts index 6b9b60d..fe9419c 100644 --- a/src/lib/git/contracts.ts +++ b/src/lib/git/contracts.ts @@ -1,62 +1,2 @@ -export interface GitChange { - path: string; - originalPath?: string; - index: string; - worktree: string; -} - -export interface GitStatus { - available: boolean; - repository: boolean; - branch: string | null; - changes: GitChange[]; -} - -export interface GitLineInfo { - commit: string; - author: string; - /** The author date in ISO 8601 format. */ - date: string; - summary: string; -} - -export interface GitApi { - status(): Promise; - diff(path: string, staged: boolean): Promise; - stage(paths: string[]): Promise; - unstage(paths: string[]): Promise; - commit(message: string): Promise; - push(): Promise; - pull(): Promise; - graph(): Promise; - commitDetails(commit: string): Promise; - commitDiff(commit: string, path: string): Promise; - blame(path: string, line: number): Promise; -} - -export interface GitGraphCommit { - id: string; - parents: string[]; - refs: string[]; - summary: string; - author: string; - date: string; -} - -export interface GitGraph { - commits: GitGraphCommit[]; -} - -export interface GitCommitFile { - path: string; - originalPath?: string; - status: string; -} -export interface GitCommitDetails { - id: string; - parents: string[]; - author: string; - date: string; - message: string; - files: GitCommitFile[]; -} +// The Git types are part of the public plugin SDK (packages/plugin-sdk/src/git.ts). +export type { GitApi, GitChange, GitCommitDetails, GitCommitFile, GitGraph, GitGraphCommit, GitLineInfo, GitStatus } from "../plugins/sdk.ts"; diff --git a/src/lib/plugins/backgroundContracts.ts b/src/lib/plugins/backgroundContracts.ts index 08ff9c6..3dc6dde 100644 --- a/src/lib/plugins/backgroundContracts.ts +++ b/src/lib/plugins/backgroundContracts.ts @@ -1,24 +1,5 @@ -export interface BackgroundFrame { - url: string; - blurredUrl?: string; - overlay: number; - position: 'center' | 'top left' | 'top' | 'top right' | 'left' | 'right' | 'bottom left' | 'bottom' | 'bottom right'; - size: 'cover' | 'contain' | 'auto'; - previous?: Omit; - transitionMs?: number; -} - -export interface BackgroundApi { - readonly version: 1; - chooseFolder(): Promise; - defaultFolder?(): Promise; - list(folder: string): Promise<{ name: string }[]>; - read(folder: string, name: string): Promise; - readImageSettings?(folder: string): Promise; - writeImageSettings?(folder: string, contents: string, expected: string | null): Promise; - set(target: string, frame: BackgroundFrame | null): void; - get(target: string): BackgroundFrame | null; - subscribe(listener: (target: string) => void): () => void; -} +// The public background types are in the plugin SDK (packages/plugin-sdk/src/backgrounds.ts). +import type { BackgroundApi } from "./sdk.ts"; +export type { BackgroundApi, BackgroundFrame } from "./sdk.ts"; export type BackgroundFiles = Pick; diff --git a/src/lib/plugins/contracts.ts b/src/lib/plugins/contracts.ts index 0035b5b..7a7e0a1 100644 --- a/src/lib/plugins/contracts.ts +++ b/src/lib/plugins/contracts.ts @@ -1,26 +1,2 @@ -import type { Dispose } from "./sdk.ts"; - -export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories"; -export interface TerminalProps { - cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean; - onClose: () => void; onMaximize?: () => void; activeFile?: boolean; - onRunFile?: () => Promise; getSelection?: () => string; onConfigureTasks?: () => Promise; -} -export interface TerminalMount { - update(props: TerminalProps): void; - command(action: Exclude): void | Promise; - dispose: Dispose; -} -export interface Contributions { - git: { blame(path: string, line: number): Promise }; - browser: { - newTab?(): Promise; - mountSettings(container: HTMLElement): Dispose | Promise; - mountBookmarks(container: HTMLElement): Dispose | Promise; - open(url: string): Promise; - }; - terminal: { - mount(container: HTMLElement, props: TerminalProps): TerminalMount; - shortcut(event: Pick): TerminalAction | null; - }; -} +// Contribution types are part of the public plugin SDK (packages/plugin-sdk/src/contributions.ts). +export type { Contributions, TerminalAction, TerminalMount, TerminalProps } from "./sdk.ts"; diff --git a/src/lib/plugins/sdk.ts b/src/lib/plugins/sdk.ts index dd60af8..ac7504d 100644 --- a/src/lib/plugins/sdk.ts +++ b/src/lib/plugins/sdk.ts @@ -1,52 +1,8 @@ -import type { Contributions } from "./contracts.ts"; -import type { CompletionApi } from "../completion/contracts.ts"; -import type { ActionMenuItem } from "../ui/actionMenu.ts"; -import type { ActionIcon } from "../ui/actionIcons.ts"; -export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts"; -/** Package API v1. Compiled plugins export activate(api). */ -export type Dispose = () => void | Promise; -export interface PluginCommand { id: string; title: string; icon?: ActionIcon | PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise } -export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; launch?: () => void | Promise; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise } -export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string } -export interface PluginDocumentContext { id: string; path: string } -export interface PluginDocumentType { - id: string; - title: string; - icon?: "kanban" | "file"; - extensions: string[]; - content?: "text" | "binary"; - identify(path: string, source: string): { id: string } | null; - create?: { label: string; defaultName: string; extension: string; contents(): string }; - mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise; -} -export interface PtyProfile { id: string; title: string; kind: string } -export interface PtyOpenOptions { - /** The workspace root of the window. The host rejects the request when the workspace changed. */ - cwd: string; - cols: number; - rows: number; - profile?: string; - /** A start folder other than the workspace root. */ - directory?: string; - /** Receives raw terminal output. UTF-8 characters can be split between two calls. */ - onData(data: Uint8Array): void; - onExit?(code: number | null): void; -} -export interface PtySession { - readonly id: string; - write(data: string): Promise; - resize(cols: number, rows: number): Promise; - /** Stops the shell. Repeated calls return the same promise. */ - close(): Promise; -} -/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */ -export interface PtyApi { - readonly version: 1; - profiles(): Promise; - open(options: PtyOpenOptions): Promise; - openWindow(): Promise; - dictation(): Promise; -} +// The public plugin API comes from the SDK package (packages/plugin-sdk). Change the public types there. +// The relative path works in SvelteKit, svelte-check, Vite, and the Node unit tests. +import type { FilesApi, PluginManifest, PtyProfile } from "../../../packages/plugin-sdk/src/index.ts"; +export * from "../../../packages/plugin-sdk/src/index.ts"; + /** The native side of `PtyApi`. `onData` and `onExit` receive the output of this session only. */ export interface PtyTransport { open(request: { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise; @@ -57,74 +13,9 @@ export interface PtyTransport { openWindow(): Promise; dictation(): Promise; } -export interface FolderGrant { id: string; path: string; name: string } -export interface FolderEntry { name: string; size: number } -/** Folders outside the workspace that the user granted to this plugin. */ -export interface FilesApi { - readonly version: 1; - chooseFolder(options?: { title?: string }): Promise; - pictureFolder(name: string): Promise; - grants(): Promise; - revoke(grant: string): Promise; - list(grant: string): Promise; - readBytes(grant: string, name: string): Promise; - readSidecar(grant: string, name: string): Promise; - writeSidecar(grant: string, name: string, contents: string, expected: string | null): Promise; -} /** The native side of `FilesApi`, bound to one plugin ID by the host. */ export type FilesTransport = Omit; -export type ServiceMethods = Record unknown>; -/** Data that one plugin offers to other plugins in the same window. */ -export interface ServicesApi { - readonly version: 1; - provide(name: string, methods: ServiceMethods): { notify(): void; dispose(): void }; - get(plugin: string, name: string): Record Promise> | null; - subscribe(listener: (plugin: string, name: string) => void): Dispose; -} -export interface PluginApi { - pty?: PtyApi; - files?: FilesApi; - services?: ServicesApi; - backgrounds?: import("./backgroundContracts.ts").BackgroundApi; - ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } }; - git?: import("../git/contracts.ts").GitApi; - completion?: CompletionApi; - readonly id: string; - readonly signal: AbortSignal; - contribute(key: K, value: Contributions[K]): void; - registerCommand(command: PluginCommand): void; - registerView(view: PluginView): void; - registerTabDrop?(receive: (data: string) => void | Promise): void; - updateViewTitle?(id: string, title: string): void; - updateViewIcon?(id: string, image: string | null): void; - registerDocumentType(type: PluginDocumentType): void; - openDocument(path: string): Promise; - openFile?(path: string): Promise; - renameDocument?(document: PluginDocumentContext, name: string): Promise; - openView(id: string, options?: PluginViewOpenOptions): void; - closeView?(id: string): void; - replaceView?(currentId: string, nextId: string): void; - replaceDocumentWithView?(document: PluginDocumentContext, nextId: string): void; - onDispose(cleanup: Dispose): void; - workspace: { - list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>; - listMarkdown?(): Promise; - read(path: string): Promise; - readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>; - readBytes?(path: string): Promise; - readOptional?(path: string): Promise; - create?(path: string, contents: string): Promise; - write(path: string, contents: string, expected: string): Promise; - subscribe?(listener: () => void): Dispose; - }; - settings: { read(): Promise; write(value: unknown): Promise; subscribe?(listener: () => void): Dispose }; - assets: { read(path: string): Promise }; -} -export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise } -export interface ExternalManifest { - schemaVersion: 1; id: string; name: string; author: string; description: string; - version: string; apiVersion: 1; entry: string; access: "full-app"; -} +export type ExternalManifest = PluginManifest; export interface InstalledPlugin { manifest: ExternalManifest; hash: string; enabled: boolean; installedAt: number | null; path: string; error: string | null; removal: boolean } export interface PluginSnapshot { root: string; plugins: InstalledPlugin[] } export interface Candidate { token: string; source: string; manifest: ExternalManifest | null; error: string | null } diff --git a/src/lib/ui/actionIcons.ts b/src/lib/ui/actionIcons.ts index 2cfc623..8b2192e 100644 --- a/src/lib/ui/actionIcons.ts +++ b/src/lib/ui/actionIcons.ts @@ -1,92 +1,2 @@ -// Stroke icons share the same 24px grid and weight as IconButton. -export const actionIcons = { - play: '', - pause: '', - 'skip-forward': '', - eye: '', - 'eye-off': '', - image: '', - settings: '', - archive: '', - save: '', - refresh: '', - 'arrow-left': '', - 'arrow-right': '', - terminal: '', - undo: '', - redo: '', - git: '', - globe: '', - puzzle: '', - 'split-right': '', - 'split-down': '', - kanban: '', - bookmark: '', - 'file-plus': '', - 'folder-plus': '', - - pin: '', - book: '', - folder: '', - rename: '', - 'zoom-in': '', - 'zoom-out': '', - close: '', - swap: '', - bullet: '', - number: '', - task: '', - heading: '', - quote: '', - table: '', - rule: '', - footnote: '', - cut: '', - copy: '', - paste: '', - 'paste-text': '', - format: '', - bold: '', - italic: '', - strike: '', - highlight: '', - code: '', - math: '', - comment: '', - clear: '', - left: '', - center: '', - right: '', - row: '', - column: '', - 'row-before': '', - 'row-after': '', - 'column-before': '', - 'column-after': '', - up: '', - down: '', - 'move-left': '', - 'move-right': '', - trash: '', - 'sort-asc': '', - 'sort-desc': '', - link: '', - external: '', - search: '', - filter: '', - extract: '', - select: '', - paragraph: '', - insert: '', - chevron: '', - plus: '', - grip: '', -} as const; -export type ActionIcon = keyof typeof actionIcons; - -export function actionIcon(name: ActionIcon): SVGSVGElement { - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true"); - svg.classList.add("action-icon"); svg.innerHTML = actionIcons[name]; - return svg; -} +// The action icons are part of the public plugin SDK, so plugins use the same artwork as the host. +export { actionIcon, actionIcons, type ActionIcon } from "../../../packages/plugin-sdk/src/icons.ts"; diff --git a/src/lib/ui/tooltip.ts b/src/lib/ui/tooltip.ts index 5b48208..926024d 100644 --- a/src/lib/ui/tooltip.ts +++ b/src/lib/ui/tooltip.ts @@ -1,49 +1,2 @@ -/** A single themed tooltip for DOM controls, with hover and keyboard dismissal. */ -export function attachTooltip(target: HTMLElement, label: () => string) { - const tip = document.createElement('span'); - tip.className = 'rs-tooltip'; - tip.setAttribute('popover', 'manual'); - tip.setAttribute('role', 'tooltip'); - tip.id = `rs-tooltip-${crypto.randomUUID()}`; - document.body.append(tip); - let timer: ReturnType | undefined; - const previousDescription = target.getAttribute('aria-describedby'); - function hide() { - clearTimeout(timer); - if (tip.matches(':popover-open')) tip.hidePopover(); - if (previousDescription) target.setAttribute('aria-describedby', previousDescription); - else target.removeAttribute('aria-describedby'); - } - function show() { - clearTimeout(timer); - timer = setTimeout(() => { - if (!target.isConnected || !label()) return; - tip.textContent = label(); - tip.showPopover(); - const bounds = target.getBoundingClientRect(), size = tip.getBoundingClientRect(); - tip.style.left = `${Math.max(8, Math.min(bounds.left, innerWidth - size.width - 8))}px`; - tip.style.top = `${Math.max(8, bounds.bottom + size.height + 8 > innerHeight ? bounds.top - size.height - 8 : bounds.bottom + 8)}px`; - target.setAttribute('aria-describedby', [previousDescription, tip.id].filter(Boolean).join(' ')); - }, 300); - } - const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') hide(); }; - target.addEventListener('mouseenter', show); - target.addEventListener('mouseleave', hide); - target.addEventListener('focusin', show); - target.addEventListener('focusout', hide); - target.addEventListener('pointerdown', hide); - window.addEventListener('resize', hide); - window.addEventListener('scroll', hide, true); - window.addEventListener('keydown', escape); - return () => { - hide(); tip.remove(); - target.removeEventListener('mouseenter', show); - target.removeEventListener('mouseleave', hide); - target.removeEventListener('focusin', show); - target.removeEventListener('focusout', hide); - target.removeEventListener('pointerdown', hide); - window.removeEventListener('resize', hide); - window.removeEventListener('scroll', hide, true); - window.removeEventListener('keydown', escape); - }; -} +// The tooltip helper is part of the public plugin SDK (packages/plugin-sdk/src/tooltip.ts). +export { attachTooltip } from "../../../packages/plugin-sdk/src/tooltip.ts"; diff --git a/tests/unit/release/releaseSdk.spec.ts b/tests/unit/release/releaseSdk.spec.ts new file mode 100644 index 0000000..5512ded --- /dev/null +++ b/tests/unit/release/releaseSdk.spec.ts @@ -0,0 +1,196 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, writeFile, copyFile, rm, access, readdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { clonePath, describePlan, git, parseArguments, planSdkRelease, releasePackageJson, runSdkRelease } from "../../../scripts/releaseSdk.mjs"; + +// These tests use temporary Git repositories. They need no network and never push. +const repository = path.resolve("."); +const sdk = "packages/plugin-sdk"; +const exists = (file: string) => access(file).then(() => true, () => false); +const identity = async (folder: string) => { + await git(folder, ["config", "user.name", "SDK test"]); + await git(folder, ["config", "user.email", "sdk-test@example.invalid"]); +}; + +type Setup = { base: string; root: string; clone: string; remote: string; env: Record }; + +// A host repository with the SDK package files, a clone of the public repository, and a bare remote for that clone. +async function fixture(options: { empty?: boolean; origin?: boolean } = {}): Promise { + const base = await mkdtemp(path.join(tmpdir(), "runestone-sdk-release-")); + const root = path.join(base, "RuneStone"); + await mkdir(path.join(root, sdk), { recursive: true }); + for (const file of ["package.json", "README.md", "LICENSE", "NOTICE"]) await copyFile(path.join(repository, sdk, file), path.join(root, sdk, file)); + const source = JSON.parse(await readFile(path.join(root, sdk, "package.json"), "utf8")); + await writeFile(path.join(root, sdk, "package.json"), JSON.stringify({ ...source, version: "0.0.0", scripts: { build: "tsc" }, devDependencies: { typescript: "6" } }, null, 2) + "\n"); + await writeFile(path.join(root, ".gitignore"), "dist/\n"); + await git(root, ["init", "-q", "-b", "master"]); + await identity(root); + await git(root, ["add", "-A"]); + await git(root, ["commit", "-q", "-m", "host"]); + + const remote = path.join(base, "remote.git"); + await git(base, ["init", "-q", "--bare", remote]); + const clone = path.join(base, "RuneStone_Plugin_SDK"); + await mkdir(clone); + await git(clone, ["init", "-q", "-b", "main"]); + await identity(clone); + if (options.origin !== false) await git(clone, ["remote", "add", "origin", remote]); + if (!options.empty) { + await writeFile(path.join(clone, ".gitignore"), "dist/\nnode_modules/\n"); + await git(clone, ["add", "-A"]); + await git(clone, ["commit", "-q", "-m", "Start"]); + } + return { base, root, clone, remote, env: { RUNESTONE_PLUGIN_REPOS: base } }; +} + +async function withFixture(options: { empty?: boolean; origin?: boolean }, body: (setup: Setup) => Promise) { + const setup = await fixture(options); + try { await body(setup); } finally { await rm(setup.base, { recursive: true, force: true }); } +} + +// A build that writes a small dist/ folder in place of the TypeScript compiler. +const fakeBuild = async (root: string) => { + const dist = path.join(root, sdk, "dist"); + await mkdir(path.join(dist, "nested"), { recursive: true }); + await writeFile(path.join(dist, "index.js"), "export const API_VERSION = 1;\n"); + await writeFile(path.join(dist, "index.d.ts"), "export declare const API_VERSION = 1;\n"); + await writeFile(path.join(dist, "nested", "extra.js"), "export {};\n"); + return dist; +}; +const failingBuild = async () => { throw Error("The compiler failed."); }; + +async function state(setup: Setup) { + return { + source: await readFile(path.join(setup.root, sdk, "package.json"), "utf8"), + head: await git(setup.clone, ["rev-parse", "--verify", "--quiet", "HEAD"]).catch(() => null), + status: await git(setup.clone, ["status", "--porcelain", "--untracked-files=all"]), + tags: await git(setup.clone, ["tag", "--list"]), + files: (await readdir(setup.clone)).sort(), + }; +} +const quiet = async (work: () => Promise) => { + const error = console.error; + console.error = () => {}; + try { return await work(); } finally { console.error = error; } +}; + +test("the SDK release script reads --version and --dry-run", () => { + assert.deepEqual(parseArguments(["--version", "0.1.0"]), { version: "0.1.0", dryRun: false }); + assert.deepEqual(parseArguments(["--dry-run", "--version", "0.1.0a"]), { version: "0.1.0a", dryRun: true }); + for (const args of [[], ["--dry-run"], ["--version"], ["0.1.0"], ["--version", "0.1.0", "--version", "0.1.1"], ["--push"]]) assert.throws(() => parseArguments(args)); +}); + +test("the clone path comes from RUNESTONE_SDK_REPO, then RUNESTONE_PLUGIN_REPOS, then the parent folder", () => { + const root = path.resolve("/work/RuneStone"); + assert.equal(clonePath(root, { RUNESTONE_SDK_REPO: "/elsewhere/sdk", RUNESTONE_PLUGIN_REPOS: "/plugins" }), path.resolve("/elsewhere/sdk")); + assert.equal(clonePath(root, { RUNESTONE_PLUGIN_REPOS: "/plugins" }), path.join(path.resolve("/plugins"), "RuneStone_Plugin_SDK")); + assert.equal(clonePath(root, {}), path.join(path.resolve("/work"), "RuneStone_Plugin_SDK")); +}); + +test("the release package.json has the version and no build scripts or development dependencies", () => { + const source = { name: "@runestone/plugin-sdk", version: "0.0.0", types: "./dist/index.d.ts", exports: {}, files: ["dist"], license: "Apache-2.0", scripts: { build: "tsc" }, devDependencies: { typescript: "6" } }; + assert.deepEqual(releasePackageJson(source, "0.1.0"), { name: "@runestone/plugin-sdk", version: "0.1.0", types: "./dist/index.d.ts", exports: {}, files: ["dist"], license: "Apache-2.0" }); + assert.throws(() => releasePackageJson({ ...source, license: undefined }, "0.1.0"), /license/); +}); + +test("a dry run plans the release, prints the push commands, and changes no file", () => withFixture({}, async setup => { + const before = await state(setup); + const plan = await planSdkRelease(setup.root, "0.1.0", setup.env); + const text = describePlan(plan); + assert.match(text, /SDK version: 0\.1\.0 \(current 0\.0\.0\)/); + assert.match(text, /Replace dist, package\.json, README\.md, LICENSE, NOTICE in the clone/); + assert.match(text, /create the tag v0\.1\.0/); + assert.deepEqual(plan.pushCommands, [`git -C "${setup.clone}" push origin main`, `git -C "${setup.clone}" push origin v0.1.0`]); + assert.equal(plan.packageJson.version, "0.1.0"); + assert.equal(plan.packageJson.scripts, undefined); + assert.equal(plan.packageJson.devDependencies, undefined); + assert.deepEqual(await state(setup), before); +})); + +test("a clone without an origin remote gets the command that adds it", () => withFixture({ origin: false }, async setup => { + const plan = await planSdkRelease(setup.root, "0.1.0", setup.env); + assert.match(plan.pushCommands[0], /remote add origin https:\/\/git\.knottywyvern\.com\/kwyvern\/RuneStone_Plugin_SDK\.git$/); +})); + +test("the release refuses a missing, unrelated, dirty, or detached clone", () => withFixture({}, async setup => { + await assert.rejects(planSdkRelease(setup.root, "0.1.0", { RUNESTONE_SDK_REPO: path.join(setup.base, "missing") }), /clone is missing/); + const plain = path.join(setup.root, sdk); + await assert.rejects(planSdkRelease(setup.root, "0.1.0", { RUNESTONE_SDK_REPO: plain }), /not the root of a Git repository/); + await writeFile(path.join(setup.clone, "notes.txt"), "draft"); + await assert.rejects(planSdkRelease(setup.root, "0.1.0", setup.env), /clone has changes/); + await rm(path.join(setup.clone, "notes.txt")); + await git(setup.clone, ["checkout", "-q", "--detach"]); + await assert.rejects(planSdkRelease(setup.root, "0.1.0", setup.env), /not on a branch/); +})); + +test("the release never replaces a tag and never goes back to an earlier version", () => withFixture({}, async setup => { + await git(setup.clone, ["tag", "v0.1.0"]); + await assert.rejects(planSdkRelease(setup.root, "0.1.0", setup.env), /The tag v0\.1\.0 exists/); + await assert.rejects(planSdkRelease(setup.root, "0.0.0", setup.env), /greater than the current version 0\.0\.0/); + await assert.rejects(planSdkRelease(setup.root, "1.0", setup.env), /release version/); + await writeFile(path.join(setup.clone, "package.json"), JSON.stringify({ version: "0.2.0" })); + await git(setup.clone, ["add", "-A"]); + await git(setup.clone, ["commit", "-q", "-m", "Earlier release"]); + await assert.rejects(planSdkRelease(setup.root, "0.1.1", setup.env), /greater than the version 0\.2\.0 in the clone/); +})); + +test("the release refuses a package without a license file or with source changes that are not committed", () => withFixture({}, async setup => { + await rm(path.join(setup.root, sdk, "LICENSE")); + await assert.rejects(planSdkRelease(setup.root, "0.1.0", setup.env), /no LICENSE file/); + await git(setup.root, ["checkout", "-q", "--", sdk]); + await writeFile(path.join(setup.root, sdk, "README.md"), "changed"); + await assert.rejects(planSdkRelease(setup.root, "0.1.0", setup.env), /not committed/); +})); + +test("a completed release commits and tags in the clone, sets the source version, and pushes nothing", () => withFixture({}, async setup => { + const plan = await planSdkRelease(setup.root, "0.1.0", setup.env); + const result = await runSdkRelease(plan, fakeBuild); + assert.equal(result.tag, "v0.1.0"); + assert.equal(await git(setup.clone, ["status", "--porcelain", "--untracked-files=all"]), ""); + assert.equal(await git(setup.clone, ["cat-file", "-t", "v0.1.0"]), "tag"); + assert.equal(await git(setup.clone, ["rev-parse", "v0.1.0^{commit}"]), result.commit); + const tracked = (await git(setup.clone, ["ls-files"])).split("\n").sort(); + assert.deepEqual(tracked, [".gitignore", "LICENSE", "NOTICE", "README.md", "dist/index.d.ts", "dist/index.js", "dist/nested/extra.js", "package.json"]); + const published = JSON.parse(await readFile(path.join(setup.clone, "package.json"), "utf8")); + assert.equal(published.version, "0.1.0"); + assert.equal(published.license, "Apache-2.0"); + assert.equal(published.scripts, undefined); + assert.equal(await readFile(path.join(setup.clone, "LICENSE"), "utf8"), await readFile(path.join(setup.root, sdk, "LICENSE"), "utf8")); + assert.match(await git(setup.clone, ["log", "-1", "--format=%B"]), new RegExp(`^Release @runestone/plugin-sdk 0\\.1\\.0\\n\\nBuilt from RuneStone ${plan.hostCommit}\\.`)); + assert.equal(JSON.parse(await readFile(path.join(setup.root, sdk, "package.json"), "utf8")).version, "0.1.0"); + assert.equal(await git(setup.remote, ["for-each-ref"]), "", "The release must not push."); + + // The next release replaces dist/ and removes files that the new build does not contain. + await git(setup.root, ["commit", "-q", "-am", "Record 0.1.0"]); + const next = await planSdkRelease(setup.root, "0.1.1", setup.env); + await runSdkRelease(next, async root => { const dist = await fakeBuild(root); await rm(path.join(dist, "nested"), { recursive: true }); return dist; }); + assert.equal(await exists(path.join(setup.clone, "dist/nested/extra.js")), false); + assert.deepEqual((await git(setup.clone, ["tag", "--list"])).split("\n"), ["v0.1.0", "v0.1.1"]); +})); + +test("a failed build restores the version and leaves the clone unchanged", () => withFixture({}, async setup => { + const before = await state(setup); + const plan = await planSdkRelease(setup.root, "0.1.0", setup.env); + await quiet(() => assert.rejects(runSdkRelease(plan, failingBuild), /compiler failed/)); + assert.deepEqual(await state(setup), before); +})); + +test("a failed commit restores the clone, also in a clone without commits", async () => { + for (const empty of [false, true]) { + await withFixture({ empty }, async setup => { + const before = await state(setup); + await writeFile(path.join(setup.clone, ".git/hooks/pre-commit"), "#!/bin/sh\nexit 1\n"); + const plan = await planSdkRelease(setup.root, "0.1.0", setup.env); + assert.equal(plan.head, empty ? null : before.head); + await quiet(() => assert.rejects(runSdkRelease(plan, fakeBuild), /git commit/)); + assert.deepEqual(await state(setup), before); + await rm(path.join(setup.clone, ".git/hooks/pre-commit")); + if (empty) { + await runSdkRelease(await planSdkRelease(setup.root, "0.1.0", setup.env), fakeBuild); + assert.equal(await git(setup.clone, ["rev-list", "--count", "HEAD"]), "1"); + } + }); + } +}); diff --git a/tests/unit/sdk/features.spec.ts b/tests/unit/sdk/features.spec.ts new file mode 100644 index 0000000..54e77c0 --- /dev/null +++ b/tests/unit/sdk/features.spec.ts @@ -0,0 +1,119 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile, access } from "node:fs/promises"; +import path from "node:path"; +import { API_VERSION, describeFeature, hasFeature, missingFeatures, MissingFeatureError, pluginFeatures, requireFeature, requireFeatures, type PluginApi } from "../../../packages/plugin-sdk/src/index.ts"; +import * as sdkIcons from "../../../packages/plugin-sdk/src/icons.ts"; +import * as sdkTooltip from "../../../packages/plugin-sdk/src/tooltip.ts"; +import * as hostIcons from "../../../src/lib/ui/actionIcons.ts"; +import * as hostTooltip from "../../../src/lib/ui/tooltip.ts"; +import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts"; +import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts"; +import { ServiceHub } from "../../../src/lib/plugins/services.ts"; +import { declarationImports } from "../../../scripts/buildSdk.mjs"; +import type { ActionMenuItem as HostMenuItem } from "../../../src/lib/ui/actionMenu.ts"; +import type { MenuOptions as HostMenuOptions } from "../../../src/lib/ui/managedActionMenu.ts"; +import type { ActionMenuItem, ActionMenuOptions } from "../../../packages/plugin-sdk/src/index.ts"; + +// The host menu files must match the copies in the Terminal plugin (scripts/menuSurfaceAudit.mjs), so they keep +// their own menu types. `pnpm check` fails when those types and the SDK types differ. +type Same = [A] extends [B] ? ([B] extends [A] ? true : false) : false; +const sameMenuTypes: [Same, Same] = [true, true]; + +const base: SessionServices = { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() }, +}; + +async function hostApi(services: Partial, views = false) { + let api!: PluginApi; + const session = views + ? new ExternalSession("org.test.sdk", { ...base, ...services }, () => {}, () => {}, new ContributionRegistry(), async () => {}, async () => "", () => {}, () => {}, () => {}) + : new ExternalSession("org.test.sdk", { ...base, ...services }, () => {}, () => {}, new ContributionRegistry()); + await session.start({ activate(value) { api = value; } }); + return { api, session }; +} + +test("feature checks find optional members, and missing members give an update message", () => { + const read = async () => new Uint8Array([1]); + const api = { workspace: { readBytes: read }, git: { status: async () => ({}) } } as unknown as PluginApi; + assert.equal(hasFeature(api, "workspace.readBytes"), true); + assert.equal(hasFeature(api, "git"), true); + assert.equal(hasFeature(api, "git.push"), false); + assert.equal(hasFeature(api, "pty"), false); + assert.deepEqual(missingFeatures(api, ["pty", "workspace.readBytes", "settings.subscribe"]), ["pty", "settings.subscribe"]); + assert.equal(requireFeature(api, "git"), (api as unknown as { git: unknown }).git); + assert.throws(() => requireFeature(api, "pty"), (error: unknown) => error instanceof MissingFeatureError + && error.name === "MissingFeatureError" && error.features.length === 1 && error.features[0] === "pty" + && error.message === "This plugin needs the terminal API (api.pty). Update RuneStone to a version that has this feature."); + assert.throws(() => requireFeatures(api, ["pty", "files", "workspace.readBytes"]), { + message: "This plugin needs the terminal API (api.pty) and the folder grant API (api.files). Update RuneStone to a version that has these features.", + }); + assert.doesNotThrow(() => requireFeatures(api, ["git", "workspace.readBytes"])); + assert.throws(() => hasFeature(api, "workspace.read" as never), TypeError); + assert.equal(describeFeature("ui.showActionMenu"), "the shared action menu (api.ui.showActionMenu)"); + assert.equal(API_VERSION, 1); +}); + +test("a required function stays bound to its parent object", async () => { + const workspace = { prefix: "ws:", async readOptional(this: { prefix: string }, file: string) { return this.prefix + file; } }; + const api = { workspace } as unknown as PluginApi; + const readOptional = requireFeature(api, "workspace.readOptional"); + assert.equal(await readOptional("a.md"), "ws:a.md"); +}); + +test("the current host gives every SDK feature when all services are present", async () => { + const pty = { open: async () => {}, write: async () => {}, resize: async () => {}, close: async () => {}, profiles: async () => [], openWindow: async () => {}, dictation: async () => {} }; + const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} }; + const git = { status: async () => ({ available: true, repository: true, branch: null, changes: [] }), diff: async () => "", stage: async () => {}, unstage: async () => {}, commit: async () => {}, push: async () => {}, pull: async () => {}, graph: async () => ({ commits: [] }), commitDetails: async () => ({ id: "", parents: [], author: "", date: "", message: "", files: [] }), commitDiff: async () => "", blame: async () => null }; + const backgrounds = { chooseFolder: async () => null, list: async () => [], read: async () => new Uint8Array() }; + const { api, session } = await hostApi({ + pty, files, git, backgrounds, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {}, + workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} }, + settings: { ...base.settings, subscribe: () => () => {} }, + }, true); + assert.deepEqual(missingFeatures(api, pluginFeatures), []); + await session.stop(); +}); + +test("the host without optional services lacks only the features that depend on them", async () => { + const { api, session } = await hostApi({}); + assert.deepEqual(missingFeatures(api, pluginFeatures).sort(), [ + "backgrounds", "closeView", "completion.transport", "files", "git", "git.commitDetails", "git.commitDiff", "git.graph", "git.pull", "git.push", + "openFile", "pty", "renameDocument", "replaceDocumentWithView", "replaceView", "settings.subscribe", + "workspace.create", "workspace.listMarkdown", "workspace.readBytes", "workspace.readMany", "workspace.readOptional", "workspace.subscribe", + ]); + await session.stop(); +}); + +test("the host uses the SDK icons and tooltip, so plugins get the same artwork and behavior", () => { + assert.equal(hostIcons.actionIcons, sdkIcons.actionIcons); + assert.equal(hostIcons.actionIcon, sdkIcons.actionIcon); + assert.equal(hostTooltip.attachTooltip, sdkTooltip.attachTooltip); + for (const [name, markup] of Object.entries(sdkIcons.actionIcons)) assert.match(markup, /^<(path|circle|rect|ellipse)\b/, name); +}); + +test("the host menu types are the SDK menu types", () => { + assert.deepEqual(sameMenuTypes, [true, true]); +}); + +test("the SDK build gives declaration imports with .js paths", () => { + assert.equal(declarationImports('export type * from "./api.ts";\nimport type { A } from \'../b.ts\';\ntype C = import("./c.ts").C;\nimport x from "node:fs";'), + 'export type * from "./api.js";\nimport type { A } from \'../b.js\';\ntype C = import("./c.js").C;\nimport x from "node:fs";'); +}); + +test("each SDK export has a source module, and the package is not for npm", async () => { + const folder = path.resolve("packages/plugin-sdk"); + const manifest = JSON.parse(await readFile(path.join(folder, "package.json"), "utf8")); + assert.equal(manifest.name, "@runestone/plugin-sdk"); + assert.equal(manifest.private, true); + assert.equal(manifest.license, "Apache-2.0"); + assert.equal(manifest.dependencies, undefined); + assert.deepEqual(manifest.files, ["dist", "README.md", "LICENSE", "NOTICE"]); + for (const file of ["README.md", "LICENSE", "NOTICE"]) await access(path.join(folder, file)); + for (const [entry, target] of Object.entries(manifest.exports as Record)) { + if (typeof target === "string") continue; + assert.equal(target.types.replace(/\.d\.ts$/, ""), target.default.replace(/\.js$/, ""), entry); + await access(path.join(folder, target.default.replace(/^\.\/dist\//, "src/").replace(/\.js$/, ".ts"))); + } +});