feat(plugins): support Markdown and UI-locale localization for Overview and What's New (#6776)

Plugin Overview and What's New rendered as plain text and ignored the UI language. plugin.toml gains optional description-file and change-notes-file (API 1.18, Markdown inside the package, UTF-8, at most 256 KiB); a shared loader validates them and localized siblings (description.zh-CN.md) in check, pack, install and index. Descriptions and change notes resolve per locale from locales/<tag>.json and those siblings, with English fallback, for installed, local catalog and marketplace plugins.

Markdown is rendered with lazily loaded marked and an isolated DOMPurify that strips scripts, event handlers, javascript:/file: links, styles and external resources, keeping marked out of the Settings window's boot graph.

Closes #6773


Merged with main: the pending-uninstall placeholder plugin now gets docs from its manifest.

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-29 13:31:13 +08:00
1 джерело fad9135f7a
коміт 10242d2e58
15 files changed
+1067 -65

No files matched your search

+41
Переглянути файл
@@ -49,11 +49,15 @@ pub struct Manifest {
pub name: String,
pub version: String,
pub description: String,
/// Markdown file for Settings › Plugins › Overview (`description-file`).
pub description_file: Option<PathBuf>,
pub authors: Vec<String>,
pub homepage: Option<String>,
pub license: Option<String>,
/// Release notes of this version (Settings › Plugins › What's New).
pub change_notes: Option<String>,
/// Markdown file for Settings › Plugins › What's New (`change-notes-file`).
pub change_notes_file: Option<PathBuf>,
/// Marketplace categories as declared (see [`Manifest::categories`]).
pub declared_categories: Vec<String>,
/// SVG shown in Settings › Plugins and the marketplace.
@@ -195,6 +199,8 @@ struct Raw {
#[serde(default)]
description: String,
#[serde(default)]
description_file: Option<PathBuf>,
#[serde(default)]
authors: Vec<String>,
#[serde(default)]
homepage: Option<String>,
@@ -203,6 +209,8 @@ struct Raw {
#[serde(default)]
change_notes: Option<String>,
#[serde(default)]
change_notes_file: Option<PathBuf>,
#[serde(default)]
categories: Vec<String>,
#[serde(default)]
icon: Option<PathBuf>,
@@ -286,10 +294,12 @@ impl Manifest {
name: raw.name,
version: raw.version,
description: raw.description,
description_file: raw.description_file,
authors: raw.authors,
homepage: raw.homepage,
license: raw.license,
change_notes: raw.change_notes,
change_notes_file: raw.change_notes_file,
declared_categories: raw.categories,
icon: raw.icon,
icon_dark: raw.icon_dark,
@@ -347,6 +357,14 @@ impl Manifest {
self.needs_api("`icon`", 2)?;
check_relative(icon, "icon")?;
}
if let Some(path) = &self.description_file {
self.needs_api("`description-file`", 18)?;
check_relative(path, "description-file")?;
}
if let Some(path) = &self.change_notes_file {
self.needs_api("`change-notes-file`", 18)?;
check_relative(path, "change-notes-file")?;
}
for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) {
if matches!(
cap,
@@ -1005,4 +1023,27 @@ mod net_ask_api_tests {
}
}
}
#[test]
fn doc_files_require_api_1_18_and_relative_paths() {
for field in ["description-file", "change-notes-file"] {
for engine in ["^1.17", "^1.18"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '{engine}'\n{field} = 'docs.md'\n"
);
let parsed = Manifest::parse(&manifest);
if engine == "^1.18" {
parsed.unwrap();
} else {
assert!(parsed.unwrap_err().contains("new in plugin API 1.18"), "{field} {engine}");
}
}
for bad in ["../escape.md", "/abs/path.md"] {
let manifest = format!(
"id = 'test'\nname = 'Test'\nversion = '0.1.0'\nengines.openidea = '^1.18'\n{field} = '{bad}'\n"
);
assert!(Manifest::parse(&manifest).unwrap_err().contains("relative path"), "{field} {bad}");
}
}
}
}
+9
Переглянути файл
@@ -27,6 +27,7 @@ use crate::MANIFEST_FILE;
use base64::Engine as _;
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
@@ -331,6 +332,9 @@ pub struct IndexEntry {
pub version: String,
#[serde(default)]
pub description: String,
/// Localized descriptions keyed by BCP 47 language tag (e.g. `zh-CN`).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub description_locales: BTreeMap<String, String>,
#[serde(default)]
pub authors: Vec<String>,
pub publisher: String,
@@ -358,6 +362,9 @@ pub struct IndexEntry {
/// This version's release notes (the manifest's `change-notes`).
#[serde(default)]
pub notes: Option<String>,
/// Localized release notes keyed by BCP 47 language tag (e.g. `zh-CN`).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub notes_locales: BTreeMap<String, String>,
/// Downloads of the plugin's packages, as counted by whoever serves them.
#[serde(default)]
pub downloads: Option<u64>,
@@ -715,6 +722,7 @@ mod tests {
name: id.into(),
version: "1.0.0".into(),
description: String::new(),
description_locales: BTreeMap::new(),
authors: Vec::new(),
publisher: publisher.into(),
download: format!("https://example.com/{id}.oiplugin"),
@@ -725,6 +733,7 @@ mod tests {
icon: None,
homepage: None,
notes: None,
notes_locales: BTreeMap::new(),
downloads: None,
featured: false,
suggest: Vec::new(),
+66 -4
Переглянути файл
@@ -22,7 +22,9 @@
mod templates;
use ide_extension::{Manifest, validate_plugin_id};
use ide_host::plugins::{PluginHost, market_href_reachable_from, plugin_icon, read_market_url, resolve_market_href};
use ide_host::plugins::{
PluginHost, market_href_reachable_from, plugin_docs, plugin_icon, read_market_url, resolve_market_href,
};
use ide_plugin::{Limits, PluginEngine};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode};
@@ -641,12 +643,15 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
Some(wasm) => engine.check_component(&engine.compile(&scratch.join(wasm))?)?,
None => None,
};
let pkg = ide_extension::Package::new(m.clone(), scratch.clone());
let docs = plugin_docs(&pkg)?;
let file = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
Ok::<_, String>(IndexEntry {
id: m.id.clone(),
name: m.name.clone(),
version: m.version.clone(),
description: m.description.clone(),
description: docs.description,
description_locales: docs.description_locales,
authors: m.authors.clone(),
publisher: signer,
download: base.map_or_else(|| file.clone(), |b| format!("{b}/{file}")),
@@ -654,9 +659,10 @@ fn cmd_index(args: &[String]) -> Result<(), String> {
capabilities: m.capabilities.all().map(|c| c.to_string()).collect(),
engine: package::engine_requirement(&m.engine, built_for.as_ref()),
categories: m.categories(),
icon: plugin_icon(&ide_extension::Package::new(m.clone(), scratch.clone()))?,
icon: plugin_icon(&pkg)?,
homepage: m.homepage.clone().filter(|h| !h.trim().is_empty()),
notes: m.change_notes.clone().filter(|n| !n.trim().is_empty()),
notes: docs.change_notes.filter(|n| !n.trim().is_empty()),
notes_locales: docs.change_notes_locales,
downloads: None,
featured: false,
suggest: Vec::new(),
@@ -1078,6 +1084,62 @@ mod tests {
assert!(index.plugins[0].icon.as_ref().expect("icon").light.contains("<rect"));
}
#[test]
fn check_validates_markdown_doc_files_and_index_carries_localized_docs() {
let tmp = tempfile::tempdir().unwrap();
let t = tmp.path();
let key = t.join("acme.key");
std::fs::write(&key, PublisherKey::from_seed([7; 32]).seed_base64()).unwrap();
let src = t.join("src");
let vars = templates::Vars { id: "acme.docs", name: "Docs", sdk: None };
for (rel, content) in templates::render(templates::Template::Theme, &vars) {
let path = src.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, content).unwrap();
}
let manifest = std::fs::read_to_string(src.join("plugin.toml"))
.unwrap()
.replace("engines.openidea = \"^1.0\"", "engines.openidea = \"^1.18\"");
std::fs::write(
src.join("plugin.toml"),
format!("description-file = \"description.md\"\nchange-notes-file = \"CHANGELOG.md\"\n{manifest}"),
)
.unwrap();
// Missing md file fails `check`.
let err = check(&src).unwrap_err();
assert!(err.contains("no such file"), "{err}");
// Valid English + zh-CN md files pass `check`, `pack`, and `index`.
std::fs::write(src.join("description.md"), "# English\n\n- Fast\n").unwrap();
std::fs::write(src.join("description.zh-CN.md"), "# 中文\n\n- 快速\n").unwrap();
std::fs::write(src.join("CHANGELOG.md"), "## 0.1.0\n\n- First release\n").unwrap();
std::fs::write(src.join("CHANGELOG.zh-CN.md"), "## 0.1.0\n\n- 首次发布\n").unwrap();
check(&src).unwrap();
let out = t.join("out");
std::fs::create_dir_all(&out).unwrap();
let (src_str, key_str) = (src.to_string_lossy().into_owned(), key.to_string_lossy().into_owned());
let package = out.join("acme.docs-0.1.0.oiplugin").to_string_lossy().into_owned();
cmd_pack(&strings(&[&src_str, "--key", &key_str, "--publisher", "acme", "--out", &package])).unwrap();
cmd_index(&strings(&[out.to_str().unwrap(), "--publisher", "acme", "--key", &key_str])).unwrap();
let index = Index::parse(&std::fs::read_to_string(out.join("index.json")).unwrap()).unwrap();
let entry = &index.plugins[0];
assert!(entry.description.contains("# English"));
assert_eq!(entry.description_locales.get("zh-CN").map(String::as_str), Some("# 中文\n\n- 快速\n"));
assert_eq!(entry.notes.as_deref(), Some("## 0.1.0\n\n- First release\n"));
assert_eq!(entry.notes_locales.get("zh-CN").map(String::as_str), Some("## 0.1.0\n\n- 首次发布\n"));
// Invalid extension fails `check`.
std::fs::write(src.join("notes.txt"), "plain").unwrap();
let bad = std::fs::read_to_string(src.join("plugin.toml"))
.unwrap()
.replace("change-notes-file = \"CHANGELOG.md\"", "change-notes-file = \"notes.txt\"");
std::fs::write(src.join("plugin.toml"), bad).unwrap();
let err = check(&src).unwrap_err();
assert!(err.contains(".md or .markdown"), "{err}");
}
/// `cargo test` of a new Rust plugin (its own tests against the mock host) with this SDK.
#[test]
fn the_command_template_builds_against_the_sdk() {
+297
Переглянути файл
@@ -0,0 +1,297 @@
//! Plugin documentation: Overview (`description` / `description-file`) and
//! What's New (`change-notes` / `change-notes-file`), with per-locale
//! translations from `locales/<tag>.json` and sibling `<stem>.<tag>.<ext>` files.
use ide_extension::{LOCALES_DIR, Manifest, Package, check_relative};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// Maximum size of a single Markdown documentation file referenced by a manifest.
pub const MAX_PLUGIN_DOC: usize = 256 << 10;
/// Resolved Overview and What's New texts of a plugin package, plus the package
/// files they reference.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PluginDocs {
pub description: String,
pub change_notes: Option<String>,
pub description_locales: BTreeMap<String, String>,
pub change_notes_locales: BTreeMap<String, String>,
/// Package-relative Markdown files referenced (base + localized siblings).
pub files: Vec<PathBuf>,
}
impl PluginDocs {
pub fn from_manifest(manifest: &Manifest) -> Self {
Self {
description: manifest.description.clone(),
change_notes: manifest.change_notes.clone(),
description_locales: BTreeMap::new(),
change_notes_locales: BTreeMap::new(),
files: Vec::new(),
}
}
}
pub(super) fn locale_tag_ok(tag: &str) -> bool {
let mut parts = tag.split('-');
let language = parts.next().unwrap_or_default();
(2..=3).contains(&language.len())
&& language.chars().all(|c| c.is_ascii_alphabetic())
&& parts.all(|p| (1..=8).contains(&p.len()) && p.chars().all(|c| c.is_ascii_alphanumeric()))
}
fn is_markdown_path(path: &Path) -> bool {
path.extension()
.and_then(|e| e.to_str())
.is_some_and(|e| e.eq_ignore_ascii_case("md") || e.eq_ignore_ascii_case("markdown"))
}
fn read_markdown_file(pkg: &Package, path: &Path, what: &str) -> Result<String, String> {
check_relative(path, what)?;
if !is_markdown_path(path) {
return Err(format!("{what} {:?}: must be a .md or .markdown file", path.display()));
}
let text = pkg.read_text(path)?;
if text.len() > MAX_PLUGIN_DOC {
return Err(format!("{}: larger than {} KiB", path.display(), MAX_PLUGIN_DOC >> 10));
}
Ok(text)
}
/// Discovers sibling `<stem>.<tag>.<ext>` Markdown files next to `base` (e.g.
/// `description.zh-CN.md` next to `description.md`), validates each one, and
/// returns `(tag -> text, relative_files)`.
fn discover_localized_markdown(
pkg: &Package,
base: &Path,
what: &str,
) -> Result<(BTreeMap<String, String>, Vec<PathBuf>), String> {
let Some(stem) = base.file_stem().and_then(|s| s.to_str()) else {
return Ok((BTreeMap::new(), Vec::new()));
};
let Some(ext) = base.extension().and_then(|e| e.to_str()) else {
return Ok((BTreeMap::new(), Vec::new()));
};
let parent_rel = base.parent().unwrap_or_else(|| Path::new(""));
let parent_dir = pkg.dir.join(parent_rel);
let Ok(entries) = std::fs::read_dir(&parent_dir) else {
return Ok((BTreeMap::new(), Vec::new()));
};
let mut names: Vec<String> = entries.filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
names.sort();
let prefix = format!("{stem}.");
let suffix_len = ext.len() + 1; // ".<ext>"
let mut localized = BTreeMap::new();
let mut files = Vec::new();
for name in names {
if name.len() <= prefix.len() + suffix_len || !name.starts_with(&prefix) {
continue;
}
let Some((before_ext, file_ext)) = name.rsplit_once('.') else {
continue;
};
if !file_ext.eq_ignore_ascii_case(ext) {
continue;
}
let Some(tag) = before_ext.strip_prefix(&prefix) else {
continue;
};
if !locale_tag_ok(tag) {
continue;
}
let rel = if parent_rel.as_os_str().is_empty() { PathBuf::from(&name) } else { parent_rel.join(&name) };
let text = read_markdown_file(pkg, &rel, what)?;
localized.insert(tag.to_owned(), text);
files.push(rel);
}
Ok((localized, files))
}
/// Reads valid `locales/<tag>.json` catalogs from `pkg` (malformed catalogs are
/// ignored here and reported by `ui_points::locales` during `prepare`).
fn read_locale_catalogs(pkg: &Package) -> BTreeMap<String, BTreeMap<String, String>> {
let dir = Path::new(LOCALES_DIR);
let Ok(entries) = std::fs::read_dir(pkg.dir.join(dir)) else {
return BTreeMap::new();
};
let mut out = BTreeMap::new();
for entry in entries.flatten() {
let Ok(name) = entry.file_name().into_string() else { continue };
let Some(tag) = name.strip_suffix(".json") else { continue };
if !locale_tag_ok(tag) {
continue;
}
let Ok(text) = pkg.read_text(&dir.join(&name)) else { continue };
let Ok(raw) = serde_json::from_str::<BTreeMap<String, Value>>(&text) else { continue };
let catalog: BTreeMap<String, String> =
raw.into_iter().filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_owned()))).collect();
out.insert(tag.to_owned(), catalog);
}
out
}
fn lookup_translation<'a>(catalog: &'a BTreeMap<String, String>, source: &str) -> Option<&'a str> {
if let Some(v) = catalog.get(source) {
return Some(v.as_str());
}
let trimmed = source.trim();
if trimmed != source {
return catalog.get(trimmed).map(String::as_str);
}
None
}
/// Reads and validates a plugin package's Overview (`description` / `description-file`)
/// and What's New (`change-notes` / `change-notes-file`), along with their
/// per-locale translations from `locales/<tag>.json` and localized Markdown siblings.
pub fn plugin_docs(pkg: &Package) -> Result<PluginDocs, String> {
let mut files = Vec::new();
let description = match &pkg.manifest.description_file {
Some(path) => {
let text = read_markdown_file(pkg, path, "description-file")?;
files.push(path.clone());
text
}
None => pkg.manifest.description.clone(),
};
let change_notes = match &pkg.manifest.change_notes_file {
Some(path) => {
let text = read_markdown_file(pkg, path, "change-notes-file")?;
files.push(path.clone());
Some(text).filter(|s| !s.trim().is_empty())
}
None => pkg.manifest.change_notes.clone(),
};
let mut description_locales = BTreeMap::new();
let mut change_notes_locales = BTreeMap::new();
for (tag, catalog) in read_locale_catalogs(pkg) {
if !description.trim().is_empty()
&& let Some(tr) = lookup_translation(&catalog, &description)
{
description_locales.insert(tag.clone(), tr.to_owned());
}
if let Some(notes) = &change_notes
&& !notes.trim().is_empty()
&& let Some(tr) = lookup_translation(&catalog, notes)
{
change_notes_locales.insert(tag.clone(), tr.to_owned());
}
}
if let Some(path) = &pkg.manifest.description_file {
let (localized, extra_files) = discover_localized_markdown(pkg, path, "description-file")?;
description_locales.extend(localized);
files.extend(extra_files);
}
if let Some(path) = &pkg.manifest.change_notes_file {
let (localized, extra_files) = discover_localized_markdown(pkg, path, "change-notes-file")?;
change_notes_locales.extend(localized);
files.extend(extra_files);
}
files.sort();
files.dedup();
Ok(PluginDocs { description, change_notes, description_locales, change_notes_locales, files })
}
#[cfg(test)]
mod tests {
use super::*;
fn pkg_with(dir: &Path, extra_toml: &str) -> Package {
let src = format!(
"id = \"acme.docs\"\nname = \"Docs\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.18\"\n{extra_toml}"
);
let manifest = Manifest::parse(&src).unwrap();
Package::new(manifest, dir.to_path_buf())
}
#[test]
fn inline_fields_and_locale_catalog_translations() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("locales")).unwrap();
std::fs::write(
tmp.path().join("locales/zh-CN.json"),
r#"{
"Plain description.": "纯文本描述。",
"0.2.0 — fixes\n0.1.0 — init": "0.2.0 — 修复\n0.1.0 — 初始版本"
}"#,
)
.unwrap();
let pkg = pkg_with(
tmp.path(),
"description = \"Plain description.\"\nchange-notes = \"\"\"\n0.2.0 — fixes\n0.1.0 — init\n\"\"\"\n",
);
let docs = plugin_docs(&pkg).unwrap();
assert_eq!(docs.description, "Plain description.");
assert_eq!(docs.description_locales.get("zh-CN").map(String::as_str), Some("纯文本描述。"));
assert_eq!(docs.change_notes_locales.get("zh-CN").map(String::as_str), Some("0.2.0 — 修复\n0.1.0 — 初始版本"));
assert!(docs.files.is_empty());
}
#[test]
fn markdown_files_and_localized_siblings_are_loaded_and_tracked() {
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("docs")).unwrap();
std::fs::create_dir_all(tmp.path().join("locales")).unwrap();
std::fs::write(tmp.path().join("docs/overview.md"), "# English Overview\n\n- Item 1\n").unwrap();
std::fs::write(tmp.path().join("docs/overview.zh-CN.md"), "# 中文概览\n\n- 条目 1\n").unwrap();
std::fs::write(tmp.path().join("docs/overview.fr.md"), "# Aperçu\n").unwrap();
std::fs::write(tmp.path().join("CHANGELOG.md"), "## 1.0.0\n\n- Initial\n").unwrap();
std::fs::write(tmp.path().join("CHANGELOG.zh-CN.md"), "## 1.0.0\n\n- 首发\n").unwrap();
// Sibling localized .md takes precedence over locales/<tag>.json for the same tag.
std::fs::write(tmp.path().join("locales/zh-CN.json"), r##"{ "# English Overview\n\n- Item 1": "from json" }"##)
.unwrap();
let pkg =
pkg_with(tmp.path(), "description-file = \"docs/overview.md\"\nchange-notes-file = \"CHANGELOG.md\"\n");
let docs = plugin_docs(&pkg).unwrap();
assert_eq!(docs.description, "# English Overview\n\n- Item 1\n");
assert_eq!(docs.description_locales.get("zh-CN").map(String::as_str), Some("# 中文概览\n\n- 条目 1\n"));
assert_eq!(docs.description_locales.get("fr").map(String::as_str), Some("# Aperçu\n"));
assert_eq!(docs.change_notes.as_deref(), Some("## 1.0.0\n\n- Initial\n"));
assert_eq!(docs.change_notes_locales.get("zh-CN").map(String::as_str), Some("## 1.0.0\n\n- 首发\n"));
assert_eq!(
docs.files,
vec![
PathBuf::from("CHANGELOG.md"),
PathBuf::from("CHANGELOG.zh-CN.md"),
PathBuf::from("docs/overview.fr.md"),
PathBuf::from("docs/overview.md"),
PathBuf::from("docs/overview.zh-CN.md"),
]
);
}
#[test]
fn rejects_missing_non_markdown_non_utf8_and_oversized_files() {
let tmp = tempfile::tempdir().unwrap();
// Missing file
let missing = pkg_with(tmp.path(), "description-file = \"missing.md\"\n");
assert!(plugin_docs(&missing).unwrap_err().contains("no such file"));
// Non-markdown extension
std::fs::write(tmp.path().join("notes.txt"), "hello").unwrap();
let bad_ext = pkg_with(tmp.path(), "change-notes-file = \"notes.txt\"\n");
assert!(plugin_docs(&bad_ext).unwrap_err().contains(".md or .markdown"));
// Invalid UTF-8 in localized sibling
std::fs::write(tmp.path().join("description.md"), "# OK\n").unwrap();
std::fs::write(tmp.path().join("description.zh-CN.md"), [0xff, 0xfe, 0xfd]).unwrap();
let bad_utf8 = pkg_with(tmp.path(), "description-file = \"description.md\"\n");
assert!(plugin_docs(&bad_utf8).unwrap_err().contains("not UTF-8"));
std::fs::remove_file(tmp.path().join("description.zh-CN.md")).unwrap();
// Oversized file
let huge = "a".repeat(MAX_PLUGIN_DOC + 1);
std::fs::write(tmp.path().join("CHANGELOG.md"), huge).unwrap();
let oversized = pkg_with(tmp.path(), "change-notes-file = \"CHANGELOG.md\"\n");
assert!(plugin_docs(&oversized).unwrap_err().contains("larger than"));
}
}
+27 -11
Переглянути файл
@@ -24,7 +24,8 @@ mod console_rules;
mod database;
mod dependencies;
pub(crate) mod diagnostics;
pub mod endpoints;
pub mod docs;
mod endpoints;
mod event_paths;
mod execution;
mod external_watch;
@@ -65,6 +66,7 @@ mod websocket;
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
pub use build_graph::{BuildGraph, GradleModule};
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, plugin_docs};
pub(crate) use hover::merge as merge_hover;
pub use icons::{
MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix,
@@ -229,6 +231,8 @@ struct LoadedPlugin {
pkg: Package,
/// Read at load so disabled and failed plugins show it too.
icon: Option<ide_extension::package::PluginIcon>,
/// Resolved Overview / What's New docs and their locale variants.
docs: PluginDocs,
/// The manifest failed to parse: `pkg` is a placeholder.
invalid: bool,
source: PluginSource,
@@ -594,6 +598,7 @@ impl PluginHost {
self.plugins.write().insert(
pending.id,
Arc::new(LoadedPlugin {
docs: PluginDocs::from_manifest(&manifest),
pkg: Package::new(manifest, dir),
icon: None,
invalid: false,
@@ -952,11 +957,12 @@ impl PluginHost {
};
let needs_consent =
grant.is_none() || publisher.is_none() || signer_changed || !capabilities.iter().all(answered);
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(m));
Ok(InstallPreview {
id: m.id.clone(),
name: m.name.clone(),
version: m.version.clone(),
description: m.description.clone(),
description: docs.description,
authors: m.authors.clone(),
has_code: m.wasm.is_some(),
capabilities,
@@ -2758,6 +2764,7 @@ impl PluginHost {
.filter(|w| !dir.join(w).is_file())
.map(|w| format!("{} is missing; build the plugin first", w.display())),
};
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&m));
out.push(CatalogPlugin {
has_code: m.wasm.is_some(),
capabilities: m
@@ -2769,10 +2776,12 @@ impl PluginHost {
id: m.id,
name: m.name,
version: m.version,
description: m.description,
description: docs.description,
description_locales: docs.description_locales,
authors: m.authors,
homepage: m.homepage,
change_notes: m.change_notes,
change_notes: docs.change_notes,
change_notes_locales: docs.change_notes_locales,
icon: plugin_icon(&pkg).ok().flatten(),
path: dir.into(),
problem,
@@ -2881,15 +2890,16 @@ impl PluginHost {
self.plugins.read().values().any(|p| p.dir() == dir)
}
/// Validates the manifest's icon and every declaration of `pkg`; the
/// icon files join the package files the declarations reference.
/// Validates the manifest's icon, docs and every declaration of `pkg`; the
/// icon and doc files join the package files the declarations reference.
fn prepare(&self, pkg: &Package) -> Result<ide_extension::PreparedSet, String> {
plugin_icon(pkg)?;
let docs = plugin_docs(pkg)?;
let mut set = self.registry.prepare(pkg)?;
check_setting_grants(pkg)?;
for icon in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten() {
if !set.files.contains(icon) {
set.files.push(icon.clone());
for file in [&pkg.manifest.icon, &pkg.manifest.icon_dark].into_iter().flatten().chain(&docs.files) {
if !set.files.contains(file) {
set.files.push(file.clone());
}
}
Ok(set)
@@ -2956,8 +2966,10 @@ impl PluginHost {
// Installed copies don't change: their validated UI declarations are indexed.
pkg = pkg.with_digest(digest.trim());
}
let docs = plugin_docs(&pkg).unwrap_or_else(|_| PluginDocs::from_manifest(&pkg.manifest));
let plugin = Arc::new(LoadedPlugin {
icon: plugin_icon(&pkg).ok().flatten(),
docs,
pkg,
invalid,
source,
@@ -3571,10 +3583,12 @@ impl PluginHost {
id: m.id.clone(),
name: m.name.clone(),
version: m.version.clone(),
description: m.description.clone(),
description: p.docs.description.clone(),
description_locales: p.docs.description_locales.clone(),
authors: m.authors.clone(),
homepage: m.homepage.clone(),
change_notes: m.change_notes.clone(),
change_notes: p.docs.change_notes.clone(),
change_notes_locales: p.docs.change_notes_locales.clone(),
icon: p.icon.clone(),
java_agent: self.java_agents.for_plugin(&m.id).map(|agent| {
let pin = self
@@ -3760,10 +3774,12 @@ fn placeholder_manifest(dir: &Path) -> Manifest {
name,
version: "0.0.0".into(),
description: String::new(),
description_file: None,
authors: Vec::new(),
homepage: None,
license: None,
change_notes: None,
change_notes_file: None,
declared_categories: Vec::new(),
icon: None,
icon_dark: None,
+8
Переглянути файл
@@ -97,9 +97,13 @@ pub struct PluginInfo {
pub name: String,
pub version: String,
pub description: String,
#[serde(default)]
pub description_locales: BTreeMap<String, String>,
pub authors: Vec<String>,
pub homepage: Option<String>,
pub change_notes: Option<String>,
#[serde(default)]
pub change_notes_locales: BTreeMap<String, String>,
pub icon: Option<PluginIcon>,
/// The Java agent this plugin declares, and whether it is still approved.
pub java_agent: Option<PluginJavaAgent>,
@@ -207,9 +211,13 @@ pub struct CatalogPlugin {
pub name: String,
pub version: String,
pub description: String,
#[serde(default)]
pub description_locales: BTreeMap<String, String>,
pub authors: Vec<String>,
pub homepage: Option<String>,
pub change_notes: Option<String>,
#[serde(default)]
pub change_notes_locales: BTreeMap<String, String>,
pub icon: Option<PluginIcon>,
/// Package directory; install with `install_from_dir(path)`.
pub path: ide_core::IpcPath,
+2
Переглянути файл
@@ -169,6 +169,7 @@ fn signed(
name: "Hello".into(),
version: version.into(),
description: String::new(),
description_locales: Default::default(),
authors: vec![],
publisher: publisher.into(),
download: out.file_name().unwrap().to_string_lossy().into_owned(),
@@ -179,6 +180,7 @@ fn signed(
icon: None,
homepage: None,
notes: None,
notes_locales: Default::default(),
downloads: None,
featured: false,
suggest: vec![],
+21 -19
Переглянути файл
@@ -41,24 +41,26 @@ mac = "Meta+Alt+C"
## Top-level fields
| Field | Required | Description |
| ------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | Yes | Segments of `[a-z0-9][a-z0-9_-]*` joined by `.`, at most 64 characters. The part before the first `.` is the publisher namespace (`acme` in `acme.word-tools`); a signed package must use its publisher's prefix. |
| `name` | Yes | Display name. Must not be empty. |
| `version` | Yes | A semantic version such as `1.2.0`. |
| `description` | No | One or two sentences shown in Settings › Plugins and the marketplace. |
| `authors` | No | List of strings. |
| `homepage` | No | URL shown in the plugin's details. |
| `license` | No | License name, for example an SPDX id. |
| `change-notes` | No | Release notes shown under **What's New** in the plugin's details. |
| `categories` | No | Up to 3 marketplace categories (see below). |
| `icon` | No | Package SVG for Settings › Plugins and the marketplace. At most 16 KiB, sanitised (no scripts, external references or `foreignObject`); an invalid icon fails the package. Needs `engines.openidea = "^1.2"`. |
| `icon-dark` | No | Variant used with dark themes. Needs `icon`. |
| `engines.openidea` | Yes | A semver requirement on the plugin API, for example `"^1.4"`. The IDE refuses a package whose requirement doesn't match its API. See [API versions](/en/plugins/versioning). |
| `wasm` | No | Path of the component. Omit it for data-only plugins. |
| `activation` | No | Events that load the code (see below). Needs `wasm`. |
| `[capabilities]` | No | `required` and `optional` lists of capability strings. See [Permissions and capabilities](/en/plugins/capabilities). |
| `[contributes]` | No | Contribution points (see below). |
| Field | Required | Description |
| ------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | Yes | Segments of `[a-z0-9][a-z0-9_-]*` joined by `.`, at most 64 characters. The part before the first `.` is the publisher namespace (`acme` in `acme.word-tools`); a signed package must use its publisher's prefix. |
| `name` | Yes | Display name. Must not be empty. |
| `version` | Yes | A semantic version such as `1.2.0`. |
| `description` | No | Plain text or Markdown shown under **Overview** in Settings › Plugins and the marketplace. |
| `description-file` | No | Package Markdown file (`.md` / `.markdown`, up to 256 KiB) for **Overview**. Sibling `<stem>.<tag>.<ext>` files (e.g. `description.zh-CN.md`) provide per-language versions. Needs `engines.openidea = "^1.18"`. |
| `authors` | No | List of strings. |
| `homepage` | No | URL shown in the plugin's details. |
| `license` | No | License name, for example an SPDX id. |
| `change-notes` | No | Plain text or Markdown release notes shown under **What's New** in the plugin's details. |
| `change-notes-file` | No | Package Markdown file (`.md` / `.markdown`, up to 256 KiB) for **What's New**. Sibling `<stem>.<tag>.<ext>` files (e.g. `CHANGELOG.zh-CN.md`) provide per-language versions. Needs `engines.openidea = "^1.18"`. |
| `categories` | No | Up to 3 marketplace categories (see below). |
| `icon` | No | Package SVG for Settings › Plugins and the marketplace. At most 16 KiB, sanitised (no scripts, external references or `foreignObject`); an invalid icon fails the package. Needs `engines.openidea = "^1.2"`. |
| `icon-dark` | No | Variant used with dark themes. Needs `icon`. |
| `engines.openidea` | Yes | A semver requirement on the plugin API, for example `"^1.4"`. The IDE refuses a package whose requirement doesn't match its API. See [API versions](/en/plugins/versioning). |
| `wasm` | No | Path of the component. Omit it for data-only plugins. |
| `activation` | No | Events that load the code (see below). Needs `wasm`. |
| `[capabilities]` | No | `required` and `optional` lists of capability strings. See [Permissions and capabilities](/en/plugins/capabilities). |
| `[contributes]` | No | Contribution points (see below). |
Unknown top-level fields are an error.
@@ -143,7 +145,7 @@ A package translates its own text with `locales/<tag>.json` files (`fr.json`, `z
{ "Count Words": "Compter les mots", "Refresh": "Actualiser" }
```
The IDE applies the catalog of the selected UI language (the exact tag, then the language, then a variant such as `zh-TW` for `zh`) to the titles, categories, labels and tooltips the manifest declares, and to the text views show. Text the plugin builds itself (notifications, error messages, `html` bodies) is not translated: read `host::locale()` when building it. `openidea-plugin check` refuses a catalog that is not a JSON object of strings.
The IDE applies the catalog of the selected UI language (the exact tag, then the language, then a variant such as `zh-TW` for `zh`) to `description`, `change-notes`, the titles, categories, labels and tooltips the manifest declares, and to the text views show. For longer Overview and What's New documents referenced via `description-file` or `change-notes-file`, add sibling Markdown files such as `description.zh-CN.md` or `CHANGELOG.zh-CN.md` alongside the English file. Text the plugin builds itself (notifications, error messages, `html` bodies) is not translated: read `host::locale()` when building it. `openidea-plugin check` refuses a catalog that is not a JSON object of strings.
## The 0.1 format
+21 -19
Переглянути файл
@@ -41,24 +41,26 @@ mac = "Meta+Alt+C"
## 顶层字段
| 字段 | 必填 | 说明 |
| ------------------ | ---- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | 是 | 由 `.` 连接的若干段,每段匹配 `[a-z0-9][a-z0-9_-]*`,总长不超过 64。第一个 `.` 之前是发布者命名空间(`acme.word-tools` 中的 `acme`);签名的包必须使用其发布者的前缀。 |
| `name` | 是 | 显示名称,不能为空。 |
| `version` | 是 | 语义化版本,如 `1.2.0`。 |
| `description` | 否 | 一两句话,显示在 设置 › 插件 和插件市场中。 |
| `authors` | 否 | 字符串列表。 |
| `homepage` | 否 | 显示在插件详情中的 URL。 |
| `license` | 否 | 许可证名称,例如 SPDX 标识。 |
| `change-notes` | 否 | 发布说明,显示在插件详情的 **新功能** 中。 |
| `categories` | 否 | 最多 3 个插件市场分类(见下文)。 |
| `icon` | 否 | 插件包的 SVG 图标,用于 设置 › 插件 和插件市场。不超过 16 KiB,会被净化(不允许脚本、外部引用和 `foreignObject`);图标无效时整个包被拒绝。需要 `engines.openidea = "^1.2"`。 |
| `icon-dark` | 否 | 深色主题下使用的图标变体,需要同时有 `icon`。 |
| `engines.openidea` | 是 | 对插件 API 的 semver 版本要求,例如 `"^1.4"`。要求与 IDE 的 API 不匹配时,IDE 拒绝这个包。见 [API 版本与兼容](/zh/plugins/versioning)。 |
| `wasm` | 否 | 组件路径。纯数据插件不写。 |
| `activation` | 否 | 触发加载代码的事件(见下文),需要有 `wasm`。 |
| `[capabilities]` | 否 | `required` 和 `optional` 两个能力字符串列表。见 [权限与能力](/zh/plugins/capabilities)。 |
| `[contributes]` | 否 | 贡献点(见下文)。 |
| 字段 | 必填 | 说明 |
| ------------------- | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | 是 | 由 `.` 连接的若干段,每段匹配 `[a-z0-9][a-z0-9_-]*`,总长不超过 64。第一个 `.` 之前是发布者命名空间(`acme.word-tools` 中的 `acme`);签名的包必须使用其发布者的前缀。 |
| `name` | 是 | 显示名称,不能为空。 |
| `version` | 是 | 语义化版本,如 `1.2.0`。 |
| `description` | 否 | 纯文本或 Markdown,显示在 设置 › 插件 的 **概览** 和插件市场中。 |
| `description-file` | 否 | 包内 Markdown 文件(`.md` / `.markdown`,不超过 256 KiB),用于 **概览**。同目录的 `<stem>.<tag>.<ext>` 文件(如 `description.zh-CN.md`)提供对应语言版本。需要 `engines.openidea = "^1.18"`。 |
| `authors` | 否 | 字符串列表。 |
| `homepage` | 否 | 显示在插件详情中的 URL。 |
| `license` | 否 | 许可证名称,例如 SPDX 标识。 |
| `change-notes` | 否 | 纯文本或 Markdown 发布说明,显示在插件详情的 **新功能** 中。 |
| `change-notes-file` | 否 | 包内 Markdown 文件(`.md` / `.markdown`,不超过 256 KiB),用于 **新功能**。同目录的 `<stem>.<tag>.<ext>` 文件(如 `CHANGELOG.zh-CN.md`)提供对应语言版本。需要 `engines.openidea = "^1.18"`。 |
| `categories` | 否 | 最多 3 个插件市场分类(见下文)。 |
| `icon` | 否 | 插件包的 SVG 图标,用于 设置 › 插件 和插件市场。不超过 16 KiB,会被净化(不允许脚本、外部引用和 `foreignObject`);图标无效时整个包被拒绝。需要 `engines.openidea = "^1.2"`。 |
| `icon-dark` | 否 | 深色主题下使用的图标变体,需要同时有 `icon`。 |
| `engines.openidea` | 是 | 对插件 API 的 semver 版本要求,例如 `"^1.4"`。要求与 IDE 的 API 不匹配时,IDE 拒绝这个包。见 [API 版本与兼容](/zh/plugins/versioning)。 |
| `wasm` | 否 | 组件路径。纯数据插件不写。 |
| `activation` | 否 | 触发加载代码的事件(见下文),需要有 `wasm`。 |
| `[capabilities]` | 否 | `required` 和 `optional` 两个能力字符串列表。见 [权限与能力](/zh/plugins/capabilities)。 |
| `[contributes]` | 否 | 贡献点(见下文)。 |
未知的顶层字段会报错。
@@ -143,7 +145,7 @@ optional = ["net:api.openai.com", "secrets"]
{ "Count Words": "Compter les mots", "Refresh": "Actualiser" }
```
IDE 根据当前界面语言选用目录(先精确匹配 tag,再匹配语言,再匹配变体,例如 `zh` 可以用 `zh-TW`),应用到清单声明的标题、分类、标签、提示,以及视图显示的文本。插件自己拼出来的文本(通知、错误信息、`html` 内容)不会被翻译:生成这些文本时读取 `host::locale()`。如果目录不是“字符串到字符串”的 JSON 对象,`openidea-plugin check` 会拒绝它。
IDE 根据当前界面语言选用目录(先精确匹配 tag,再匹配语言,再匹配变体,例如 `zh` 可以用 `zh-TW`),应用到 `description`、`change-notes`、清单声明的标题、分类、标签、提示,以及视图显示的文本。对于通过 `description-file` 或 `change-notes-file` 引用的长文档,可在英文文件同目录放置对应语言的 Markdown 文件(如 `description.zh-CN.md`、`CHANGELOG.zh-CN.md`)。插件自己拼出来的文本(通知、错误信息、`html` 内容)不会被翻译:生成这些文本时读取 `host::locale()`。如果目录不是“字符串到字符串”的 JSON 对象,`openidea-plugin check` 会拒绝它。
## 0.1 格式
+8
Переглянути файл
@@ -4448,9 +4448,11 @@ export type CatalogPlugin = {
name: string,
version: string,
description: string,
descriptionLocales?: { [key in string]: string },
authors: string[],
homepage: string | null,
changeNotes: string | null,
changeNotesLocales?: { [key in string]: string },
icon: PluginIcon | null,
/** Package directory; install with `install_from_dir(path)`. */
path: IpcPath,
@@ -8941,6 +8943,8 @@ export type IndexEntry = {
name: string,
version: string,
description?: string,
/** Localized descriptions keyed by BCP 47 language tag (e.g. `zh-CN`). */
descriptionLocales?: { [key in string]: string },
authors?: string[],
publisher: string,
/** The package, relative to the index (or an absolute URL). */
@@ -8965,6 +8969,8 @@ export type IndexEntry = {
homepage?: string | null,
/** This version's release notes (the manifest's `change-notes`). */
notes?: string | null,
/** Localized release notes keyed by BCP 47 language tag (e.g. `zh-CN`). */
notesLocales?: { [key in string]: string },
/** Downloads of the plugin's packages, as counted by whoever serves them. */
downloads?: number | null,
/** Picked by the marketplace's maintainers. */
@@ -11606,9 +11612,11 @@ export type PluginInfo = {
name: string,
version: string,
description: string,
descriptionLocales?: { [key in string]: string },
authors: string[],
homepage: string | null,
changeNotes: string | null,
changeNotesLocales?: { [key in string]: string },
icon: PluginIcon | null,
/** The Java agent this plugin declares, and whether it is still approved. */
javaAgent: PluginJavaAgent | null,
+85 -1
Переглянути файл
@@ -261,11 +261,95 @@
}
.notes {
margin: 10px 0 0;
max-width: 640px;
color: var(--fg);
font: inherit;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.markdown {
line-height: 1.55;
overflow-wrap: anywhere;
}
.markdownPlain {
white-space: pre-wrap;
}
.markdown > :first-child {
margin-top: 0;
}
.markdown > :last-child {
margin-bottom: 0;
}
.markdown :where(h1, h2, h3, h4, h5, h6) {
margin: 14px 0 6px;
color: var(--fg-strong);
font-weight: 600;
line-height: 1.3;
}
.markdown :where(h1) {
font-size: 1.25em;
}
.markdown :where(h2) {
font-size: 1.125em;
}
.markdown :where(h3, h4, h5, h6) {
font-size: 1em;
}
.markdown :where(p) {
margin: 0 0 8px;
}
.markdown :where(ul, ol) {
margin: 0 0 8px;
padding-left: 20px;
}
.markdown :where(li) {
margin: 2px 0;
}
.markdown :where(a) {
color: var(--link);
text-decoration: none;
}
.markdown :where(a:hover) {
color: var(--link-hover);
text-decoration: underline;
}
.markdown :where(code) {
padding: 1px 4px;
border-radius: var(--radius-small);
background: var(--bg-input);
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.markdown :where(pre) {
overflow: auto;
margin: 0 0 10px;
padding: 8px 10px;
border-radius: var(--radius-small);
background: var(--bg-input);
}
.markdown :where(pre code) {
padding: 0;
background: none;
}
.markdown :where(blockquote) {
margin: 0 0 8px;
padding-left: 10px;
border-left: 2px solid var(--border-strong);
color: var(--fg-secondary);
}
.markdown :where(hr) {
height: 1px;
margin: 12px 0;
border: 0;
background: var(--border);
}
.markdown :where(table) {
margin: 0 0 10px;
border-collapse: collapse;
}
.markdown :where(th, td) {
padding: 4px 8px;
border: 1px solid var(--border);
}
.titleLine {
display: flex;
align-items: center;
+36 -11
Переглянути файл
@@ -73,7 +73,8 @@ import { createPortal } from "react-dom";
import styles from "./PluginsPage.module.css";
import { pluginsBackend } from "./backend";
import { confirm } from "@/workbench/messages";
import { tx } from "@/platform/i18n";
import { tx, useI18n } from "@/platform/i18n";
import { PluginMarkdown, localizePluginText } from "./pluginMarkdown";
const STATUS: Record<
PluginStatus,
@@ -124,14 +125,26 @@ export function filterPlugins(plugins: readonly PluginInfo[], query: string): Pl
const q = query.trim().toLowerCase();
if (!q) return [...plugins];
return plugins.filter((p) =>
matches([p.name, p.id, p.description, ...p.authors, ...p.contributions.map((c) => c.label)], q),
matches(
[
p.name,
p.id,
p.description,
...Object.values(p.descriptionLocales ?? {}),
...p.authors,
...p.contributions.map((c) => c.label),
],
q,
),
);
}
export function filterCatalog(catalog: readonly CatalogPlugin[], query: string): CatalogPlugin[] {
const q = query.trim().toLowerCase();
if (!q) return [...catalog];
return catalog.filter((p) => matches([p.name, p.id, p.description, ...p.authors], q));
return catalog.filter((p) =>
matches([p.name, p.id, p.description, ...Object.values(p.descriptionLocales ?? {}), ...p.authors], q),
);
}
/** What the Available tab offers for a catalog package given what is installed. */
@@ -441,8 +454,8 @@ function DetailTabs({ notes, overview }: { notes: string | null; overview: React
/>
{tab === "overview" ? (
overview
) : notes ? (
<pre className={styles.notes}>{notes.trim()}</pre>
) : notes?.trim() ? (
<PluginMarkdown text={notes} className={styles.notes} />
) : (
<p className={styles.muted}>
<T>This version has no release notes.</T>
@@ -775,6 +788,8 @@ function authorContacts(entries: readonly string[]) {
}
function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
const locale = useI18n((s) => s.locale);
const t = usePluginT(plugin.id);
const busy = usePlugins((s) => !!s.busy[plugin.id]);
const installing = usePlugins((s) => s.installing);
const update = useMarketUpdate(plugin);
@@ -783,6 +798,10 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
const [confirmUninstall, setConfirmUninstall] = useState(false);
const { authors, emails } = authorContacts(plugin.authors);
const author = vendorOf(authors) || plugin.publisher;
const description =
localizePluginText(null, plugin.descriptionLocales, locale) ?? (plugin.description ? t(plugin.description) : null);
const notes =
localizePluginText(null, plugin.changeNotesLocales, locale) ?? (plugin.changeNotes ? t(plugin.changeNotes) : null);
const toggle = (
<Button
variant={plugin.enabled ? "secondary" : "primary"}
@@ -800,7 +819,7 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
{plugin.error}
</div>
)}
{plugin.description && <p className={styles.description}>{plugin.description}</p>}
{description && <PluginMarkdown text={description} className={styles.description} />}
<dl className={styles.facts}>
<dt>
@@ -962,12 +981,15 @@ function InstalledDetails({ plugin }: { plugin: PluginInfo }) {
</div>
)}
</header>
<DetailTabs notes={plugin.changeNotes} overview={overview} />
<DetailTabs notes={notes} overview={overview} />
</div>
);
}
function CatalogDetails({ entry }: { entry: CatalogPlugin }) {
const locale = useI18n((s) => s.locale);
const description = localizePluginText(entry.description, entry.descriptionLocales, locale);
const notes = localizePluginText(entry.changeNotes, entry.changeNotesLocales, locale);
const contributes = entry.contributions.map((c) => `${pointTitle(c.point)}: ${c.count}`);
const overview = (
<>
@@ -976,7 +998,7 @@ function CatalogDetails({ entry }: { entry: CatalogPlugin }) {
{entry.problem}
</div>
)}
{entry.description && <p className={styles.description}>{entry.description}</p>}
{description && <PluginMarkdown text={description} className={styles.description} />}
<dl className={styles.facts}>
<dt>
<T>ID:</T>
@@ -1030,7 +1052,7 @@ function CatalogDetails({ entry }: { entry: CatalogPlugin }) {
<span className={styles.version}>{entry.version}</span>
</div>
</header>
<DetailTabs notes={entry.changeNotes} overview={overview} />
<DetailTabs notes={notes} overview={overview} />
</div>
);
}
@@ -1312,11 +1334,14 @@ function MarketDetails({
suggestedBy: string | undefined;
onInstalled: (id: string) => void;
}) {
const locale = useI18n((s) => s.locale);
const description = localizePluginText(entry.description, entry.descriptionLocales, locale);
const notes = localizePluginText(entry.notes, entry.notesLocales, locale);
const example = isExample(entry);
const { authors, emails } = authorContacts(entry.authors ?? []);
const overview = (
<>
{entry.description && <p className={styles.description}>{entry.description}</p>}
{description && <PluginMarkdown text={description} className={styles.description} />}
<dl className={styles.facts}>
<dt>
<T>ID:</T>
@@ -1419,7 +1444,7 @@ function MarketDetails({
<span>{tx`Suggested because this project has ${suggestedBy}.`}</span>
</p>
)}
<DetailTabs notes={entry.notes ?? null} overview={overview} />
<DetailTabs notes={notes} overview={overview} />
</div>
);
}
+305
Переглянути файл
@@ -0,0 +1,305 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { CatalogPlugin, MarketPlugin, PluginInfo } from "@/bindings";
import { setLocale } from "@/platform/i18n";
import { setPluginsBackend, createMemoryPluginsBackend } from "../backend";
import { usePlugins } from "../store";
import { PluginsPage } from "../PluginsPage";
import { loadPluginMarkdown, localizePluginText } from "../pluginMarkdown";
import { renderPluginMarkdown } from "../pluginMarkdownParser";
const openExternalMock = vi.fn().mockResolvedValue(undefined);
vi.mock("@/platform/openUrl", () => ({
openExternalUrl: (...args: unknown[]) => openExternalMock(...args),
}));
function makePlugin(overrides: Partial<PluginInfo> = {}): PluginInfo {
return {
id: "acme.demo",
name: "Demo Plugin",
version: "1.0.0",
description: "Plain description.",
descriptionLocales: {},
authors: ["Acme"],
homepage: null,
changeNotes: null,
changeNotesLocales: {},
icon: null,
javaAgent: null,
source: "installed",
path: "/plugins/acme.demo",
enabled: true,
status: "static",
error: null,
hasCode: false,
capabilities: [],
netHosts: [],
netSettings: [],
contributions: [],
activation: [],
warnings: [],
stats: {
activations: 0,
activationMs: 0,
calls: 0,
errors: 0,
maxCallMs: 0,
p95CallMs: 0,
slowCalls: 0,
crashes: 0,
reclaims: 0,
},
publisher: null,
previousVersion: null,
depends: [],
dependents: [],
extensionPoints: [],
...overrides,
};
}
function makeCatalog(overrides: Partial<CatalogPlugin> = {}): CatalogPlugin {
return {
id: "acme.catalog",
name: "Catalog Plugin",
version: "1.0.0",
description: "## Features\n\n- Fast\n- Safe",
descriptionLocales: { "zh-CN": "## 功能\n\n- 快速\n- 安全" },
authors: ["Acme"],
homepage: null,
changeNotes: "### 1.0.0\n\n- Initial release",
changeNotesLocales: { "zh-CN": "### 1.0.0\n\n- 首次发布" },
icon: null,
path: "/catalog/acme.catalog",
hasCode: false,
capabilities: [],
contributions: [],
problem: null,
...overrides,
};
}
function makeMarket(overrides: Partial<MarketPlugin> = {}): MarketPlugin {
return {
id: "acme.market",
name: "Market Plugin",
version: "2.0.0",
description: "See [docs](https://example.com/docs).",
descriptionLocales: { "zh-CN": "查看 [文档](https://example.com/zh)。" },
authors: ["Acme"],
publisher: "acme",
publisherName: "Acme",
download: "https://example.com/acme.market-2.0.0.oiplugin",
digest: "abc",
capabilities: [],
engine: "^1.18",
categories: ["tools"],
icon: null,
homepage: null,
notes: "- Added **Markdown** support",
notesLocales: { "zh-CN": "- 新增 **Markdown** 支持" },
downloads: 100,
featured: false,
suggest: [],
installed: null,
compatible: true,
...overrides,
};
}
describe("renderPluginMarkdown", () => {
it("renders headings, lists, code blocks, and safe links", () => {
const md = [
"## Overview",
"",
"- Feature **one**",
"- Feature `two`",
"",
"```ts",
"const x = 1;",
"```",
"",
"Read [the guide](https://example.com/guide).",
].join("\n");
const html = renderPluginMarkdown(md);
const root = document.createElement("div");
root.innerHTML = html;
expect(root.querySelector("h2")?.textContent).toBe("Overview");
expect(root.querySelectorAll("ul > li")).toHaveLength(2);
expect(root.querySelector("strong")?.textContent).toBe("one");
expect(root.querySelector("pre > code")?.textContent).toContain("const x = 1;");
const link = root.querySelector("a");
expect(link?.getAttribute("href")).toBe("https://example.com/guide");
expect(link?.getAttribute("rel")).toBe("noopener noreferrer");
});
it("strips scripts, event handlers, javascript links, and external resources", () => {
const hostile = [
"<script>window.__xss = 1</script>",
"",
'<img src="https://evil.example/tracker.png" onerror="alert(1)" />',
"",
"![badge](https://img.shields.io/badge/test-blue.svg)",
"",
'<a href="javascript:alert(1)">bad</a>',
'<a href="file:///etc/passwd">local</a>',
'<div style="background:url(https://evil.example/bg.png)" onclick="alert(1)">text</div>',
'<iframe src="https://evil.example/frame"></iframe>',
"<style>body { display: none; }</style>",
'<video src="https://evil.example/v.mp4"></video>',
].join("\n");
const html = renderPluginMarkdown(hostile);
const root = document.createElement("div");
root.innerHTML = html;
expect(root.querySelector("script")).toBeNull();
expect(root.querySelector("img")).toBeNull();
expect(root.querySelector("iframe")).toBeNull();
expect(root.querySelector("style")).toBeNull();
expect(root.querySelector("video")).toBeNull();
for (const a of root.querySelectorAll("a")) {
expect(a.getAttribute("href")).toBeNull();
}
expect(html).not.toContain("javascript:");
expect(html).not.toContain("onerror");
expect(html).not.toContain("onclick");
expect(html).not.toContain("evil.example");
expect(html).not.toContain("shields.io");
expect(root.textContent).toContain("text");
});
it("preserves single-line and multi-line plain text compatibility", () => {
const single = renderPluginMarkdown("Counts and transforms words.");
expect(single.trim()).toBe("<p>Counts and transforms words.</p>");
const multi = renderPluginMarkdown("0.3.0 — tree view\n0.2.0 — edits\n0.1.0 — initial");
const root = document.createElement("div");
root.innerHTML = multi;
expect(root.querySelectorAll("br")).toHaveLength(2);
expect(root.textContent).toContain("0.3.0 — tree view");
expect(root.textContent).toContain("0.1.0 — initial");
});
});
describe("localizePluginText", () => {
it("picks exact tag, language tag, and falls back to English base", () => {
const locales = { "zh-CN": "简体", fr: "Français" };
expect(localizePluginText("English", locales, "en")).toBe("English");
expect(localizePluginText("English", locales, "zh")).toBe("简体");
expect(localizePluginText("English", locales, "fr")).toBe("Français");
expect(localizePluginText("English", locales, "ko")).toBe("English");
expect(localizePluginText("English", {}, "zh")).toBe("English");
expect(localizePluginText(null, locales, "ko")).toBeNull();
});
});
describe("PluginsPage Markdown and locale switching", () => {
beforeEach(async () => {
openExternalMock.mockClear();
await loadPluginMarkdown();
await setLocale("en");
usePlugins.setState({
plugins: [],
catalog: [],
market: null,
marketUrl: null,
marketError: null,
loaded: false,
loading: false,
installing: false,
error: null,
catalogError: null,
busy: {},
ui: [],
});
});
afterEach(async () => {
await setLocale("en");
});
it("renders Markdown Overview and What's New and switches with UI locale", async () => {
const user = userEvent.setup();
setPluginsBackend(
createMemoryPluginsBackend([
makePlugin({
description: "## Features\n\n- **Fast** search\n- See [docs](https://example.com/en)",
descriptionLocales: {
"zh-CN": "## 功能\n\n- **快速** 搜索\n- 查看 [文档](https://example.com/zh)",
},
changeNotes: "### 1.0.0\n\n- Added `markdown` rendering",
changeNotesLocales: {
"zh-CN": "### 1.0.0\n\n- 支持 `markdown` 渲染",
},
}),
]),
);
render(<PluginsPage initialTab="installed" />);
await screen.findByRole("heading", { level: 2, name: "Demo Plugin" });
// Default English Markdown rendering in Overview
expect(screen.getByRole("heading", { level: 2, name: "Features" })).toBeInTheDocument();
const enLink = screen.getByRole("link", { name: "docs" });
expect(enLink).toHaveAttribute("href", "https://example.com/en");
await user.click(enLink);
expect(openExternalMock).toHaveBeenCalledWith("https://example.com/en");
// Switch UI language to Simplified Chinese
await act(async () => {
await setLocale("zh");
});
expect(screen.getByRole("heading", { level: 2, name: "功能" })).toBeInTheDocument();
expect(screen.getByRole("link", { name: "文档" })).toHaveAttribute("href", "https://example.com/zh");
// Switch to What's New tab (localized to "新功能" in zh) — shows Chinese release notes
await user.click(screen.getByRole("tab", { name: "新功能" }));
expect(screen.getByText(/支持/)).toBeInTheDocument();
expect(screen.getByText("markdown").tagName).toBe("CODE");
// Unsupported language falls back to English
await act(async () => {
await setLocale("fr");
});
expect(screen.getByText(/Added/)).toBeInTheDocument();
});
it("renders localized Markdown for catalog and marketplace plugins too", async () => {
const user = userEvent.setup();
const backend = createMemoryPluginsBackend([], [makeCatalog()]);
backend.marketUrl = async () => "https://example.com/index.json";
backend.market = async () => [makeMarket()];
setPluginsBackend(backend);
render(<PluginsPage initialTab="marketplace" />);
await screen.findByRole("heading", { level: 2, name: "Market Plugin" });
expect(screen.getByRole("link", { name: "docs" })).toBeInTheDocument();
await act(async () => {
await setLocale("zh");
});
await waitFor(() => expect(screen.getByRole("link", { name: "文档" })).toBeInTheDocument());
await user.click(screen.getByRole("tab", { name: "新功能" }));
expect(screen.getByText("Markdown").tagName).toBe("STRONG");
expect(screen.getByText(/新增/)).toBeInTheDocument();
});
it("renders localized Markdown for local catalog plugins", async () => {
const user = userEvent.setup();
setPluginsBackend(createMemoryPluginsBackend([], [makeCatalog()]));
render(<PluginsPage initialTab="marketplace" />);
await screen.findByRole("heading", { level: 2, name: "Catalog Plugin" });
expect(screen.getByRole("heading", { level: 2, name: "Features" })).toBeInTheDocument();
await act(async () => {
await setLocale("zh");
});
expect(screen.getByRole("heading", { level: 2, name: "功能" })).toBeInTheDocument();
await user.click(screen.getByRole("tab", { name: "新功能" }));
expect(screen.getByText("首次发布")).toBeInTheDocument();
});
});
+71
Переглянути файл
@@ -0,0 +1,71 @@
/**
* Sanitized Markdown rendering and UI-locale text selection for plugin Overview
* and What's New panels.
*/
import { useMemo, useSyncExternalStore, type MouseEvent } from "react";
import clsx from "clsx";
import { openExternalUrl } from "@/platform/openUrl";
import { pickCatalogTag } from "./pluginText";
import styles from "./PluginsPage.module.css";
type Parser = typeof import("./pluginMarkdownParser");
let parser: Parser | null = null;
let loading: Promise<Parser> | null = null;
const readyListeners = new Set<() => void>();
export function loadPluginMarkdown(): Promise<Parser> {
return (loading ??= import("./pluginMarkdownParser").then((m) => {
parser = m;
readyListeners.forEach((l) => l());
return m;
}));
}
function subscribeReady(cb: () => void) {
readyListeners.add(cb);
if (!parser) void loadPluginMarkdown().catch(() => {});
return () => void readyListeners.delete(cb);
}
/** Picks the translation matching `locale` from `locales`, falling back to `base`. */
export function localizePluginText(
base: string | null | undefined,
locales: Partial<Record<string, string>> | null | undefined,
locale: string,
): string | null {
const fallback = base ?? null;
if (!locales) return fallback;
const tags = Object.keys(locales).filter((k) => typeof locales[k] === "string");
if (tags.length === 0) return fallback;
const tag = pickCatalogTag(tags, locale);
return tag ? (locales[tag] ?? fallback) : fallback;
}
function handleLinkClick(e: MouseEvent<HTMLDivElement>) {
const link = (e.target as HTMLElement).closest("a");
if (!link) return;
e.preventDefault();
const href = link.getAttribute("href")?.trim() ?? "";
if (/^(?:https?:|mailto:)/i.test(href)) {
void openExternalUrl(href).catch(() => {});
}
}
export function PluginMarkdown({ text, className }: { text: string; className?: string }) {
const ready = useSyncExternalStore(subscribeReady, () => parser !== null);
const trimmed = text.trim();
const html = useMemo(() => (ready && parser ? parser.renderPluginMarkdown(trimmed) : null), [ready, trimmed]);
if (!trimmed) return null;
if (html === null) {
return <div className={clsx(styles.markdown, styles.markdownPlain, className)}>{trimmed}</div>;
}
return (
<div
className={clsx(styles.markdown, className)}
onClick={handleLinkClick}
dangerouslySetInnerHTML={{ __html: html }}
/>
);
}
+70
Переглянути файл
@@ -0,0 +1,70 @@
/**
* Plugin Overview / What's New: Markdown → sanitized HTML (marked + DOMPurify).
* Loaded lazily by `pluginMarkdown.tsx` so `marked` stays out of the Settings
* window's static boot graph. Follows the same security policy as the built-in
* Markdown preview: no script execution and no external resource loading.
*/
import { Marked } from "marked";
import DOMPurify from "dompurify";
const marked = new Marked({ gfm: true, breaks: true });
// Own instance so hooks never leak into other Markdown renderers.
let purifier: ReturnType<typeof DOMPurify> | null = null;
/** Only safe navigable link schemes are kept on `<a href>`. */
const ALLOWED_LINK_URI = /^(?:https?:|mailto:)/i;
/** Tags that could load external resources or alter surrounding IDE styles/forms. */
const FORBID_TAGS = [
"style",
"form",
"img",
"picture",
"source",
"video",
"audio",
"track",
"iframe",
"object",
"embed",
"link",
"base",
"meta",
];
const FORBID_ATTR = ["style", "src", "srcset", "poster", "background", "ping", "action", "formaction"];
/** Whether the webview would read `value` as an address on another host. */
const namesHost = (value: string) =>
/^(?:https?:|[\\/]{2})/i.test([...value].filter((c) => c.charCodeAt(0) > 32).join(""));
function purify(): ReturnType<typeof DOMPurify> {
if (purifier) return purifier;
const p = DOMPurify(window);
p.addHook("uponSanitizeAttribute", (node, data) => {
if (data.attrName === "href" && node.tagName === "A") {
if (!ALLOWED_LINK_URI.test(data.attrValue.trim())) data.keepAttr = false;
return;
}
if (data.attrName === "alt" || data.attrName === "title") return;
if (namesHost(data.attrValue)) data.keepAttr = false;
});
p.addHook("afterSanitizeAttributes", (node) => {
if (node.tagName === "A" && node.getAttribute("href")) {
node.setAttribute("rel", "noopener noreferrer");
}
});
purifier = p;
return p;
}
export function renderPluginMarkdown(markdown: string): string {
const html = marked.parse(markdown, { async: false }) as string;
return purify().sanitize(html, {
USE_PROFILES: { html: true },
ALLOWED_URI_REGEXP: ALLOWED_LINK_URI,
FORBID_TAGS,
FORBID_ATTR,
});
}