Skip to content

Commit 2c1fed1

Browse files
authored
feat(project): markdown.resolveReference 决定预览可跟随的链接与可加载的图片 (#37)
预览点链接、加载图片时由 Core 判定目标:http/https/mailto 链接交给系统, #锚点留在文档内,相对或 /path 文件按工作区(文档在工作区外时为文档目录)解析; 图片只放行范围内、解析符号链接后仍在范围内的现有图片文件,以及 http/https 地址。 契约同步写明请求、返回的 kind 和判定规则,并更新已过时的 Windows 客户端描述。
1 parent 3cff440 commit 2c1fed1

7 files changed

Lines changed: 602 additions & 7 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -550,7 +550,8 @@ or removing a command fails until the table changes in the same commit.
550550
| `processLifecycle.resolve` | Decide how each process or resource of one Lithe instance ends |
551551
| `processLifecycle.inventory` | Group a process snapshot of one Lithe instance into terminals, Agent tasks and background services |
552552
| `processLifecycle.settle` | Turn confirmation answers into what ends, what is kept and the updated settings |
553-
| `markdown.render` | Render and sanitizes shared Markdown |
553+
| `markdown.render` | Renders and sanitizes shared Markdown |
554+
| `markdown.resolveReference` | Decides what a link or an image of a rendered Markdown document points at |
554555
| `keymap.parseContext` | Compile a bounded boolean shortcut context (from `lithe-core-rules`) |
555556
| `keymap.evaluateContext` | Evaluate a precompiled shortcut context (from `lithe-core-rules`) |
556557
| `keymap.analyzeConflicts` | Find conflicts among the final layered shortcut bindings (from `lithe-core-rules`) |
@@ -5496,11 +5497,50 @@ embedding. Inline `<svg>` keeps its drawing elements (shapes, text, `use`,
54965497
primitives) with their geometry and presentation attributes; `script`,
54975498
`foreignObject`, `style`, the animation elements, `feImage` and the `style`
54985499
attribute are removed, and `use`/`textPath` may only reference `#id` in the
5499-
same document. Windows asynchronously requests this existing command via its
5500-
central dispatcher, discards obsolete responses and falls back to the sanitized
5501-
fragment if syntax coloring fails. Render failures are shown as localized text;
5502-
there is no frontend Markdown parser fallback. This does not promise Windows
5503-
math or diagram rendering parity.
5500+
same document. Frontends request the command off their window thread, discard
5501+
responses to an older revision of the source and show the sanitized fragment
5502+
unchanged if syntax coloring, math or diagram rendering fails. Render failures
5503+
are shown as localized text; there is no frontend Markdown parser fallback.
5504+
5505+
`markdown.resolveReference` decides what one link destination or image `src` of
5506+
a rendered document points at, so every preview follows and loads the same
5507+
things. It accepts:
5508+
5509+
```json
5510+
{
5511+
"documentPath": "/workspace/docs/guide.md",
5512+
"workspaceRoot": "/workspace",
5513+
"reference": "../assets/logo.svg?v=2",
5514+
"purpose": "resource"
5515+
}
5516+
```
5517+
5518+
`workspaceRoot` is optional. A document inside it has the workspace as its
5519+
scope; without it, or for a document outside it, the scope is the document's
5520+
folder. `reference` is the attribute exactly as the HTML holds it. `purpose` is
5521+
`link` for a click and `resource` for an image the page loads. The response is
5522+
tagged by `kind`:
5523+
5524+
| kind | purpose | fields | meaning |
5525+
| --- | --- | --- | --- |
5526+
| `external` | link | `url` | An http, https or mailto address for the system's browser or mail client |
5527+
| `remote` | resource | `url` | An http or https address with a host; the frontend downloads it under its proxy policy |
5528+
| `anchor` | link | `anchor` | A `#fragment` of the document, without `#` and percent-decoded |
5529+
| `file` | both | `path`, `mime` for a resource | A file of the machine |
5530+
| `none` | both | — | Nothing is followed or loaded |
5531+
5532+
Addresses come back normalized as a browser reads them, and a scheme-relative
5533+
`//host` address gets `https:`. Any other scheme, including `file:`, `data:`,
5534+
`javascript:` and a one-letter Windows drive, is `none`. A path drops its query
5535+
and fragment and is percent-decoded; `/path` starts at the scope's root and any
5536+
other path at the document's folder, with `.` and `..` resolved lexically. A
5537+
link's `file` is that lexical path, which need not exist. A resource's `file`
5538+
must stay inside the scope both lexically and after Core resolves symbolic
5539+
links, must be an existing regular file, and must have an image extension
5540+
(`apng`, `avif`, `bmp`, `gif`, `ico`, `jpeg`, `jpg`, `png`, `svg`, `webp`); its
5541+
`path` is canonical and `mime` names the type. Otherwise the resource is
5542+
`none`. Frontends read a resource file without following another link and do not
5543+
load what this command refuses.
55045544

55055545
Shared examples: `rust/fixtures/editor/markdown-render-v1.json`,
55065546
`markdown-html-v1.json` and `markdown-rich-content-v1.json`.

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ pub enum CoreCommand {
126126
ProcessLifecycleSettle,
127127
/// Renders and sanitizes shared Markdown (`markdown.render`).
128128
MarkdownRender,
129+
/// Decides what a link or an image of a rendered Markdown document points at
130+
/// (`markdown.resolveReference`).
131+
MarkdownResolveReference,
129132
/// Editor reducers: workbench state, text edits, find, navigation and preferences (`editor.*`).
130133
Editor(EditorCommand),
131134
/// Applies one transition to the rearrangeable workbench chrome: stripe, title bar and status bar
@@ -1184,6 +1187,7 @@ impl CoreCommand {
11841187
"processLifecycle.inventory" => Some(Self::ProcessLifecycleInventory),
11851188
"processLifecycle.settle" => Some(Self::ProcessLifecycleSettle),
11861189
"markdown.render" => Some(Self::MarkdownRender),
1190+
"markdown.resolveReference" => Some(Self::MarkdownResolveReference),
11871191
"keymap.parseContext" => Some(Self::Keymap(KeymapCommand::ParseContext)),
11881192
"keymap.evaluateContext" => Some(Self::Keymap(KeymapCommand::EvaluateContext)),
11891193
"keymap.analyzeConflicts" => Some(Self::Keymap(KeymapCommand::AnalyzeConflicts)),

‎rust/crates/core/src/runtime/dispatcher.rs‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
//! child module named after it; the remaining small families dispatch here.
55
66
use crate::project::{
7-
self, DocumentLifecycleRequest, FileReadRequest, FileWriteRequest, MarkdownRenderRequest,
7+
self, DocumentLifecycleRequest, FileReadRequest, FileWriteRequest, MarkdownReferenceRequest,
8+
MarkdownRenderRequest,
89
};
910
use crate::protocol::{CoreCommand, CoreError, CoreRequest, CoreResponse, ErrorCode, GitCommand};
1011
use lithe_github::{NormalizeResponseRequest, ParseRemoteRequest, RequestPlanRequest};
@@ -455,6 +456,24 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
455456
Err(error) => CoreResponse::failure(id, error),
456457
}
457458
}
459+
CoreCommand::MarkdownResolveReference => {
460+
match serde_json::from_value::<MarkdownReferenceRequest>(parsed.payload).map_err(
461+
|error| {
462+
CoreError::new(
463+
ErrorCode::InvalidRequest,
464+
"Invalid Markdown reference request",
465+
)
466+
.with_details(error.to_string())
467+
},
468+
) {
469+
Ok(request) => CoreResponse::success(
470+
id,
471+
serde_json::to_value(crate::project::resolve_reference(request))
472+
.expect("Markdown reference response should encode"),
473+
),
474+
Err(error) => CoreResponse::failure(id, error),
475+
}
476+
}
458477
CoreCommand::Lsp(command) => lsp::dispatch(command, id, parsed.payload),
459478
CoreCommand::NetworkProxyPolicy => {
460479
match serde_json::from_value::<lithe_network::NetworkProxyPolicyRequest>(parsed.payload)

‎rust/crates/core/src/runtime/request_trace.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ pub(crate) fn is_hot(method: &str) -> bool {
154154
"document.classifyText"
155155
| "document.lifecycle"
156156
| "markdown.render"
157+
| "markdown.resolveReference"
157158
| "workspace.classifyVisibility"
158159
| "workspace.visibilityDefaults"
159160
| "lsp.syncDocument"

‎rust/crates/core/src/tests/project.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,45 @@ fn markdown_render_command_returns_sanitized_html() {
926926
assert!(!html.contains("alert(1)"));
927927
}
928928

929+
#[test]
930+
fn markdown_resolve_reference_command_answers_links_and_resources() {
931+
let resolve = |reference: &str, purpose: &str| -> Value {
932+
let request = serde_json::json!({
933+
"id": "markdown-reference",
934+
"command": "markdown.resolveReference",
935+
"payload": {
936+
"documentPath": "/workspace/docs/guide.md",
937+
"workspaceRoot": "/workspace",
938+
"reference": reference,
939+
"purpose": purpose
940+
}
941+
});
942+
let response: Value = serde_json::from_str(&execute_json(
943+
&serde_json::to_string(&request).expect("Markdown reference request should encode"),
944+
))
945+
.expect("Markdown reference response should be JSON");
946+
assert_eq!(response["ok"], true, "{response}");
947+
response["data"].clone()
948+
};
949+
950+
assert_eq!(
951+
resolve("https://example.com", "link"),
952+
serde_json::json!({"kind": "external", "url": "https://example.com/"})
953+
);
954+
assert_eq!(
955+
resolve("#usage", "link"),
956+
serde_json::json!({"kind": "anchor", "anchor": "usage"})
957+
);
958+
assert_eq!(
959+
resolve("//example.com/a.png", "resource"),
960+
serde_json::json!({"kind": "remote", "url": "https://example.com/a.png"})
961+
);
962+
assert_eq!(
963+
resolve("javascript:alert(1)", "link"),
964+
serde_json::json!({"kind": "none"})
965+
);
966+
}
967+
929968
#[test]
930969
fn search_matches_shared_fixture_semantics() {
931970
let fixture = fixture();

‎rust/crates/project/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ pub mod files;
1616
mod history;
1717
pub mod indexing;
1818
mod markdown;
19+
mod markdown_reference;
1920
mod name_matching;
2021
pub mod name_ranking;
2122
pub mod recent_projects;
@@ -26,6 +27,7 @@ pub use document_lifecycle::*;
2627
pub use files::*;
2728
pub use history::*;
2829
pub use markdown::*;
30+
pub use markdown_reference::*;
2931
pub use search_paging::{search_page, SearchPageRequest};
3032

3133
#[cfg(test)]

0 commit comments

Comments
 (0)